Pass value from Textview in dialog to Asynctask - android

i am having a problem passing values from a textview in a dialog to asynctask to add to database, here is the code:
public void addfooddialog(View v){
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.addfooddialog);
dialog.setTitle("Insert food");
dialog.setCancelable(false);
dialog.show();
Button b = (Button)dialog.findViewById(R.id.addfood);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
new add().execute();
}
});
}
and here is the class extending AsyncTask
class add extends AsyncTask<String, String, String> {
Dialog d= new Dialog(context);
#Override
protected void onPreExecute() {
super.onPreExecute();
d.setContentView(R.layout.addfooddialog);
Log.i("","ata3 men hon");
}
#Override
protected String doInBackground(String... arg0) {
TextView title= (TextView)d.findViewById(R.id.plattername);
TextView description= (TextView) d.findViewById(R.id.description);
TextView price= (TextView)d. findViewById(R.id.price);
String foodname = title.getText().toString();
String fooddescription = description.getText().toString();
String foodprice = price.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("title", foodname));
params.add(new BasicNameValuePair("description", fooddescription));
params.add(new BasicNameValuePair("price", foodprice));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_add,
"POST", params);
final String TAG_SUCCESS = "success";
// 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
Log.i("sucees","---------------------------------");
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
Now i know that the dialog is being recreated and this is why the values return to null, but how to i pass the values directly to the asynctask class?
Thank you in advance

you can create global variable that take the value from EditText and using the variable in AsyncTask class

Related

Method getText must be called form the UI thread (Error) [duplicate]

This question already has answers here:
Method getText() must be called from the UI Thread (Android Studio)
(5 answers)
Closed 6 years ago.
I'm making the register in Android Studio, and I found a problem on
String name = names. getText (). toString ();
String address = address. getText (). toString ();
String telephone = telephone. getText (). toString ();
String username = user. getText (). toString ();
String password = pass. getText (). toString ();,
Possible solutions?
Here is my Activity code:
public class ActivityRegister extends Activity implements View.OnClickListener {
private EditText user, pass, nama, alamat, telpon;
private TextView t1;
private RadioButton rb1, rb2;
private Button mRegister;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://10.0.2.2/coba/api/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Register Distro App");
nama = (EditText) findViewById(R.id.nama);
alamat = (EditText) findViewById(R.id.alamat);
telpon = (EditText) findViewById(R.id.telpon);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
rb1=(RadioButton)findViewById(R.id.option1);
rb2=(RadioButton)findViewById(R.id.option2);
t1=(TextView)findViewById(R.id.TextView01);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityRegister.this);
pDialog.setMessage("Mendaftar Member...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String namanya = nama.getText().toString();
String alamatnya = alamat.getText().toString();
String telponnya = telpon.getText().toString();
String username = user.getText().toString();
String password = pass.getText().toString();
if(rb1.isChecked() == true)
t1.setText(rb1.getText());
if(rb2.isChecked() == true)
t1.setText(rb2.getText());
if(rb1.isChecked() == false && rb2.isChecked() == false)
t1.setText("");
String jenkel = t1.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("nama", namanya));
params.add(new BasicNameValuePair("alamat", alamatnya));
params.add(new BasicNameValuePair("telpon", telponnya));
params.add(new BasicNameValuePair("jenkel", jenkel));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
Log.d("Register attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Register Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (file_url != null){
Toast.makeText(ActivityRegister.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
The reason is in AsyncTask behavior.
Methods onPreExecute(), onPostExecute are called from UI Thread.
But doInBackground() is called in separate thread.
The solution is to pass text parameters to AsyncTask#execute.
See: AsyncTask tutorial
You have a background thread but when you access UI components you have to access them through the man UI thread. You can do this by
youActivity.runOnUiThread(new Runnable() {
public void run() {
t1.setText(rb1.getText());
}
});

Pass string with button into next activity

i want to pass my id into another activity. can you show me how? i try search in google but nothing can help me. i hope that you can help me a little. i must be great if you can help me. i'm stuck with this problem for 3 days. makes me confused.
this is my code for pass :
private ProgressDialog mProgressDialog;
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
EditText inputfirstname,
inputmiddlename,
inputlastname,
inputaliasname,
inputcitybirth,
inputyearbirth;
RadioGroup gender;
RadioButton mr,mrs;
private static final String TAG_ID = "ID_Person";
private static String url_create_person ="http://172.18.0.20/person_new_xml.php";
private Spinner date,month,year;
Button saveperson,cancelperson;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.newperson);
inputfirstname = (EditText) findViewById(R.id.newfirstname);
inputmiddlename = (EditText) findViewById(R.id.newmiddlename);
inputlastname = (EditText) findViewById(R.id.newlastname);
inputaliasname = (EditText) findViewById(R.id.newaliasname);
gender = (RadioGroup)findViewById(R.id.jekel);
inputcitybirth = (EditText) findViewById(R.id.newcitybirth);
date = (Spinner) findViewById(R.id.spinnerdate);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.date_array, android.R.layout.simple_spinner_dropdown_item);
date.setAdapter(adapter);
month = (Spinner) findViewById(R.id.spinnermonth);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource
(this, R.array.month_array, android.R.layout.simple_spinner_dropdown_item);
month.setAdapter(adapter2);
year = (Spinner) findViewById(R.id.spinneryear);
ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource
(this, R.array.year_array, android.R.layout.simple_spinner_dropdown_item);
year.setAdapter(adapter3);
cancelperson = (Button) findViewById(R.id.btncancelnewperson);
saveperson = (Button) findViewById(R.id.btnsnextnewperson);
saveperson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreatePerson().execute();
}
});
}
private class CreatePerson extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Creating Product..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String select = null;
switch (gender.getCheckedRadioButtonId())
{
case R.id.mr:
select="Mr.";
break;
case R.id.mrs:
select="Mrs.";
default:
break;
}
String firstname = inputfirstname.getText().toString();
String middlename = inputmiddlename.getText().toString();
String lastname = inputlastname.getText().toString();
String aliasname = inputaliasname.getText().toString();
String city = inputcitybirth.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("FirstName", firstname));
params.add(new BasicNameValuePair("MiddleName", middlename));
params.add(new BasicNameValuePair("LastName", lastname));
params.add(new BasicNameValuePair("AliasName", aliasname));
params.add(new BasicNameValuePair("Gender", select));
params.add(new BasicNameValuePair("CityBirth", city));
params.add(new BasicNameValuePair("DateBirth", date.getSelectedItem().toString()));
params.add(new BasicNameValuePair("MonthBirth", month.getSelectedItem().toString()));
params.add(new BasicNameValuePair("YearBirth", year.getSelectedItem().toString()));
JSONObject json = jsonParser.makeHttpRequest(url_create_person, "POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
String id = ((Button) findViewById(R.id.btnsnextnewperson)).getText().toString();
Intent i = new Intent(getApplicationContext(),CreateUser.class);
i.putExtra(TAG_ID, id);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
mProgressDialog.dismiss();
}
}
}
and this is my code for receive :
private ProgressDialog mProgressDialog;
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
String ID;
//String Name;
private static final String TAG_Person = "person";
private static final String TAG_ID = "ID_Person";
TextView id;
EditText inputuser,inputpassword,inputanswer;
private Spinner question;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registeruser);
ID = getIntent().getStringExtra(TAG_ID);
id =(TextView) findViewById(R.id.textname);
inputuser = (EditText) findViewById(R.id.inputuser);
inputpassword = (EditText) findViewById(R.id.inputpassword);
inputanswer = (EditText) findViewById(R.id.inputanswer);
question = (Spinner) findViewById(R.id.questionspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.securityquestion, android.R.layout.simple_spinner_dropdown_item);
question.setAdapter(adapter);
new User().execute();
save = (Button) findViewById(R.id.savebutton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createuser().execute();
}
});
}
private class User extends AsyncTask<String, String, JSONArray>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(CreateUser.this);
mProgressDialog.setMessage("Loading products. Please wait...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected JSONArray doInBackground(String... param) {
// TODO Auto-generated method stub
JSONArray personobj = new JSONArray();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ID_Person", ID));
String url_product_detials = "http://172.18.0.20/get.php";
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
Log.d("Single Person Details", json.toString());
personobj = json.getJSONArray(TAG_Person);
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return personobj;
}
protected void onPostExecute(JSONArray personobj){
mProgressDialog.dismiss();
try {
for (int i = 0; i < personobj.length(); i++) {
JSONObject person;
person = personobj.getJSONObject(i);
String Id = person.getString("ID_Person");
id.setText(Id);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I will recommend to call the intent in onPostExecute of AsyncTask. Also store the text of the button in a string before going into doInBackground. The doInBackground is a seperate thread and can't communicate with Main UI Thread.
as berserk said,the doInBackground is a seperate thread that cant communicate with main UI Thread,so, as my recommedn,you should startActivity() in the onPostExecute.
just change to below
private class CreatePerson extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Creating Product..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
//String select = null;//member var of outside class
switch (gender.getCheckedRadioButtonId())
{
case R.id.mr:
select="Mr.";
break;
case R.id.mrs:
select="Mrs.";
default:
break;
}
String firstname = inputfirstname.getText().toString();
String middlename = inputmiddlename.getText().toString();
String lastname = inputlastname.getText().toString();
String aliasname = inputaliasname.getText().toString();
String city = inputcitybirth.getText().toString();
//List<NameValuePair> params = new ArrayList<NameValuePair>();//member var of outside class
params.add(new BasicNameValuePair("FirstName", firstname));
params.add(new BasicNameValuePair("MiddleName", middlename));
params.add(new BasicNameValuePair("LastName", lastname));
params.add(new BasicNameValuePair("AliasName", aliasname));
params.add(new BasicNameValuePair("Gender", select));
params.add(new BasicNameValuePair("CityBirth", city));
params.add(new BasicNameValuePair("DateBirth", date.getSelectedItem().toString()));
params.add(new BasicNameValuePair("MonthBirth", month.getSelectedItem().toString()));
params.add(new BasicNameValuePair("YearBirth", year.getSelectedItem().toString()));
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// JSONObject json = null//member var of outside class
json = jsonParser.makeHttpRequest(url_create_person, "POST", params);
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
if(mProgressDialog != null && mProgressDialog.isShow()){
mProgressDialog.dismiss();
}
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
String id = ((Button) findViewById(R.id.btnsnextnewperson)).getText().toString();
Intent i = new Intent(getApplicationContext(),CreateUser.class);
i.putExtra(TAG_ID, id);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

FATAL EXCEPTION : AsyncTask#5

They have mentionned that the ERROR was occured while excecuting doInBackground()
public class NewClientActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText name;
EditText login;
EditText password;
EditText rePassword;
EditText email;
EditText adresse;
EditText tel;
// url to create new product
private static String url_add_client = "http://192.168.1.3/android_connect/add_client.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity1);
// Edit Text
name = (EditText) findViewById(R.id.textViewNom);
login = (EditText) findViewById(R.id.textViewLogin);
password = (EditText) findViewById(R.id.textViewPassword);
rePassword = (EditText) findViewById(R.id.textViewPassword1);
email = (EditText) findViewById(R.id.textViewEmail);
adresse = (EditText) findViewById(R.id.textViewAdresse);
tel = (EditText) findViewById(R.id.textViewTel);
// Create button
Button btnAddClient = (Button) findViewById(R.id.connect);
// button click event
btnAddClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewClientActivity.this);
pDialog.setMessage("Adding Customer to DataBase..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Name = name.getText().toString();
String Login = login.getText().toString();
String Password = password.getText().toString();
// String RePassword = rePassword.getText().toString();
String Email = email.getText().toString();
String Adresse = adresse.getText().toString();
String Tel = tel.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Name", Name));
params.add(new BasicNameValuePair("Login", Login));
params.add(new BasicNameValuePair("Password", Password));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Adresse", Adresse));
params.add(new BasicNameValuePair("Tel", Tel));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_add_client,
"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(), AllProductsActivity.class);
// startActivity(i);
// closing this screen
// finish();
} else {
Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show(); }
} 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();
}
}
}
Please if you can check it out and tell me where the ERROR is ??
thank you in advance !!
just override into your AsyncTask the method onProgressUpdate
class CreateNewProduct extends AsyncTask<String, String, String> {
...
...
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
...
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
// startActivity(i);
// closing this screen
// finish();
} else {
publishProgress("L'inscription n'a pas été éfectuée correctement");
}
} catch (JSONException e) {
e.printStackTrace();
}
...
}
}
I believe the error is because you are trying to update the UI in the doInBackground method of the AsyncTask.
Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show();
Move the above code to postExecute.
Also the following code in doInBackground wouldn't possibly cause an error to occur
String Name = name.getText().toString();
String Login = login.getText().toString();
String Password = password.getText().toString();
String Email = email.getText().toString();
String Adresse = adresse.getText().toString();
String Tel = tel.getText().toString();
Forget ASyncTask,
Android Annotations is the better solution!
Look this:
https://github.com/excilys/androidannotations/wiki
Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show();
You are trying to update ui from the background thread ie displaying toast.
Display toast in onPostExecute() or use runonuithread
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Toast.makeText(NewClientActivity.this,"mymessage", 1000).show();
}
});
Use a activity context in place of getApplicationContext()
When to call activity context OR application context?
For more information check the link below .
http://developer.android.com/reference/android/os/AsyncTask.html

check text boxes if written android

i want your help in something
i am looking to put a code that can check if the text boxes are empty or not
if the text boxes are empty i want to show a text messg saying that informations are incomplete and if not we continue our processus
the problem that i am not knowing where should i write the if condition to check if the text boxes are empty or not
please check my code :
public class register extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputUser;
EditText inputPass;
EditText inputAge;
EditText inputBloodType;
// url to create new product
private static String url_create_product = "http://10.0.2.2/blood_needed/create_product.php" ;
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
inputName = (EditText) findViewById(R.id.editText1);
inputUser = (EditText) findViewById(R.id.editText5);
inputPass = (EditText) findViewById(R.id.editText3);
inputAge = (EditText) findViewById(R.id.editText2);
inputBloodType = (EditText) findViewById(R.id.editText4);
// Create button
Button btnRegister = (Button) findViewById(R.id.Button01);
// button click event
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(register.this);
pDialog.setMessage("Regestering..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String user = inputUser.getText().toString();
String pass = inputPass.getText().toString();
String age = inputAge.getText().toString();
String bloodtype = inputBloodType.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pass));
params.add(new BasicNameValuePair("age", age));
params.add(new BasicNameValuePair("bloodtype", bloodtype));
// 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
// 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) {
Toast.makeText(getBaseContext(), "Succes!", Toast.LENGTH_SHORT).show();
// dismiss the dialog once done
pDialog.dismiss();
}}
Put it in onClick()
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
String name = inputName.getText().toString();
String user = inputUser.getText().toString();
String pass = inputPass.getText().toString();
String age = inputAge.getText().toString();
String bloodtype = inputBloodType.getText().toString();
if(user.equals("") || pass.equals("") || age.equals("") || bloodtype.equals("") || name.equals("")){
// add message here
}else{
new CreateNewProduct().execute();
}
}
});}

Android: can't get doInBackground result in OnPostExecute method in an Asynctask

I have a problem with an Asynctask, I can't get the return values of the doInBackground method in the OnPostExecute, can you help me?
I setted the return value of the Asynctask as an Integer, and the value that I'm returning is an int, so why does the app stop on the return of the doInBackground?
If you can explain to me how the Asynctask works I will really appreciate it.
Thank you very much!!
public class LoginActivity extends Activity
{
ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
JSONArray user = null;
ArrayList<HashMap<String, String>> userList;
private static String loginURL = "htttp://example.com/query.php";
private static String KEY_SUCCESS = "success";
private static String KEY_EMAIL = "email";
private static String KEY_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
userList = new ArrayList<HashMap<String, String>>();
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
btnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new CheckUser().execute();
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class CheckUser extends AsyncTask<String, String, Integer>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Verifica dati inseriti...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected Integer doInBackground(String... args)
{
int valoreOnPostExecute = 0;
String emailInserted = inputEmail.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", emailInserted));
// getting JSON string from URL
JSONObject json = null;
json = jParser.getJSONFromUrl(loginURL, params);
// Check your log cat for JSON response
Log.d("All Users: ", json.toString());
try
{
// Checking for SUCCESS TAG
int success = json.getInt(KEY_SUCCESS);
if (success == 1)
{
// users found
// Getting Array of users
user = json.getJSONArray("utenti");
// looping through All users
for (int i = 0; i < user.length(); i++)
{
JSONObject c = user.getJSONObject(i);
// Storing each json item in variable
String email = c.getString(KEY_EMAIL);
String password = c.getString(KEY_PASSWORD);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_EMAIL, email);
map.put(KEY_PASSWORD, password);
// adding HashList to ArrayList
userList.add(map);
}
// Intent intent = new Intent(LoginActivity.this,GenereMusicale.class);
// startActivity(intent);
valoreOnPostExecute = success;
}
// else
// {
// Log.d("success != 1", json.toString());
// //Toast.makeText(LoginActivity.this, "Username/password non corretti", Toast.LENGTH_SHORT).show();
// }
}
catch (JSONException e)
{
e.printStackTrace();
Log.d("User ARRAY", "user array: "+user);
}
return valoreOnPostExecute;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int valoreOnPostExecute)
{
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
if(valoreOnPostExecute == 1)
{
Intent intent = new Intent(LoginActivity.this,GenereMusicale.class);
startActivity(intent);
}
else
{
new AlertDialog.Builder(LoginActivity.this)
.setTitle("Fine del Round!")
//.setMessage("Terminare round?")
//.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).create().show();
}
}
}
}
Your return type from doInBackground() and receiving type in onPostExecute() does not match
try like this
class CheckUser extends AsyncTask<String, String, Integer>
protected Integer doInBackground(String... args)
protected void onPostExecute(Integer valoreOnPostExecute)

Categories

Resources