1

I've have tried many method from Stack Overflow on how to retrieve the php value to android app but no success. I have no idea what's wrong here. Can someone figure out the problem for me? or at least a link/ hint ?

Firstly, I'm call addInformation(name, weather, date2, status, first1[1], last1[1]); //to insert the data into MySQL through php.

Then showList (); // show the lastID from php

Finally display it Toast.makeText(getApplicationContext(),"aa"+lastID,Toast.LENGTH_LONG).show();

 addInformation(name, weather, date2, status, first1[1], last1[1]); showList(); Toast.makeText(getApplicationContext(),lastID,Toast.LENGTH_LONG).show(); 

I declared the lastID as global.

This is my addInformation function

 public void addInformation(final String name, final String weather, final String date2, final String status, final String timeIn, final String timeOut) { class AddInfo extends AsyncTask<String, Void, String> { ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(WorkDetailsTable.this, "Please Wait", null, true, true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(String... params) { HashMap<String, String> data = new HashMap<String, String>(); data.put(Config.KEY_USER_NAME, name); data.put(Config.KEY_WEATHER, weather); data.put(Config.KEY_DATE, date2); data.put(Config.KEY_STATUS, status); data.put(Config.KEY_TIMEIN, timeIn); data.put(Config.KEY_TIMEOUT, timeOut); RequestHandler rh = new RequestHandler(); String result = rh.sendPostRequest(Config.ADD_INFORMATION, data); return result; } } AddInfo ru = new AddInfo(); ru.execute(name, weather, date2, status, timeIn, timeOut); } 

addInformation.php

<?php require_once('dbConnect.php'); if($_SERVER['REQUEST_METHOD']=='POST'){ $response = array(); //Getting values $name = $_POST['name']; $weather = $_POST['weather']; $date = $_POST['date']; $status = $_POST['status']; $timeIn = $_POST['timeIn']; $timeOut = $_POST['timeOut']; //Creating an sql query $sql = "INSERT INTO information(name, weather, date, status, time_in, time_out) VALUES ('$name','$weather','$date', '$status', '$timeIn', '$timeOut')"; //Importing our db connection script require_once('dbConnect.php'); //Executing query to database if(mysqli_query($con,$sql)){ echo 'Information Added Successfully'; $insertId= mysqli_insert_id($con); $response["lastId"]=$insertId; echo json_encode($response); }else{ echo 'Could Not Add Information'; } //Closing the database mysqli_close($con); } ?> // I get Information Added Successfully follow by the latest ID 

Next, go to showList() to get the latestID by using the same php script.

 public void showList() { class GetLastID extends AsyncTask<Void, Void, String> { private ProgressDialog progressDialog = new ProgressDialog(WorkDetailsTable.this); InputStream inputStream = null; String result = ""; protected void onPreExecute() { progressDialog.setMessage("Downloading your data..."); progressDialog.show(); progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { GetLastID.this.cancel(true); } }); } @Override protected String doInBackground(Void... params) { String url_select = "http://192.168.107.115/Android/CRUD/addInformation.php"; // same php in addInformation, get the latestID and return to android app ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); try { // Set up HTTP post // HttpClient is more then less deprecated. Need to change to URLConnection HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // Read content & Log inputStream = httpEntity.getContent(); } catch (UnsupportedEncodingException e1) { Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show(); //Log.e("UnsupportedEncodingException", e1.toString()); //e1.printStackTrace(); } catch (ClientProtocolException e2) { Toast.makeText(getApplicationContext(), "ERROR 1", Toast.LENGTH_LONG).show(); //Log.e("ClientProtocolException", e2.toString()); // e2.printStackTrace(); } catch (IllegalStateException e3) { Toast.makeText(getApplicationContext(), "ERROR 2", Toast.LENGTH_LONG).show(); // Log.e("IllegalStateException", e3.toString()); // e3.printStackTrace(); } catch (IOException e4) { Toast.makeText(getApplicationContext(), "ERROR 3", Toast.LENGTH_LONG).show(); // Log.e("IOException", e4.toString()); //e4.printStackTrace(); } // Convert response to string using String Builder try { BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); result = sBuilder.toString(); JSONObject resultObject = new JSONObject(result); lastID = resultObject.getString("lastId"); // get the latestID from php Log.e("TAG",lastID); } catch (Exception e) { Log.e("TAG", "A"); } return result; } } } 

I suppose the Toast will display the latest ID, but it display null instead.

Edited

addInformation()

 @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); showList(); 

showList()

 public void showList() { class GetLastID extends AsyncTask<Void, Void, String> { private ProgressDialog progressDialog = new ProgressDialog(WorkDetailsTable.this); InputStream inputStream = null; String result = ""; ProgressDialog loading; protected void onPreExecute() { progressDialog.setMessage("Downloading your data..."); progressDialog.show(); progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { GetLastID.this.cancel(true); } }); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(),"aa"+lastID,Toast.LENGTH_LONG).show(); } 
0

2 Answers 2

1

Update php code

//Executing query to database if(mysqli_query($con,$sql)){ // echo 'Information Added Successfully'; // Remove this line $insertId= mysqli_insert_id($con); $response["lastId"]=$insertId; echo json_encode($response); }else{ echo 'Could Not Add Information'; } 

And use this class

public class AddInfo extends AsyncTask<String, Void, ContentValues> { private final Context context; private final ProgressDialog loading; public AddInfo(Context context) { this.context = context; } private ContentValues handleActionSend(String name, String weather, String date2, String status, String timeIn, String timeOut) { ContentValues retour = new ContentValues(); retour.put("success", false); try { HttpPost post = new HttpPost(Config.ADD_INFORMATION); post.addHeader("Accept", "application/json"); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair(Config.KEY_USER_NAME, name)); postParams.add(new BasicNameValuePair(Config.KEY_WEATHER, weather)); postParams.add(new BasicNameValuePair(Config.KEY_DATE, date2)); postParams.add(new BasicNameValuePair(Config.KEY_STATUS, status)); postParams.add(new BasicNameValuePair(Config.KEY_TIMEIN, timeIn)); postParams.add(new BasicNameValuePair(Config.KEY_TIMEOUT, timeOut)); post.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8)); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } JSONObject json = new JSONObject(result.toString()); retour.put("success", true); retour.put("lastId", json.getInt("lastId")); } catch (MalformedURLException e) { retour.put("message", "MalformedURLException Error: " + e.getLocalizedMessage()); } catch (UnsupportedEncodingException e) { retour.put("message", "UnsupportedEncodingException Error: " + e.getLocalizedMessage()); } catch (IOException e) { retour.put("message", "IOException Error: " + e.getLocalizedMessage()); } catch (Exception e) { retour.put("message", "Exception Error: " + e.getLocalizedMessage()); } return retour; } @Override protected ContentValues doInBackground(String... args) { loading = ProgressDialog.show(context, "Please Wait", null, true, true); return handleActionSend(args[0], args[1], args[2], args[3], args[4], args[5]); } @Override protected void onPostExecute(ContentValues contentValues) { super.onPostExecute(contentValues); loading.dismiss(); String message; if(contentValues.getAsBoolean("success")) { message = "Inserted successfully: "+ contentValues.getAsInt("lastId"); } else { message = "An error has occured!\n"+ contentValues.getAsString("message"); } Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } } 

And call it

public void addInformation(final String name, final String weather, final String date2, final String status, final String timeIn, final String timeOut) { AddInfo ru = new AddInfo(this); ru.execute(name, weather, date2, status, timeIn, timeOut); } 
Sign up to request clarification or add additional context in comments.

7 Comments

contentValues.getAsInt("lastId"); is the lastId from php ?
Yes got from here retour.put("lastId", json.getInt("lastId"));. json contains the return of php code. First we get that value and put it in the result of the task which is a content value.
Process: com.example.project.myapplication, PID: 31014 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.<init>(Handler.java:200)
It is caused by the ProgressDialog. You can remove it and try using a toast instead or declare AddInfo class as internal to your activity and show progress dialog while loading and hide it after job done.
I get An Error has occured Excertion error : No value for success
|
1

You probably have json exceptions in your logcat, in your php you have:

 //Executing query to database if(mysqli_query($con,$sql)){ echo 'Information Added Successfully'; $insertId= mysqli_insert_id($con); $response["lastId"]=$insertId; echo json_encode($response); }else{ echo 'Could Not Add Information'; } 

so you echo no json strings like 'Information Added Successfully' - your json parser will fail on it and throw exception. You should only return what json_encode returns. If you have errors in your php script (like wrong input data, etc.), then put them into json also.

6 Comments

How can I return it to android variable(lastID) ?
for example: echo json_encode(array('lastId'=>$insertId));. But your current json code in php is OK, the problem is that you should not return anything else. Put a Toast in place of Log.e("TAG", "A"); , it should show indicating exception in parsing you json.
@JohnJoe there might be other problems in your code, ie. you should not show Toast-s in your doInBackground, do it inside onPostExecute - all your UI updates do inside onPostExecute. You can change GUI only from UI thread, onPostExecute is executed on UI thread, while doInBackground is executed on worker thread.
A little bit confused here. Inside showList don't have onPostExecute
@JohnJoe onPostExecute is a method from AsyncTask, you should override it inside your GetLastID class.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.