I want to connect mysql database locally with android emulator. I used http GET and POST methods for accessing data from Google Cloud SQL with app engine but i want to connect it with locally using phpmyadmin..
when i use following code it show Toast for connection failed
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","Hammad"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/myApp/read_data.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("user_id")+
", Username: "+json_data.getString("username")+
", Name: "+json_data.getInt("name")+
", City: "+json_data.getInt("city")
);
Toast.makeText(getApplicationContext(), "JsonArray pass", Toast.LENGTH_SHORT).show();
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}
}
If you're running this within the emulator localhost:3306 won't work. Replace that with the IP address of the machine running MySQL. So for example if your local dev machine (running MySQL) uses IP 192.168.0.10, change that to 192.168.0.10:3306.
Just to expand a bit - when you attempt to access http://localhost:3306 within the emulator (or even on a device) it tries to connect to the port 3306 on the loopback address (on the emulator/device). You obviously don't have the SQL service running on the android so this doesn't make sense.
Also, depending on your OS configuration, you may have to open port 3306 in your firewall.
Edit: Warren's tip (below) leads me to the details in the Android docs. May want to stick with 10.0.2.2 if you don't want to mess around with your OS' firewall.
Related
I'm trying to get info from the API of Google Places for an Android application. To do that, first I have enabled this API in my Google Account.
Second, I have created an API KEY for Browser. I already have an API KEY Server due to another API.
So, in my code I have been tested with these two Keys and with both I've got always the same result!!!
{
"error_message" : "This service requires an API key.",
"html_attributions" : [],
"results" : [],
"status" : "REQUEST_DENIED"
}
The code that I'm using to make the call are ...
#Override
protected String doInBackground(LocationService... ls) {
JSONObject result = new JSONObject();
URL url;
HttpsURLConnection urlConnection;
// Making HTTP request
try {
//Define connection
url = new URL("https://maps.googleapis.com/maps/api/place/nearbysearch/json");
urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("charset", "utf-8");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
//Send data
String parameters = "?location=" + String.valueOf(ls[0].getLocation().getLatitude()) + "," + String.valueOf(ls[0].getLocation().getLongitude());
parameters+="&radius=5000";
parameters+="&types=restaurant|health|city_hall|gas_station|shopping_mall|grocery_or_supermarket";
parameters+="&sensor=false";
parameters+="&key=" + Constants.API_KEY_BROWSER_APPLICATIONS;
byte[] postData = parameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
urlConnection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
DataOutputStream data = new DataOutputStream(urlConnection.getOutputStream());
data.write(postData);
data.flush();
data.close();
Log.d(TAG, "Datos enviados");
Log.d(TAG, "ResponseCode: " + String.valueOf(urlConnection.getResponseCode()));
//Display what returns POST request
StringBuilder sb = new StringBuilder();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
String json;
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
//System.out.println(""+sb.toString());
Log.d(TAG, "json: " + sb.toString());
FileService file = new FileService();
file.writeLog(POIActivity.TAG, getClass().getName(), POIActivity.urlConnection + parameters);
file.writeLog(POIActivity.TAG, "doInBackground", sb.toString());
// Parse the String to a JSON Object
result = new JSONObject(sb.toString());
}else{
//System.out.println(urlConnection.getResponseMessage());
Log.d(TAG, "urlConnection.getResponseMessage(): " + urlConnection.getResponseMessage());
result = null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d(TAG, "UnsuppoertedEncodingException: " + e.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "Error JSONException: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "IOException: " + e.toString());
}
// Return JSON Object
return result.toString();
}
When I make the call to the API I've got like ResponseCode = 200 and the call that I build is finally like that ...
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=38.26790166666667,-0.7052183333333333&radius=5000&types=restaurant|health|city_hall|gas_station|shopping_mall|grocery_or_supermarket&sensor=false&key=API_KEY
Remember, like API_KEY I have used both, Api Key for server applications and Api Key for browser applications and I've got the same result with both.
Sincerely, I'm desperate with this problem because I don't know what I am doing wrong!!!
The problem is that you are not using the Google Places API for Android, you are using the Google Places API Web Service.
Here is an example of using Google Places API for Android, and here is an example of using the Google Places API Web Service. You are definitely using the latter.
Enable the Google Places API Web Service and it will work:
If you go to this link while signed into your Google Cloud Console account:
https://console.cloud.google.com/apis/library?filter=category:maps
This is the API that should be enabled:
From the documentation:
Note: You need an Android API key, not a browser key. You can use the same API key for your Google Maps Android API v2 apps and your Google Places API for Android apps.
Check this for more help.
For an easier way try latest GCM configuration file implementation and easily create project using their developer interface.
Enable Google services for your app
When downloading a JSON array, it cuts off 1/4 of the way through the string, its pretty huge - but it should get the entire string.
There are no errors thrown in the LogCat. This is the method I am using, I have been through it a few times and cant see a reason why it is cutting off. I am pretty new to this however.
public static JSONArray getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try {
Log.d("log_tag", "jresult: " + result + "finish");
jArray = new JSONArray(result);
//Log.e("log_tag", "result: " + jArray.toString());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
I think once this is cracked I will be set. I will make this a class to use in future projects too so I dont have to keep rebuilding it!
EDIT: For loop where markers should be added to map:
try{
for(int i=0;i<arrayResultFromURL.length();i++){
JSONObject json_data = arrayResultFromURL.getJSONObject(i);
// assign attributes from the JSON string to local variables
String id =json_data.getString("id");
String title =json_data.getString("title");
String strap =json_data.getString("strap");
Double lat = (double) json_data.getDouble("lat");
Double lon = (double) json_data.getDouble("long");
theMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.title(title)
.snippet(strap));
}
}catch (Exception e){
Log.e("log_tag", "error in array: " + e.toString());
}
Maybe your problem comes from the way your are treating the response object. Check this thread.
If not try to check the size of the response first to see if you are receving all.
httpResponse.getEntity().getContentLength()
Also just in case you didn't know there is a nice library (i've been using it since i found it) that simplifies json parsing ckeck it out here.
These type of things can best be done by libraries such as GSON or Jackson
Also, if your goal is to create a JSONArray, there is a constructor that takes in a JSONTokener. JSONTokener can in turn be constructed from your InputStream.
I'm trying to program a Login-System for Android (in Eclipse) and have to get the data from an external MySQL-DB.
Source I took the code for it: Connecting to MySQL Database
The Website I'm trying to fetch the data from is here.(I know there are some safety issues, blabla, this is not my problem right now^^)
The Problem I have, is when I try to run the Application, The Error "No Password found".
This Error is catched within this Code:
ArrayList<String> passwort = new ArrayList<String>();
ArrayList<String> benutzer = new ArrayList<String>();
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
passwort.add(json_data.getString("pw"));
benutzer.add(json_data.getString("benutzer"));
}
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("arrayBenutzerExtra", benutzer);
intent.putExtra("arrayPasswortExtra", passwort);
startActivity(intent);
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Password found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
As addition, here is the code where I connect with the website, but it doesn't seem to be the problem, though I don't get an error message about that!
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://winklermarkus.at/appconnection.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
The Code of the .php file is here:
$sql_pw = "SELECT ". "Passwort ". "FROM ". "benutzerdaten ";
$result_pw = mysql_query ($sql_pw);
$data_pw = mysql_fetch_array ($result_pw);
$pw = $data_pw["Passwort"];
$sql_benutzer = "SELECT ". "Email ". "FROM ". "benutzerdaten ";
$result_benutzer = mysql_query ($sql_benutzer);
$data_benutzer = mysql_fetch_array ($result_benutzer);
$benutzer = $data_benutzer["Email"];
print(json_encode($pw));
print(json_encode($benutzer));
mysql_close();
?>
as Perception mentioned, I don't get valid JSON output, could this possibly be in relation with me, trying to transmit 2 strings at once?
Your PHP code is not doing what you think it's doing. I cannot recommend a fix to it as you've created a significant security hole.
As an alternative strategy, instead of sending all the passwords and all the emails to the client (in an unassociated fashion no less), send the clients hashed password and email to the service (over SSL). Then on the service side query if you have the combination of email/pass in the database. If you do return login success, otherwise return login failed.
In my Android app, I am accessing a website using GET requests to its API. The request returns an HTML file with a variety of user information. From this, I want to know how to extract user data, such as their profile pictures, their data and such. I would like to know how I could access and retrieve this data to display in my app.
Any help will be greatly appreciated.
Thanks in advance.
If you just want to be able to access the data you could get the api to output in in JSON format and read the JSON from your app, something like:
public void getData(){
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/download.html");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
names.add(" " + json_data.getString("name"));
age.add(" " + Integer.toString(json_data.getInt("age")));
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
The easiest way to go for HTML Parsing to extract and manipulate the data then go for JSoup......
See this link for more details:
http://jsoup.org/
The simplest way would be to display the HTML data in a WebView.
Hi am trying to get data from php script in json. I get few errors: first is variable is not resolved. If I try to add new variable like below, then after running app I get error which says Error with converting. It's mainly a tutorial code but there as I said before is a problem with IS variable. Can you help me?
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
InputSteam is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/bandymas/getAllPeopleBornAfter.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
I suspect the simple typo in the InputStream declaration might be a place to start.