Android connect with php Mysql - java

I can't figure out whats wrong with this code , it's supposed to get data from php page that i created.
I'm using Eclipse with android SDK.
package com.myproject.myproject2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class EntList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entlist);
JSONArray jsonArray = null;
String jsonString = null;
StringBuilder stringBuilder = null;
InputStream inStream = null;
TextView tv = (TextView) findViewById(R.id.listtitle);
ArrayList<NameValuePair> nVPArray = new ArrayList<NameValuePair>(); //This is empty because you're asking for data
try{
//Connect to your script, and save get an object to read the data (inStream)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sawtaljabal.com/ar/android_connect/test.php"); // Be sure to replace with your actual script
post.setEntity(new UrlEncodedFormEntity(nVPArray));
HttpResponse postResponse = client.execute(post);
HttpEntity responseEntity = postResponse.getEntity();
inStream = responseEntity.getContent();
}catch(Exception e){
Log.e("Error connecting", e.getLocalizedMessage());
}
try{
//read the stream to a single JSON string
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"iso-8859-1"), 10); // iso-8859-1 is the character converter
stringBuilder = new StringBuilder();
stringBuilder.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inStream.close();
jsonString = stringBuilder.toString();
}catch(Exception e){
Log.e("Error creating JSON string", e.getLocalizedMessage());
}
try{
//Turn the JSON string into an array of JSON objects
jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = null;
for(int i=0;i< jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
//do something with the object, like String data = jsonObject.getString("KEY");
String data = jsonObject.getString("n_t");
tv.setText(data);
}
}
catch(JSONException e){
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I don't even know what to try , can u help me please, this is my first Application.

To connect php using Android
first your have to call a web service (which may be a php page returning json), call to this page should be in AsynTask class.
Then you need to parse json in right way.
You can try any good tutorial for this. Try this

If this is your first android app you may want to try cloning this project and learn with code there:
https://github.com/jgilfelt/android-jsonarrayadapter?files=1
Hope it helps.

Are you sure, the String you are getting in the response is a JSON Array. I think it should be a JSON object by which you can get the further JSON Array .
which means
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonString);
} catch (JSONException e) {
}
and then parse the JSON array from JSON Object.
Check Out this link, it might be helpful.
Also do all networking call in AsynTask or in a different thread.

Related

REST return to JSONObject without writing and reading a file

The following code I have (below) works and gets the job done just fine. But what I'd really like to do is make my REST call, internally parse(if needed), and grab/apply my JSONObject values from there without having to first write my JSON return results to a text file. Basically I'd like to get the same result with out having to Write and Read the JSON from a text file in the middle of my process.
It seems like there are several options to do this. But none I've tried so far work or are out of my grasp of understanding. There may be a simple fix to this too with in the current libraries that I'm just not aware of. Any help to show me how I could alter my code to accomplish this would be appreciated.
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Account {
public static void main(String[] args) {
File f = new File(
"/Users/name/restLog.txt");
if (!f.exists()) {
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(f);
TeeOutputStream myOut = new TeeOutputStream(System.out, fos);
PrintStream ps = new PrintStream(myOut);
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
}
try {
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
// create new getRequest
HttpGet getRequest = new HttpGet(
"http://www.asite.com");
HttpResponse response = httpClient.execute(getRequest);
// check 200 response was successful
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
// Get-Capture Complete application/JSON body response
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
// Simply iterate through JSON response and show on console.
while ((output = br.readLine()) != null) {
System.out.println(output);
JSONParser parser = new JSONParser();
Object obj = parser
.parse(new FileReader(
"/Users/name/restLog.txt"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject accountObject = (JSONObject) jsonObject
.get("account");
String email = (String) accountObject.get("email");
Long id = (Long) accountObject.get("id");
System.out.println("My id is " + id);
System.out.println("My email is " + email);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
You have to implement your own object modell to be able to parse the respone with the ObjectMapper like:
ObjectMapper mapper = new ObjectMapper();
YourObject object = mapper.readValue(response.getEntity().getContent());
This object has to contain JSON annotated fields like:
#JsonProperty("userName")
private String userName;
Then you can generate getter/setter pair for your fields. If the json property is a json array then you have to create a java list object. If you work in Java EE you even do not need the annotations, the mapping happens without the need to annotate the fields. Also have a look at Jackson.

Emulator won't execute AsyncTask.execute().get()

I have a program to download JSON Strings from a server. Things were working fine up until recently, when I try to call
jsonReader.execute(getUrl).get();
Where jsonReader is an AsyncTask to download JSON Strings and getUrl is the URL to execute. This method never gets executed, the weird thing is, it works on my phone.
Here is my code
Method which calls json string reader
private PointOfInterest getPointWithID(int id) {
String getUrl;
JSONReader jsonReader = new JSONReader();
try {
Log.d(TAG,"Trying to get ID: " + id);
getUrl = url + String.valueOf(id);
Log.d(TAG,"Trying to get json from: " + id); <-- Last Log line to get printed when run on emulator
jsonReader.execute(getUrl).get();
} catch (Exception e) {
e.printStackTrace();
}
String jsonString = jsonReader.returnJSONString();
Log.d(TAG,"Downloaded: " + jsonString);
//System.out.println("JSON: " + jsonString);
JSONResponse jsonResponse = JSONResponse.convertJSONToResponse(jsonString);
//System.out.println("JSON RESPONSE " + jsonResponse);
return jsonResponse.getPointofInterest();
}
jsonReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
/**
* Read JSON Strings
* #author Tom
*
*/
public class JSONReader extends AsyncTask <String, Void, String> {
String result;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
StringBuilder sb = new StringBuilder();
String TAG = "JSONReader";
// constructor
public JSONReader() {
result = "";
}
#Override
protected String doInBackground(String... url) {
Log.d(TAG, "Executing " + url); <--Does not get printed when run on emulator
HttpPost httppost = new HttpPost(url[0]);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
// json is UTF-8 by default i believe
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}catch(Exception e){
e.printStackTrace();
}
return result = sb.toString();
}
public String returnJSONString(){
return result;
}
}
I have tried restarting adb, making new AVD's but nothing seems to work, my only option is testing on my phone however, this is not desirable as I am developing for api 17. Thanks for your help !
There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Connect to a MySQL database from android. No indication it's working/not working...?

I've been going through two tutorials to get the code for this project of mine;
Connecting to MySQL database
Connecting Android to remote mysql via PHP and JSON
I've learnt the code up to a point since I'm still a beginner and used a lot of it at the same time. Here is what I have at the moment:
package com.android.history;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CurrentSeasonDrivers extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentseason_drivers);
}
//PARSE JSON ETC
public void parseJSON() {
String result = "";
String drivername = "";
String drivesfor = "";
InputStream is=null;
//HTTP POST REQUEST
try{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.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());
Toast.makeText(getBaseContext(), "Could not connect", Toast.LENGTH_LONG).show();
}
//CONVERT DATA 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());
Toast.makeText(getBaseContext(), "Could not convert result", Toast.LENGTH_LONG).show();
}
//PARSE JSON DATA
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
drivername=json_data.getString("Driver_full_name");
drivesfor=json_data.getString("Drives_for");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(), "Could not parse data", Toast.LENGTH_LONG).show();
}
}
}
Now I have no errors and the application works fine. When I got to the page that this is all made for I get nothing. A blank page. As you can see from my code I've added toasts exceptions but none of them show up either. Even if I intentionally close my server which is odd. Is there something else I should be doing. As the title says because the toasts are not working I have no indication if the code is actually doing anything. I just have a blank page.
I've added Internet to my manifest to allow the app access to that. If I visit the URL in my code (192.168.0.13/testdatabase.php) via my browser the data from my database shows up just fine.
Edit: The overall outcome I want from this eventually is to have some data from database displayed for my users to see. Instead of putting it in as static text and having to update the entire app just to update some data.
You need to implement your network connection on a separate thread for API level 11 or greater. Take a look on this link: HTTP Client API level 11 or greater in Android.
Also for the POST request, I think that you can use this code:
public String post(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(SERVER_ADDRESS);
StringEntity input = new StringEntity(str);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
StringBuilder result = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
String output;
while ((output = br.readLine()) != null)
result.append(output);
return result;
}

Android - Connecting to MySQL database [duplicate]

This question already has answers here:
How to connect Android with MySQL using Mysql JDBC driver [duplicate]
(2 answers)
Closed 1 year ago.
I have been trying out the tutorials shown on various websites on connecting a MySQL database to android. At the moment the code below, takes the values which you hard code in, (i.e year=2005 and name=tom) and runs it through the php script. What I would like know is how I can modify this, so that it takes the values of what the user enters in a textbox instead.
package com.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class test extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retrieval
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://***.****.com/mysqlcon.php"; //i use my real ip here
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","2005"));
nameValuePairs.add(new BasicNameValuePair("name","tom"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
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());
}
//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")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
Okay, I understand what do you want. You want to have an EditText or two in the app. The user will enter information in it and after pressing a button th information in the EditText should move into the mysql database. So, you want to make a dynamic app that inserts record into mysql. For that do the following to modify the above java code.
Insert following line below, TextView txt;
EditText editTxt;
Below rootLayout.addView(txt); insert following two lines,
editTxt = new EditText(this);
rootLayout.addView(editTxt);
Now, modify this line, nameValuePairs.add(new BasicNameValuePair("name","tom")); to fetch value from the EditText.
nameValuePairs.add(new BasicNameValuePair("name",editTxt.getText().toString()));
You can also create one for year.

Internal Server Error [duplicate]

This question already has answers here:
How to do a HTTP Post in Android?
(2 answers)
Closed 7 years ago.
I am working on an SMS Sending application and for login purpose i want to send the username and password using POST method from my Android Application to the web server.
When I click on lo-gin button the application is not responding and the console prints the following message in response of the Post request.
HTTP/1.1 500 Internal Server Error
While my application running fine with the GET method.
I am not able to figure out why this is causing...
the whole code is here:
package com.vikas.httplogin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class HttpLogin extends Activity {
TextView tv;
private static final String tag ="FATAL_ERROR";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
connecttoServer();
}
private void connecttoServer()
{
BufferedReader br = null;
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("url of my site");
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("username","vikaspatidar"));
params.add(new BasicNameValuePair("password", "patidar"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
request.setEntity(entity);
Log.v(tag,request.getMethod().toString());
HttpResponse response = client.execute(request);
Log.v(tag, response.getStatusLine().toString());
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
sb.append(line + NL);
}
br.close();
String result = sb.toString();
Log.v(tag, result);
} catch (ClientProtocolException e)
{
Log.v(tag, e.getMessage());
}
catch (IllegalStateException e) {
Log.v(tag, e.getMessage());
} catch (IOException e) {
Log.v(tag, e.getMessage());
}
}
}
That's definitely looks like server-side error, not android problem. Look at server log files.
The way you're setting parameters to request looks weird, try setting parameters like this:
HttpPost post = new HttpPost("url of my site");
BasicHttpParams basicHttpParams = new BasicHttpParams();
basicHttpParams.setParameter("username", "vikaspatidar");
basicHttpParams.setParameter("password", "patidar");
post.setParams(basicHttpParams);
//...
Here is solution for this:
How to do a HTTP Post in Android?

Categories