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
Related
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.
i have just now published my app on google play store. I'm sure that the apk is well written and compiled, without any crashes. Unfortunally after i've published it on the store in beta-version it crashes on the FIRST asynctask. This is my log:
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.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at it.mybow.SaronnoCity.Login.RegStep3$Senddata.doInBackground(RegStep3.java:358)
at it.mybow.SaronnoCity.Login.RegStep3$Senddata.doInBackground(RegStep3.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
... 4 more
And this is the class of the mysterious error:
class Senddata extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Registrazione in corso...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
int success;
MyApplication application;
application = (MyApplication) getActivity().getApplicationContext();
//String regId = application.getGCMId();
String regId = "Appenaregistrato";
String nome = application.getnome();
String sesso = application.getsesso();
String email = application.getemail();
String username = application.getusername();
String password = application.getpassword();
String telefono = application.gettelephone();
//Log.d("regId", regId);
try {
Log.d("regId", regId);
Log.d("nome", nome);
Log.d("sesso", sesso);
Log.d("email", email);
Log.d("username", username);
Log.d("password", password);
Log.d("telefono", telefono);
//Aggiungo i parametri generati dalle variabili
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("registration_id", regId));
params.add(new BasicNameValuePair("nome", nome));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("sesso", sesso));
params.add(new BasicNameValuePair("telefono", telefono));
Log.d("request!", "starting");
//Utilizzo JSON per mandare i dati delle variabili
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// Line 358 ERROR
Log.d("Login attempt", json.toString());
//Se va tutto bene...
success = json.getInt(TAG_SUCCESS);
if (success == 3) {
Log.d("User Created!", json.toString());
getActivity().finish();
return json.getString(TAG_MESSAGE);
}if(success == 0){
Log.d("Inserire tutti i campi!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
if (success == 1) {
Log.d("L'username scelto รจ gia in uso", json.toString());
return json.getString(TAG_MESSAGE);
}if(success == 2){
Log.d("Operazione fallita!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
//Funzione dismiss
pDialog.dismiss();
if (file_url != null){
Toast.makeText(getActivity(), file_url, Toast.LENGTH_LONG).show();
}
}
};
So two thinks make all this very strange:
1) why does my app crash after been published, while the apk does not?
2) why it crashes not on a specific asyntask, but in general on the first called?
Thanks to all.
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.
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());
}
}
I am working in android platform and want to send some signup details to a php page for that i created an activity named as 'ContinueRegister' it contains an AsyncTask class. while running my project it shows unfortunately has stopped and there is some errors in logcat like
Activity com.opz.ContinueRegister has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41269db8
error opening trace file: No such file or directory
at android.os.Looper.loop(Looper.java:137)
at android.os.Handler.handleCallback(Handler.java:615)
atcom.opz.ContinueRegister$CreateNewUser.onPreExecute(ContinueRegister.java:76)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at java.lang.reflect.Method.invokeNative(Native Method)
this is my class file
public class ContinueRegister extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText firstname;
EditText lastname;
EditText dob;
EditText gender;
RegisterActivity ra= new RegisterActivity();
// url to create new product
private static String url_create_product = "http://localhost/login_api/create_account.php/";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.registerfinsh);
Button bt=(Button)findViewById(R.id.btnRegister);
// Listening to Login Screen link
bt.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
new CreateNewUser().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContinueRegister.this);
pDialog.setMessage("Creating New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating User
* */
protected String doInBackground(String... args) {
String Username = ra.username.getText().toString();
String Email = ra.email.getText().toString();
String Password =ra.password.getText().toString();
firstname = (EditText)findViewById(R.id.first_name);
lastname =(EditText)findViewById(R.id.last_name);
dob =(EditText)findViewById(R.id.date_of_birth);
gender = (EditText)findViewById(R.id.gender);
String Firstname = firstname.getText().toString();
String Lastname = lastname.getText().toString();
String Dob =dob.getText().toString();
String Gender =gender.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
params.add(new BasicNameValuePair("Firstname", Firstname));
params.add(new BasicNameValuePair("Lastname", Lastname));
params.add(new BasicNameValuePair("Dob", Dob));
params.add(new BasicNameValuePair("Gender", Gender));
// getting JSON Object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created user
Intent i = new Intent(getApplicationContext(), FinishSignupActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
}
} 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();
TextView loginScreen = (TextView) findViewById(R.id.link_to_login2);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent m = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(m);
}
});
}
}
}
please help me to fix this errors
String url_create_product = "http://10.0.2.2/login_api/create_account.php/";
OR
Use your local IP Like 192.168.0.1
String url_create_product = "http://192.168.0.1/login_api/create_account.php/";
Also check your login_api folder have file which name is create_account.php
One more thing is Never Access Any view inside doinBackGround(...)
Because doinBackGround method is non-UI thread.
we must give complete url like 192.10.1.000.
you can check in windows by using localhost.but you must provide complete url in the above line.
To know ur ipaddress open cmd prompt. and type ipconfig.
Put the code for calling intent onPostexecute
going to another activity is never a background task