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();
}
}
Related
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
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 have two things in my project first is login page which extended with Activity and to check username and password I am using following json {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}.
Now second thing is I am using navigation drawer which is extended with Activity and it uses different Fragment file,now after user log in successfully first fragment will display in which I want to parse some data in List view and for that I am using following json {"matching":[{"name":"Dynamic Street","profile_id":"","image":"path"}]}.So the problem is I need to use user login id 2650 to parse data in List view and want to send it with request in my http URL.
public class LoginPage extends Activity implements OnClickListener{
private Button btn;
private EditText user;
private EditText pass;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
private Button btn1;
private static final String LOGIN_URL = "http://XXXXX/login";
private static final String TAG_SUCCESS = "status";
private static final String TAG_LOGIN = "login";
private static final String TAG_USERID="user_login_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
user=(EditText)findViewById(R.id.loginmailid);
pass=(EditText)findViewById(R.id.loginpwd);
btn=(Button)findViewById(R.id.login);
btn1=(Button)findViewById(R.id.btnreg);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.btnreg:
Intent i = new Intent(this, RegistrationForm.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
LOGIN_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_SUCCESS);
}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 product deleted
pDialog.dismiss();
if(file_url.equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
for fragment class check this https://stackoverflow.com/questions/26816016/how-to-parse-json-data-from-server-using-fragment
You can send the LOGIN_ID value from Activity as:
Bundle bundle = new Bundle();
bundle.putString("LOGIN_ID", value);
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment get value in onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
return inflater.inflate(R.layout.fragment, container, false);
}
Edit :
Remove return line, check this code :
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
new LoadAlbums().execute();
return rootView;
}
You dont need NameValuePairs. remove below lines.
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
create another object.
JsonObject request = new JsonObject();
request.put("email", username));
request.put("password", password));
request.put("version", "apps"));
You can also add ID in it request.put("ID", ID_VALUE));
ask server developer format of request he will let you know exact format he is parsing on server.
change the code,
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected JsonObject doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
LOGIN_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return jobj;
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_SUCCESS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(JsonObject file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(jobj.getString("status").equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", jobj.getString("user_login_id"));
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
JSONObject object = new JSONObject();
object.put("email", username);
object.put("password", password);
object.put("version", "apps");
String dat = object.toString();
JSONObject object1 = new JSONObject();
object1.put("userAuthentication", object);
String dat1 = object1.toString();
httppost.setEntity(new StringEntity(dat1, HTTP.US_ASCII));
httppost.setHeader("Content-type", "application/json;" + HTTP.UTF_8);
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(result!=null) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
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());
}
}