check text boxes if written android - 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();
}
}
});}

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

Sending Image to the MySQL database with Android

I have the current application which sends and retrieves data from a MySQL database but the information so far I was transferring was String. How can I update the code below to be able to send images too.
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
EditText inputImg;
Button btnTakePhoto;
ImageView imgTakenPhoto;
private static final int CAM_REQUREST = 1313;
// url to create new product
private static String url_create_product = "http://buiud.com/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
inputImg = (EditText) findViewById(R.id.imageView1);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
btnTakePhoto = (Button) findViewById(R.id.button1);
imgTakenPhoto = (ImageView) findViewById(R.id.imageView1);
btnTakePhoto.setOnClickListener(new btnTakePhotoClicker());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAM_REQUREST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imgTakenPhoto.setImageBitmap(thumbnail);
}
}
class btnTakePhotoClicker implements Button.OnClickListener
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAM_REQUREST);
}
}
/**
* 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(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
String image = inputImg.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
params.add(new BasicNameValuePair("image", image));
// 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(), AllProductsActivity.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();
}
}
}
Note: I have added the image field as I did other String fields, but the application now stops, it can't convert the picture as Text obviously. Let me know what you think, or any sort of casting available. I just take a photo and that photo is to be sent to MySQL.

Pass value from Textview in dialog to Asynctask

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

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

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