Android Async doinbackaground data to onpostexecute - android

I need some help with taking results from doinbackground to onpostexecute. The results are in the form of JSONArray. I want to populate two textviews in the UI through onpostexecute. There is no error in the code but nothing happens as it seems inpostexecute is not getting called. Please help. I have looked at several similar questions here and tried many things but unable to get it to work..thanks in advance. Please note private static final String TAG_LATEST_SCORES = "cricket_scores";
class PostScores extends AsyncTask<JSONArray, Void, JSONArray> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewScoreupdatescricketActivity.this);
pDialog.setMessage("Posting LiveScore Updates..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected JSONArray doInBackground(JSONArray... args) {
String runs1 = runs.getText().toString();
String wicket1 = wicket.getText().toString();
String overs1 = over.getText().toString();
String rr1 = rr.getText().toString();
String team_name = null;
String bat1;
if (innings.isChecked() == false) {
bat1 = "1";
team_name = bat.getText().toString();
} else {
bat1 = "2";
team_name = bat.getText().toString();
}
if (rr1.equals("NA")) {
rr1 = "0";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("runs", runs1));
params.add(new BasicNameValuePair("wickets", wicket1));
params.add(new BasicNameValuePair("id", id1));
params.add(new BasicNameValuePair("overs", overs1));
params.add(new BasicNameValuePair("rr", rr1));
params.add(new BasicNameValuePair("bat", bat1));
params.add(new BasicNameValuePair("team_name", team_name));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
pDialog.dismiss();
if (success == 1) {
latest_scores = json.getJSONArray(TAG_LATEST_SCORES);
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
return latest_scores;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONArray latest_sc) {
// dismiss the dialog once done
try {
for (int i = 0; i < latest_sc.length(); i++) {
JSONObject c = latest_sc.getJSONObject(i);
String wickets = c.getString(TAG_WICKETS);
String runs = c.getString(TAG_RUNS);
score_inngs1.setText(wickets + runs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Check your brackets. After your definition of doInBackground, you have an extra bracket - that one closes off your PostScores class, so your onPostExecute method is defined as a member of whatever class is enclosing PostScores, if any.
Also, you'll need to #Override the AsyncTask methods to provide your own implementation.

Related

window leakage error not resolved after inserting data in MySQL

I am using localhost and MySQL database in my project. i have to insert data in database and then move to next intended activity. The Data is successfully added into database but after that app terminates with window leakage error in logcat.
Code:
class CreateNewCourier extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PackageDetail.this);
pDialog.setMessage("Adding Details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_no", "120"));
params.add(new BasicNameValuePair("recp_name", recp_name));
params.add(new BasicNameValuePair("recp_no", recp_no));
params.add(new BasicNameValuePair("recp_adres", recp_adres));
params.add(new BasicNameValuePair("pkg_name", pkg_name));
params.add(new BasicNameValuePair("pkg_quan", pkg_quan));
params.add(new BasicNameValuePair("pickup_adres", pickup_adres));
params.add(new BasicNameValuePair("pkg_type", pkg_type));
params.add(new BasicNameValuePair("veh_type", veh_type));
params.add(new BasicNameValuePair("Breakable", Breakable));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
// closing this screen
finish();
} else {
//failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
//dismiss the dialog once done
pDialog.dismiss();
}
Here is the solution , move this code to onPostExecute() after pDialog.dismiss();
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
// closing this screen
finish();
} else {
//failed to create product
}
and also in onDestroy of activity add pDialog.dismiss(); to avoid leakage

how can i call an new activity from onPostExecute?

protected String doInBackground(String... args) {
String myres = null;
String bot_string = args[0] ;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("question", bot_string));
JSONObject json = jsonParser.makeHttpRequest(url_pythonwebservice, "GET", params);
// Check your log cat for JSON reponse
Log.d("results: ", json.toString());
try {
myres = json.getString(TAG_BOTRESPONSE);
} catch (JSONException e) {
e.printStackTrace();
}
return myres;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(),file_url , Toast.LENGTH_LONG).show();
//Get reference to textview above in oncreate method
//bot.setText(file_url);
}
if (file_url == "Navigation"){
Intent i = new Intent(Voice.this, MapsActivity.class);
startActivity(i);
}
Toast is printing.I want to call MapsActivity.class if String file_url == "Navigaion" but this is not working if i put inside the onPostExecute. How can i call MapsActivity.class. This is a voice recognition application.
In Java, you should compare two string as,
if(string1.equals(string2))
{
// code block
}
So, for your example, you should change your code like,
if (file_url.equals("Navigation"))
{
// more code follows
}

method getText must be called from the ui thread

I am doing an application that need to send data from android to database. I am doing it using JSONParser. But I got problem when I launched the application, it doesn't send the data to the server. I got and error on "String name = inputName.getText().toString();". Here is it:
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String date = inputDate.getText().toString();
String time = inputTime.getText().toString();
String latitude = inputLatitude.getText().toString();
String longitude = inputLongitude.getText().toString();
String contacts = inputContacts.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
params.add(new BasicNameValuePair("latitude", latitude));
params.add(new BasicNameValuePair("longitude", longitude));
params.add(new BasicNameValuePair("contacts", contacts));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
As the error tells you, you cannot call getText() on a background thread. Instead, move your six getText() calls into a constructor of your AsyncTask, or possibly into an onPreExecute() callback, so the getText() calls are made on the main application thread.

save data from listview to database

I have data from listview, and I want to save it in my database, here's my code;
listResep = (ListView) findViewById(R.id.listResep);
int leng = listResep.getCount();
for(int i = 0; i < leng; i++) {
resep = listResep.getItemAtPosition(i).toString();
new inputResep().execute();
}
and for inputResep;
class inputResep extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(InputRM.this);
pDialog.setMessage("save Resep..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("rm", rm));
params.add(new BasicNameValuePair("noregis", noregis));
params.add(new BasicNameValuePair("tanggal", tglinput));
params.add(new BasicNameValuePair("pukul", pukul));
params.add(new BasicNameValuePair("ruper", ruper));
params.add(new BasicNameValuePair("kelas", kelas));
params.add(new BasicNameValuePair("profesi", profesi));
params.add(new BasicNameValuePair("kajian", resep));
params.add(new BasicNameValuePair("id_user", id_user));
params.add(new BasicNameValuePair("tglsave", tglsave));
// getting JSON Object
// Note that create product url accepts POST method
json = jsonParser.makeHttpRequest(URL_INPUT_RESEP,"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
but every time I tried to input resep, it only save last data from listview as much as data in listview, ex= listview: data1, data2, data3; save: data3, data3, data3;
Put the whole thing in a FOR LOOP, getting the size of the total views in listview and so for each loop the data will be uploaded in the database!!
after looking at #Exeptional answer, this is how I deal with it;
int leng = listResep.getCount();
Log.d("jml resep", ""+leng);
for(int i = 0; i < leng; i++) {
resep = listResep.getItemAtPosition(i).toString();
Log.d("save resep"+i, resep);
// new inputResep().execute();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("rm", rm));
params.add(new BasicNameValuePair("noregis", noregis));
params.add(new BasicNameValuePair("tanggal", tglinput));
params.add(new BasicNameValuePair("pukul", pukul));
params.add(new BasicNameValuePair("ruper", ruper));
params.add(new BasicNameValuePair("kelas", kelas));
params.add(new BasicNameValuePair("profesi", profesi));
params.add(new BasicNameValuePair("kajian", resep));
params.add(new BasicNameValuePair("id_user", id_user));
params.add(new BasicNameValuePair("tglsave", tglsave));
// getting JSON Object
// Note that create product url accepts POST method
json = jsonParser.makeHttpRequest(URL_INPUT_RESEP,"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
}
EDIT:
it works fine when I tried with emulator, then I tried install in my tablet, at first it works fine, but it didn't work when I tried to save data, so I changed it and put loop in the asyncTask:
class inputResep extends AsyncTask<String, String, String> {
/**
* Creating product
* */
protected String doInBackground(String... args) {
int leng = listResep.getCount();
Log.d("jml resep", ""+leng);
for(int i = 0; i < leng; i++) {
resep = listResep.getItemAtPosition(i).toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("rm", rm));
params.add(new BasicNameValuePair("noregis", noregis));
params.add(new BasicNameValuePair("tanggal", tglinput));
params.add(new BasicNameValuePair("pukul", pukul));
params.add(new BasicNameValuePair("ruper", ruper));
params.add(new BasicNameValuePair("kelas", kelas));
params.add(new BasicNameValuePair("profesi", profesi));
params.add(new BasicNameValuePair("kajian", resep));
params.add(new BasicNameValuePair("id_user", id_user));
params.add(new BasicNameValuePair("tglsave", tglsave));
// getting JSON Object
// Note that create product url accepts POST method
json = jsonParser.makeHttpRequest(URL_INPUT_RESEP,"POST", params);
Log.d("testinput", "4");
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
Log.d("test", "berhasil simpan resep");
} else {
// failed to create product
Log.d("test", "failed to create product ");
}
Log.d("test", "in try");
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
}
return null;
}
}
try useing this one in postexecute in forloop
protected void onPostExecute(response response) {
pDialog.dismiss();
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
}

NetworkOnMainThereadException when activating a new activity from MainActivity to display details about a list item

Whenever I run and click on a list item in my MainActivity to initiate DetailsActivity that is suppose to diaply a little more info about the selected list item(name, description) LogCat throws the following at me:
E/AndroidRuntime(678): at
com.example.myfirstapp.JSONParser.makeHttpRequest(JSONParser.java:61)
E/AndroidRuntime(678): at
com.example.myfirstapp.DetailsActivity$GetProductDetails$1.run(DetailsActivity.java:93)
Line 61(JSONParser): HttpResponse httpResponse = httpClient.execute(httpGet);
Line 93(DetailsActivity): JSONObject json = jsonParser.makeHttpRequest(
url_car_details, "GET", params);
DetailsActivity:
package com.example.myfirstapp;
/*
* ...imports...
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
JSONParser:
package com.example.myfirstapp;
/*
* ...imports...
*/
public class DetailsActivity extends Activity {
TextView lblTitle;
TextView lblDesc;
String id;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_car_details = "http://10.0.2.2/webservice/get_car_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CAR = "car";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
id = i.getStringExtra(TAG_ID);
// Getting complete product details in background thread
new GetProductDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DetailsActivity.this);
pDialog.setMessage("Loading car details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_car_details, "GET", params);
// check your log for json response
Log.d("Single Car Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_CAR); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
lblTitle = (TextView) findViewById(R.id.lblTitle);
lblDesc = (TextView) findViewById(R.id.lblDesc);
// display product data in EditText
lblTitle.setText(product.getString(TAG_NAME));
lblDesc.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
What Luksprog said, this is missing the point:
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
Move the code that needs to update the UI to onPostExecute(). Basically save the retrieved data in a variable and "return" it.
Chnage your code as:
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DetailsActivity.this);
pDialog.setMessage("Loading car details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_car_details, "GET", params);
// check your log for json response
Log.d("Single Car Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_CAR); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// updating UI from Background Thread
DetailsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// product with this pid found
// Edit Text
lblTitle = (TextView) findViewById(R.id.lblTitle);
lblDesc = (TextView) findViewById(R.id.lblDesc);
// display product data in EditText
lblTitle.setText(product.getString(TAG_NAME));
lblDesc.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
Second solution is remove runOnUiThread from doInBackground and move all Ui elememts inside onPostExecuteof AsyncTask. because onPostExecute get called when doInBackground done given task completely and you are able to access all UI elements inside onPostExecute

Categories

Resources