save data from listview to database - android

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());
}
}

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

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.

How do i get the response in onPostExecute() AsyncTask android

I recently started working on android, now i am working with AsyncTask how can i get response which is returned from the API below is the code.Every suggestion is appreciable.
class signmeup extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(WolfActivity.this);
pDialog.setMessage("Loading");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("section","user"));
params.add(new BasicNameValuePair("action","new"));
params.add(new BasicNameValuePair("device_type","2"));
params.add(new BasicNameValuePair("device_token","dhdkhgkdfhgkhfdghkdfjhgkjdfhgkdfhkhkHKhdkhsdkhKJHKWJHDSKAHDKJSAHJKDfhkashfkdjhfkjhskjhKJHJk"));
params.add(new BasicNameValuePair("first_name",fname));
params.add(new BasicNameValuePair("last_name",lname));
params.add(new BasicNameValuePair("email",email));
params.add(new BasicNameValuePair("phone",phone));
params.add(new BasicNameValuePair("fax",fax));
params.add(new BasicNameValuePair("address",addr));
params.add(new BasicNameValuePair("address1",addr1));
params.add(new BasicNameValuePair("facility",facility));
params.add(new BasicNameValuePair("password",pwd));
params.add(new BasicNameValuePair("zip",zipcode));
params.add(new BasicNameValuePair("city",city));
params.add(new BasicNameValuePair("state",state));
params.add(new BasicNameValuePair("how_you_found",huf));
params.add(new BasicNameValuePair("how_you_found_value",hufv));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest("http://eastendwebsolutions.com/wf/ws/", "GET", params);
Log.d("First Name",fname);
Log.d("Last Name",lname);
Log.d("Email",email);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
String success = json.getString("status");
String message = json.getString("message");
if(success == "0") {
Toast.makeText(WolfActivity.this,message ,Toast.LENGTH_LONG).show();
} else {
Toast.makeText(WolfActivity.this,"Error "+message ,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#SuppressWarnings("deprecation")
//#Override
protected void onPostExecute(String Result) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
Log.d("Result",Result);
AlertDialog.Builder builder=new AlertDialog.Builder(WolfActivity.this);
builder.setTitle("Info");
builder.setMessage("Successfully registered");
builder.setIcon(R.drawable.app_icon);
builder.create().show();
}
}
Above code is terminates with error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at zonup.wolf.WolfActivity$signmeup.onPostExecute(WolfActivity.java:222)
at zonup.wolf.WolfActivity$signmeup.onPostExecute(WolfActivity.java:135)
Error because this statement Log.d("Result",Result); in function
onPostExecute(String Result)
I tried to alert the user with status in doInBackground() method but no toasts are coming:( is it correct??
Just try this way you can see the message you get in the json response.
class signmeup extends AsyncTask<String, String, String> {
String message="";
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(WolfActivity.this);
pDialog.setMessage("Loading");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("section","user"));
params.add(new BasicNameValuePair("action","new"));
params.add(new BasicNameValuePair("device_type","2"));
params.add(new BasicNameValuePair("device_token","dhdkhgkdfhgkhfdghkdfjhgkjdfhgkdfhkhkHKhdkhsdkhKJHKWJHDSKAHDKJSAHJKDfhkashfkdjhfkjhskjhKJHJk"));
params.add(new BasicNameValuePair("first_name",fname));
params.add(new BasicNameValuePair("last_name",lname));
params.add(new BasicNameValuePair("email",email));
params.add(new BasicNameValuePair("phone",phone));
params.add(new BasicNameValuePair("fax",fax));
params.add(new BasicNameValuePair("address",addr));
params.add(new BasicNameValuePair("address1",addr1));
params.add(new BasicNameValuePair("facility",facility));
params.add(new BasicNameValuePair("password",pwd));
params.add(new BasicNameValuePair("zip",zipcode));
params.add(new BasicNameValuePair("city",city));
params.add(new BasicNameValuePair("state",state));
params.add(new BasicNameValuePair("how_you_found",huf));
params.add(new BasicNameValuePair("how_you_found_value",hufv));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest("http://eastendwebsolutions.com/wf/ws/", "GET", params);
Log.d("First Name",fname);
Log.d("Last Name",lname);
Log.d("Email",email);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
String success = json.getString("status");
message = json.getString("message");
if(success == "0") {
Toast.makeText(WolfActivity.this,message ,Toast.LENGTH_LONG).show();
} else {
Toast.makeText(WolfActivity.this,"Error "+message ,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
message=e.toString();
e.printStackTrace();
}
return message;
}
#SuppressWarnings("deprecation")
//#Override
protected void onPostExecute(String Result) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
Log.d("Result",Result);
AlertDialog.Builder builder=new AlertDialog.Builder(WolfActivity.this);
builder.setTitle("Info");
builder.setMessage(Result);
builder.setIcon(R.drawable.app_icon);
builder.create().show();
}
}

putting data from editText into a table

I am a beginner in android, I make tables in eclipse, and I want to retrieve the information entered by the user to put it in a table named user when pressing on the button REGISTER
What code should I wrote to do that ?
params.add(new BasicNameValuePair("mobile_number", number));
params.add(new BasicNameValuePair("password", pwd));
params.add(new BasicNameValuePair("hint", h));
params.add(new BasicNameValuePair("email_id", id));
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
flag=0;
Intent i = new Intent(getApplicationContext(),Welcome.class);
i.putExtra("mobile_number",number);
i.putExtra("password",pwd);
startActivity(i);
finish();
}
else
{
// failed to Sign in
flag=1;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;

Android Async doinbackaground data to onpostexecute

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.

Categories

Resources