Java (Android) - With PHP a IsLoggedIn Method - android

I will make a IsLoggedIn Function with PHP (because i check again the name and password in db), but i get a NetworkOnMainThreadException in my logcat.
What is wrong?
public boolean LoggedIn() {
try {
int success;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(CHECK_URL, "POST", params);
success = json.getInt(TAG_SUCCESS);
if(success == 1) {
return true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}

Like the exception says, you can't run network operations on the UI thread on Android. You will need to run them on a separate thread so your application doesn't freeze while you're doing stuff on the network. The most common approach for this is an AsyncTask.

Related

method getText must be called from the ui thread

I am doing an application that need to send data from android to database. I am doing it using JSONParser. But I got problem when I launched the application, it doesn't send the data to the server. I got and error on "String name = inputName.getText().toString();". Here is it:
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String date = inputDate.getText().toString();
String time = inputTime.getText().toString();
String latitude = inputLatitude.getText().toString();
String longitude = inputLongitude.getText().toString();
String contacts = inputContacts.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
params.add(new BasicNameValuePair("latitude", latitude));
params.add(new BasicNameValuePair("longitude", longitude));
params.add(new BasicNameValuePair("contacts", contacts));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
As the error tells you, you cannot call getText() on a background thread. Instead, move your six getText() calls into a constructor of your AsyncTask, or possibly into an onPreExecute() callback, so the getText() calls are made on the main application thread.

How I can update two different Mysql tables from android with one async task?

I want to update two Mysql tables with one async task and different params, when save button is clicked. It's working properly when its about one table.. How do I implement such a thing?
The code on doInBackground() is:
// getting updated data
Log.d("aa for save", String.valueOf(aa));
Log.d("bb for save", String.valueOf(bb));
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, p_id));
params.add(new BasicNameValuePair(TAG_aa, String.valueOf(aa)));
params.add(new BasicNameValuePair(TAG_bb, String.valueOf(bb)));
JSONObject json = jsonParser.makeHttpRequest(url_update_product,"POST", params);
// getting updated data
// Building Parameters
List<NameValuePair> params_user = new ArrayList<NameValuePair>();
params_user.add(new BasicNameValuePair(TAG_UNAME, uname));
params_user.add(new BasicNameValuePair(TAG_aa, String.valueOf(aa)));
params_user.add(new BasicNameValuePair(TAG_bb, String.valueOf(bb)));
JSONObject json_user = jsonParser.makeHttpRequest(url_update_user_votes,"POST", params_user);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
int success2 = json_user.getInt(TAG_SUCCESS);
if (success == 1 && success2 ==1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about update
setResult(100, i);
finish();
} else {
// failed to update
}
} catch (JSONException e) {
e.printStackTrace();
}
The error I get is :
"java.lang.IllegalArgumentException: View not attached to window manager"
on the activity that has the onActivityResult()
Change two mysql tables in one php script and send success and succes2 in one json from servera
// getting updated data
Log.d("aa for save", String.valueOf(aa));
Log.d("bb for save", String.valueOf(bb));
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, p_id));
params.add(new BasicNameValuePair(TAG_UNAME, uname));
params.add(new BasicNameValuePair(TAG_aa, String.valueOf(aa)));
params.add(new BasicNameValuePair(TAG_bb, String.valueOf(bb)));
JSONObject json = jsonParser.makeHttpRequest(url_update_all,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
int success2 = json.getInt(TAG_SUCCESS2);
if (success == 1 && success2 ==1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about update
setResult(100, i);
finish();
} else {
// failed to update
}
} catch (JSONException e) {
e.printStackTrace();
}
example php script
<?php
$aa = $_REQUEST['aa'];
$bb = $_REQUEST['bb'];
$p_id = $_REQUEST['p_id'];
$uname = $_REQUEST['uname'];
//db connect.......
$success=0;
$resttt = "UPDATE table1 SET aa='$aa' ";
$result = mysql_query("$resttt");
if($result) { $success=1; }
$success2=0;
$resttt2 = "UPDATE table2 SET bb='$bb' ";
$result2 = mysql_query("$resttt2");
if($result2) { $success2=1; }
// array for JSON response
$response = array();
// success
$response["success"] = $success;
$response["success2"] = $success2;
// echoing JSON response
echo json_encode($response);
?>

putting data from editText into a table

I am a beginner in android, I make tables in eclipse, and I want to retrieve the information entered by the user to put it in a table named user when pressing on the button REGISTER
What code should I wrote to do that ?
params.add(new BasicNameValuePair("mobile_number", number));
params.add(new BasicNameValuePair("password", pwd));
params.add(new BasicNameValuePair("hint", h));
params.add(new BasicNameValuePair("email_id", id));
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
flag=0;
Intent i = new Intent(getApplicationContext(),Welcome.class);
i.putExtra("mobile_number",number);
i.putExtra("password",pwd);
startActivity(i);
finish();
}
else
{
// failed to Sign in
flag=1;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;

Android: Android App is not responding, close it?

I have an application which sends data to a server and sometimes the following message appears: Android app is not responding , Close it? ( i don't know if is the same in English)
It's difficult to see the log because it happens in one of 20 devices approximately when they are all working, and I can't see the log at that moment.
I think the problem can be with the Asynctask function that sends data to the server.
Here is the function:
class UpdateCandidatos extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", Nombres.getPID()));
params.add(new BasicNameValuePair("test", nombre));
params.add(new BasicNameValuePair("pregunta", npregunta));
params.add(new BasicNameValuePair("bateria", levelstring));
params.add(new BasicNameValuePair("correctas", correctasString));
params.add(new BasicNameValuePair("errores", fallosString));
JSONObject json = jsonParser.makeHttpRequest(url_update,
"POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
When it is called the asynctask function:
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
if (radBotA.isChecked()) {
Respuestas[posicion] = "A";
}
else if (radBotB.isChecked()) {
Respuestas[posicion] = "B";
}
else if (radBotC.isChecked()) {
Respuestas[posicion] = "C";
}
else if (radBotD.isChecked()) {
Respuestas[posicion] = "D";
}
else {
Respuestas[posicion] = "";
}
if (Titulacion.IsReachable1(getApplicationContext())) {
Correccion();
new UpdateCandidatos().execute();
}
}
});
The message appears after there is some time that even you click on any button the app continues blocked. Is there anything wrong on my asynctask function? How Could I solve this problem?
Edit: Correccion() is comparing 2 arrays.
public void Correccion(){
correctas = 0;
fallos = 0;
sinresponder = 0;
for(int posicion=0;posicion<=nPreguntas-1;posicion++){
if(Respuestas[posicion].equals(RespuestasC[posicion])){
correctas++;
}
else if(Respuestas[posicion].equals("")){
sinresponder++;
}
else{
fallos++;
}
}
correccion++;
correctasString = String.valueOf(correctas);
fallosString = String.valueOf(fallos);
}
isReachable() is used in order to know if the device can reach the Server.
public static boolean IsReachable1(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
boolean isReachable = false;
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://10.0.0.15/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1 * 200);
urlc.connect();
isReachable = (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e("TAG", e.getMessage());
}
}
return isReachable;
}
If you click several times on the button you start several asyncTask, I suggest:
Avoid multiple task: wait for previous execution end
Use the following code to start the task:
The code:
myTask = new GetDeviceLogTask();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
else
myTask.execute((Void[]) null);
EDIT:
Ok I think you're doing to much things on the main thread that normally is used only to update the user interface and you may not use for caluclations. So try to move Correccion() and .IsReachable1() inside your async task:
class UpdateCandidatos extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
if (!Titulacion.IsReachable1(getApplicationContext())) {
return null;
}
Correccion();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", Nombres.getPID()));
params.add(new BasicNameValuePair("test", nombre));
params.add(new BasicNameValuePair("pregunta", npregunta));
params.add(new BasicNameValuePair("bateria", levelstring));
params.add(new BasicNameValuePair("correctas", correctasString));
params.add(new BasicNameValuePair("errores", fallosString));
JSONObject json = jsonParser.makeHttpRequest(url_update,
"POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

save data from listview to database

I have data from listview, and I want to save it in my database, here's my code;
listResep = (ListView) findViewById(R.id.listResep);
int leng = listResep.getCount();
for(int i = 0; i < leng; i++) {
resep = listResep.getItemAtPosition(i).toString();
new inputResep().execute();
}
and for inputResep;
class inputResep extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(InputRM.this);
pDialog.setMessage("save Resep..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("rm", rm));
params.add(new BasicNameValuePair("noregis", noregis));
params.add(new BasicNameValuePair("tanggal", tglinput));
params.add(new BasicNameValuePair("pukul", pukul));
params.add(new BasicNameValuePair("ruper", ruper));
params.add(new BasicNameValuePair("kelas", kelas));
params.add(new BasicNameValuePair("profesi", profesi));
params.add(new BasicNameValuePair("kajian", resep));
params.add(new BasicNameValuePair("id_user", id_user));
params.add(new BasicNameValuePair("tglsave", tglsave));
// getting JSON Object
// Note that create product url accepts POST method
json = jsonParser.makeHttpRequest(URL_INPUT_RESEP,"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
but every time I tried to input resep, it only save last data from listview as much as data in listview, ex= listview: data1, data2, data3; save: data3, data3, data3;
Put the whole thing in a FOR LOOP, getting the size of the total views in listview and so for each loop the data will be uploaded in the database!!
after looking at #Exeptional answer, this is how I deal with it;
int leng = listResep.getCount();
Log.d("jml resep", ""+leng);
for(int i = 0; i < leng; i++) {
resep = listResep.getItemAtPosition(i).toString();
Log.d("save resep"+i, resep);
// new inputResep().execute();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("rm", rm));
params.add(new BasicNameValuePair("noregis", noregis));
params.add(new BasicNameValuePair("tanggal", tglinput));
params.add(new BasicNameValuePair("pukul", pukul));
params.add(new BasicNameValuePair("ruper", ruper));
params.add(new BasicNameValuePair("kelas", kelas));
params.add(new BasicNameValuePair("profesi", profesi));
params.add(new BasicNameValuePair("kajian", resep));
params.add(new BasicNameValuePair("id_user", id_user));
params.add(new BasicNameValuePair("tglsave", tglsave));
// getting JSON Object
// Note that create product url accepts POST method
json = jsonParser.makeHttpRequest(URL_INPUT_RESEP,"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
}
EDIT:
it works fine when I tried with emulator, then I tried install in my tablet, at first it works fine, but it didn't work when I tried to save data, so I changed it and put loop in the asyncTask:
class inputResep extends AsyncTask<String, String, String> {
/**
* Creating product
* */
protected String doInBackground(String... args) {
int leng = listResep.getCount();
Log.d("jml resep", ""+leng);
for(int i = 0; i < leng; i++) {
resep = listResep.getItemAtPosition(i).toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("rm", rm));
params.add(new BasicNameValuePair("noregis", noregis));
params.add(new BasicNameValuePair("tanggal", tglinput));
params.add(new BasicNameValuePair("pukul", pukul));
params.add(new BasicNameValuePair("ruper", ruper));
params.add(new BasicNameValuePair("kelas", kelas));
params.add(new BasicNameValuePair("profesi", profesi));
params.add(new BasicNameValuePair("kajian", resep));
params.add(new BasicNameValuePair("id_user", id_user));
params.add(new BasicNameValuePair("tglsave", tglsave));
// getting JSON Object
// Note that create product url accepts POST method
json = jsonParser.makeHttpRequest(URL_INPUT_RESEP,"POST", params);
Log.d("testinput", "4");
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
Log.d("test", "berhasil simpan resep");
} else {
// failed to create product
Log.d("test", "failed to create product ");
}
Log.d("test", "in try");
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
}
return null;
}
}
try useing this one in postexecute in forloop
protected void onPostExecute(response response) {
pDialog.dismiss();
try {
int success = json.getInt(TAG_SUCCESS);
Log.d("stat", success+"");
if (success > 0) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("test", "JSONException"+e.getMessage());
}
}

Categories

Resources