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
Related
my app crash when execute asynctask. I try to send data from android to the server but my app crashes when execute AsyncTask
` input input = new input();
input.execute();
mainActivity = this;
latitude = "-6.711647";
longitude ="108.5413";`
public class input extends AsyncTask<String, String, String>
{
HashMap<String, String> user = db.getUserDetails();
String email = user.get("email");
String success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Sending Data to server...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
String strEMAIL = email.toString();
String strNama = latitude.toString();
String strProdi = longitude.toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", strEMAIL));
params.add(new BasicNameValuePair("latitude", strNama));
params.add(new BasicNameValuePair("longitude", strProdi));
JSONObject json = jParser.makeHttpRequest(url, "POST", params);
try {
success = json.getString("success");
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_LONG).show();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if (success.equals("1"))
{
Toast.makeText(getApplicationContext(), "kirim data Sukses!!!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "kirim data Gagal!!!", Toast.LENGTH_LONG).show();
}
}
}
this my complete code http://pastebin.com/jRdxeQKG
and this my logcat http://prntscr.com/7p3vbz
The reference db is null when you call new input() in onCreate().
Solution: Just initialize db before calling new input():
db = new SQLiteHandler(getApplicationContext());
input input = new input();
By the way, there are many issues from the design point of view, but this will solve (one of) the crash(es).
1 Starting the name of your class with a lowercase letter is bad practice.input should be Input and should be a little more descriptive.
2 Your db initialization should come before the call to execute AsyncTask
3 You need to really understand AsyncTask before using it. You declare three generic types for your AsyncTask
public class input extends AsyncTask<String, String, String> {
but none of them is used. Your doInBackground method should be returning an instance of type NameValuePair or JSONObject.
The first generic type of an AsyncTask is the params, that is what you intend to pass to your doInBackground method. You say it's String but do not pass in any String in input.execute(); This is not a problem right now because you haven't attempted to use args0, but your app will crash if you try to. I just think you should really read about AsyncTask first and understand the basics.It will save you a whole lot of trouble.Cheers.
Hi I am building a login app in where the details of the users will be shown using JSON PHP and MYSQL but whenever the profile would show up it crashes what Am I doing wrong? What's weird is that this was working few days ago
logcat report
10-05 18:55:34.088: E/AndroidRuntime(3173): FATAL EXCEPTION: main
10-05 18:55:34.088: E/AndroidRuntime(3173): java.lang.NullPointerException
10-05 18:55:34.088: E/AndroidRuntime(3173): at com.example.itmaproject.EditContactsActivity$GetProductDetails$1.run(EditContactsActivity.java:144)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.os.Handler.handleCallback(Handler.java:725)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.os.Handler.dispatchMessage(Handler.java:92)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.os.Looper.loop(Looper.java:137)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-05 18:55:34.088: E/AndroidRuntime(3173): at java.lang.reflect.Method.invokeNative(Native Method)
10-05 18:55:34.088: E/AndroidRuntime(3173): at java.lang.reflect.Method.invoke(Method.java:511)
10-05 18:55:34.088: E/AndroidRuntime(3173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-05 18:55:34.088: E/AndroidRuntime(3173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-05 18:55:34.088: E/AndroidRuntime(3173): at dalvik.system.NativeStart.main(Native Method)
my codepackage com.example.itmaproject;
public class EditContactsActivity extends Activity {
TextView txtName;
TextView txtNumber;
TextView txtAbout;
TextView txtDate;
Button btnSave;
Button btnDelete;
TextView txtDepart;
TextView fullname;
TextView txtUser;
Button btnLogout;
String username;
SessionManager session;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_contact_details = "http://10.0.3.2/sunshine-ems/login/get_contact_details.php";
// url to update product
private static final String url_update_contact = "http://10.0.3.2/sunshine-ems/login/get_contact_details.php";
// url to delete product
private static final String url_delete_contact = "http://10.0.3.2/sunshine-ems/delete_contact.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CONTACT = "contacts";
private static final String TAG_USERNAME = "username";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_DEPART = "department";
private static final String TAG_LASTNAME = "lastname";
private static final String TAG_ID = "user_id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_contact);
btnLogout = (Button) findViewById(R.id.btnLogout);
// save button
// getting product details from intent
//Intent i = getIntent();
// getting product id (pid) from intent
//pid = i.getStringExtra(TAG_USERNAME);
session = new SessionManager(getApplicationContext());
username = session.getUsername();
// Getting complete product details in background thread
new GetProductDetails().execute();
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching All products Activity
session.logoutUser();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditContactsActivity.this);
pDialog.setMessage("Loading contact details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_contact_details, "GET", params);
// check your log for json response
Log.d("Single Contact Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray contactObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first product object from JSON Array
JSONObject contact = contactObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.inputName);
txtDepart = (TextView) findViewById(R.id.department);
//txtAbout = (TextView) findViewById(R.id.inputDesc);
txtUser = (TextView) findViewById(R.id.inputPrice);
// display product data in EditText
String fullname = contact.getString(TAG_LASTNAME)+' '+ contact.getString(TAG_FIRSTNAME);
txtName.setText(fullname);
txtDepart.setText(contact.getString(TAG_DEPART));
//txtAbout.setText(contact.getString(TAG_LASTNAME));
txtUser.setText(contact.getString(TAG_ID));
Log.v("blahhhhh", "blah hhhhblah");
}else{
// product with pid not found
Log.v("blah", "blah blah");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditContactsActivity.this);
pDialog.setMessage("Saving contact ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
//String number = txtNumber.getText().toString();
//String about = txtAbout.getText().toString();
String user = txtUser.getText().toString();
String depart = txtDepart.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_USERNAME, username));
params.add(new BasicNameValuePair(TAG_FIRSTNAME, name));
params.add(new BasicNameValuePair(TAG_DEPART, depart));
//params.add(new BasicNameValuePair(TAG_LASTNAME, about));
params.add(new BasicNameValuePair(TAG_ID, user));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_contact,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update 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 product uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditContactsActivity.this);
pDialog.setMessage("Deleting Contact...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_contact, "POST", params);
// check your log for json response
Log.d("Delete Contact", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} 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();
}
}
}
Line 141
Log.d("Single Contact Details", json.toString());
Please check your url JSON may be null because of it
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
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
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();
}
}
});}