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
Related
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());
}
});
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.
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();
}
}
});}
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)
i'm having a problem with my application trying to retrieve data from mysql database. when i run the application i get a message that I've created in the php code saying "student not found".
Here is the java code:
public class StudentEditAccount extends Activity {
EditText txtsid;
EditText txtfirstname;
EditText txtlastname;
EditText txtcoursecode;
EditText txtphonenumber;
EditText txtemail;
Button btnSave;
Button btnDelete;
String sid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single student url
private static final String url_product_detials = "http://10.0.2.2/example/get_product_details.php";
// url to update student
private static final String url_update_product = "http://10.0.2.2/example/update_product.php";
// url to delete student
private static final String url_delete_product = "http://10.0.2.2/example/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_STUDENTS = "students";
private static final String TAG_SID = "sid";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_LASTNAME = "lastname";
private static final String TAG_COURSECODE = "coursecode";
private static final String TAG_PHONENUMBER = "phonenumber";
private static final String TAG_EMAIL = "email";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.studenteditaccount);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting student details from intent
Intent i = getIntent();
// getting student id (id) from intent
sid = i.getStringExtra(TAG_SID);
// Getting complete student details in background thread
new GetStudentAccountDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// starting background task to update student
new SaveStudentAccountDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// deleting student in background thread
new DeleteStudentAccount().execute();
}
});
}
/**
* Background Async Task to Get complete student details
* */
class GetStudentAccountDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(StudentEditAccount.this);
pDialog.setMessage("Loading account details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting student 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("sid", sid));
// getting student details by making HTTP request
// Note that student details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single student Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received student details
JSONArray studentsObj = json
.getJSONArray(TAG_STUDENTS); // JSON Array
// get first student object from JSON Array
JSONObject students = studentsObj.getJSONObject(0);
// student with this sid found
// Edit Text
txtfirstname = (EditText) findViewById(R.id.inputfname);
txtlastname = (EditText) findViewById(R.id.inputlname);
txtcoursecode = (EditText) findViewById(R.id.inputcoursecode);
txtphonenumber = (EditText) findViewById(R.id.inputphonenumber);
txtemail = (EditText) findViewById(R.id.inputemail);
// display student data in EditText
txtfirstname.setText(students.getString(TAG_FIRSTNAME));
txtlastname.setText(students.getString(TAG_LASTNAME));
txtcoursecode.setText(students.getString(TAG_COURSECODE));
txtphonenumber.setText(students.getString(TAG_PHONENUMBER));
txtemail.setText(students.getString(TAG_EMAIL));
}else{
// student with sid not found
}
} 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 student Details
* */
class SaveStudentAccountDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(StudentEditAccount.this);
pDialog.setMessage("Saving account ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving student
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String sid = txtsid.getText().toString();
String firstname = txtfirstname.getText().toString();
String lastname = txtlastname.getText().toString();
String coursecode = txtcoursecode.getText().toString();
String phonenumber = txtphonenumber.getText().toString();
String email = txtemail.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_SID, sid));
params.add(new BasicNameValuePair(TAG_FIRSTNAME, firstname));
params.add(new BasicNameValuePair(TAG_LASTNAME, lastname));
params.add(new BasicNameValuePair(TAG_COURSECODE, coursecode));
params.add(new BasicNameValuePair(TAG_PHONENUMBER, phonenumber));
params.add(new BasicNameValuePair(TAG_EMAIL, email));
// sending modified data through http request
// Notice that update student url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"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 student update
setResult(100, i);
finish();
} else {
// failed to update student
}
} 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 student updated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteStudentAccount extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(StudentEditAccount.this);
pDialog.setMessage("Deleting Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting student
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sid", sid));
// getting student details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "POST", params);
// check your log for json response
Log.d("Delete student", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// student successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about student 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 student deleted
pDialog.dismiss();
}
}
}
And this is the PHP code:
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["sid"])) {
$sid = $_GET['sid'];
// get a students from student table
$result = mysql_query("SELECT *FROM student WHERE sid = $sid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$students = array();
$students["sid"] = $result["sid"];
$students["firstname"] = $result["firstname"];
$students["lastname"] = $result["lastname"];
$students["coursecode"] = $result["coursecode"];
$students["phonenumber"] = $result["phonenumber"];
$students["email"] = $result["email"];
// success
$response["success"] = 1;
// user node
$response["students"] = array();
array_push($response["students"], $students);
// echoing JSON response
echo json_encode($response);
} else {
// no student found
$response["success"] = 0;
$response["message"] = "No student found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no student found
$response["success"] = 0;
$response["message"] = "No student found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
my question is: what is the problem that cause the application to display the message "Student not found" every time when i try to retrieve the data from Mysql database?
Thank you.
There is a missing space in your SQL query. It should be SELECT * FROM student WHERE sid = $sid