An error occurred while executing doinBackground().
class PostComment extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddComment.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
//postData("deepika");
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String post_title = intime.getText().toString();
String post_message = outtime.getText().toString();
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(AddComment.this);
String post_username = sp.getString("username", "anon");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
params.add(new BasicNameValuePair("intime", post_title));
params.add(new BasicNameValuePair("outtime", post_message));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(POST_COMMENT_URL, "POST",
params);
//JSONObject json1 = jsonParser.makeHttpRequest("http://192.168.10.30/webservice/comments.php", "POST",
// params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Attendence Marked!", json.toString());
//finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Attendence Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
finish();
if (file_url != null) {
Toast.makeText(AddComment.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
This is the error log:
11-05 05:03:20.171: E/AndroidRuntime(3171): FATAL EXCEPTION: AsyncTask #1
11-05 05:03:20.171: E/AndroidRuntime(3171): Process: com.example.mysqltest, PID: 3171
11-05 05:03:20.171: E/AndroidRuntime(3171): java.lang.RuntimeException: An error occurred while executing doInBackground()
11-05 05:03:20.171: E/AndroidRuntime(3171): at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-05 05:03:20.171: E/AndroidRuntime(3171): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.lang.Thread.run(Thread.java:841)
11-05 05:03:20.171: E/AndroidRuntime(3171): Caused by: java.lang.NullPointerException
in click listener do this
mSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View vw) {
String post_title = intime.getText().toString();
String post_message = outtime.getText().toString();
new PostComment(post_title,post_message).execute();
}
});
and in the asynch task change this
class PostComment extends AsyncTask<String, String, String> {
String response = "";
String post_title ="";
String post_message="";
// Check for success tag
int success;
public PostComment(String title,String msg) {
post_title = title;
post_message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddComment.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
//postData("deepika");
}
#Override
protected String doInBackground(String... args) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(AddComment.this);
String post_username = sp.getString("username", "anon");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
params.add(new BasicNameValuePair("intime", post_title));
params.add(new BasicNameValuePair("outtime", post_message));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(POST_COMMENT_URL, "POST",
params);
//JSONObject json1 = jsonParser.makeHttpRequest("http://192.168.10.30/webservice/comments.php", "POST",
// params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Attendence Marked!", json.toString());
response = json.getString(TAG_MESSAGE);
}else{
Log.d("Attendence Failure!", json.getString(TAG_MESSAGE));
response = json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(AddComment.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
Related
I want to create application for registration. But i have an error. java.lang.RuntimeException: An error occured while executing doInBackground()
whats wrong? this is my full class
public class signup_activity extends AppCompatActivity {
EditText username_reg;
EditText email_reg;
EditText password_reg;
Button signup_reg;
String url_server = "http://192.168.1.215/register.php";
TextView tanggal_reg;
Boolean cekinput;
String aksi;
String tanggal_kirim;
HttpResponse response;
String GetUsername, GetEmail, GetPassword, GetTanggal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
username_reg = (EditText)findViewById(usernameup);
email_reg = (EditText)findViewById(emailup);
password_reg = (EditText)findViewById(passwordup);
signup_reg = (Button)findViewById(signup);
tanggal_reg = (TextView)findViewById(tanggalup);
signup_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Getcekinputkosong();
if(cekinput){
kirimdata(GetUsername, GetEmail, GetPassword, GetTanggal);
}
else {
Toast.makeText(signup_activity.this, "Data yang anda isikan belum lengkap", Toast.LENGTH_LONG). show();
}
}
});
}
public void Getcekinputkosong(){
GetUsername = username_reg.getText().toString();
GetEmail = email_reg.getText().toString();
GetPassword = password_reg.getText().toString();
GetTanggal=tanggal_reg.getText().toString();
if (TextUtils.isEmpty(GetUsername) || TextUtils.isEmpty(GetEmail) || TextUtils.isEmpty(GetPassword) || TextUtils.isEmpty(GetTanggal)) {
cekinput = false;
}
else {
cekinput = true;
}
}
public void kirimdata(final String username_reg, final String email_reg, final String password_reg, final String tanggal_reg) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String username_kirim = username_reg;
String email_kirim = email_reg;
String password_kirim = password_reg;
String tanggal_kirim = tanggal_reg;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username_reg", username_kirim));
nameValuePairs.add(new BasicNameValuePair("email_reg", email_kirim));
nameValuePairs.add(new BasicNameValuePair("password_reg", password_kirim));
nameValuePairs.add(new BasicNameValuePair("tanggal_reg", tanggal_kirim));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_server);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Berhasil Terkirim";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(signup_activity.this, "Data Berhasil Terkirim", Toast.LENGTH_SHORT).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(username_reg, email_reg, password_reg);
}
public void kembali_login(View arg0){
Intent kembali = new Intent(signup_activity.this, register_activity.class);
startActivity(kembali);
signup_activity.this.finish();
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new datepickerlah();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
I am getting this Error while running:
E/AndroidRuntime:
FATAL EXCEPTION: AsyncTask #3
Process: com.example.client18.dd, PID: 8356
java.lang.RuntimeException: An error occured while executing
doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException
at com.example.client18.dd.signup_activity$1SendPostReqAsyncTask.doInBackground(signup_activity.java:128)
at com.example.client18.dd.signup_activity$1SendPostReqAsyncTask.doInBackground(signup_activity.java:112)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
This is my register.php
<?php
$server = "localhost";
$user="root";
$password="";
$database = "contohdatabase";
$koneksi = mysql_connect($server, $user, $password, $database);
if(isset($_POST['username']) && isset($_POST['password'])){
$nama = $_POST['username_reg'];
$email = $_POST['email_reg'];
$password = $_POST['password_reg'];
$tanggal_lahir = $_POST['tanggal_reg'];
$tambahdata = "INSERT INTO login(username, email, password, tanggal_lahir) VALUE($nama, $email, $password, $tanggal_lahir);";
if(mysql_query($koneksi,$tambahdata)){
echo "Data berhasil diinput ";
}
else {
echo "Data tidak sukses terkirim";
}
echo "$result";
}
?>
Your mistake is here,
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
You have not initialize "response" and use it.so, replace it with "httpResponse".
i am working on registration form where i have to fill all the fields and the EditText input data should go to the database using json parser.but am facing a problem here ..when i try example fn.gettext().toString()..it gives me red line that" Method getText() must be called from the UI thread, currently inferred thread is worker ".now everything is fine only this line gives me error.i don't know whether this is the correct way to send data as i m newbie here.
here is my Registration.java class:
public class RegistrationForm extends AppCompatActivity {
EditText fn,ln,mb,em,pw,cpw,dob,gen;
Switch sw;
RadioGroup male,feml;
Switch swth;
private ProgressDialog pDialog;
private static String url_create_book = "http://cl...com/broccoli/creatinfo.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
private int serverResponseCode = 0;
Context c;
int i=0;
Button sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_form);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fn=(EditText)findViewById(R.id.fnm) ;
ln=(EditText)findViewById(R.id.lnm) ;
mb=(EditText)findViewById(R.id.mobile) ;
em=(EditText)findViewById(R.id.email) ;
pw=(EditText)findViewById(R.id.pass) ;
cpw=(EditText)findViewById(R.id.cpass) ;
RadioButton male=(RadioButton)findViewById(R.id.rgm) ;
RadioButton feml=(RadioButton)findViewById(R.id.rgf) ;
Switch swth=(Switch)findViewById(R.id.mySwitch) ;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sub=(Button)findViewById(R.id.sub2);
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CreateNewProduct().execute();
// startActivity(new Intent(RegistrationForm.this, Home.class));
}
});
}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationForm.this);
pDialog.setMessage("Creating books..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String fname = fn.getText().toString();
String lname = ln.getText().toString();
String email = em.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("First_Name", fname));
params.add(new BasicNameValuePair("Last_Name",lname));
params.add(new BasicNameValuePair("email", email));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_book,
"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(), Login.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();
}
}
here is my php file for adding data :
<?php
/
// array for JSON response
include ('config.php');
// check for required fields
if (isset($_POST['First_Name']) && isset($_POST['Last_Name']) && isset($_POST['email'])) {
$fname = $_POST['First_Name'];
$lname = $_POST['Last_Name'];
$email = $_POST['email'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO UserInfo(First_Name, Last_Name, email) VALUES('$fname', '$lname ', '$email')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
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);
}
?>
i am trying to add few fields if this will work..i will add full fields .
here is my logcat:
2-28 14:11:44.201 3245-3504/com.example.zeba.broccoli E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.zeba.broccoli, PID: 3245
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.zeba.broccoli.RegistrationForm$CreateNewProduct.doInBackground(RegistrationForm.java:147)
at com.example.zeba.broccoli.RegistrationForm$CreateNewProduct.doInBackground(RegistrationForm.java:107)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
12-28 14:11:44.341 3245-3354/com.example.zeba.broccoli D/mali_winsys: new_window_surface returns 0x3000, [540x960]-format:1
12-28 14:11:44.456 3245-3245/com.example.zeba.broccoli I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#2f0f4385 time:209884695
12-28 14:11:44.736 3245-3245/com.example.zeba.broccoli E/WindowManager: android.view.WindowLeaked: Activity com.example.zeba.broccoli.RegistrationForm has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{6dda29d V.E..... R......D 0,0-501,174} that was originally added here
Update your createNewProduct to this:
class CreateNewProduct extends AsyncTask<String, String, String> {
private String fname;
private String lname;
private String email;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationForm.this);
pDialog.setMessage("Creating books..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
fname = fn.getText().toString();
lname = ln.getText().toString();
email = em.getText().toString();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("First_Name", fname));
params.add(new BasicNameValuePair("Last_Name",lname));
params.add(new BasicNameValuePair("email", email));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_book,
"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(), Login.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();
}
}
In AsyncTask, onPreExecute and onPostExecute runs in main thread whereas doInBackground runs in background thread in which you are not able to perform any ui related operations.
You are doing UI activity in doInBackground
protected String doInBackground(String... args) {
String fname = fn.getText().toString();
String lname = ln.getText().toString();
String email = em.getText().toString();
........
}
getText() should be in onPreExecute or in onCreate method. Define all above string globally.
here the corrct php for this type of code where you want add data from edittext..my mistake was that with GET and POST METHODE...
<?php
include ('config.php');
$fname = $_POST['First_Name'];
$lname = $_POST['Last_Name'];
$email = $_POST['email'];
$stmt = mysqli_query($conn,"INSERT INTO UserInfo(First_Name,Last_Name,email) VALUES ('$fname','$lname','$email')");
/*now only submenu items of given type will be selected*/
if ($stmt) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
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);
}*/
//echo json_encode($arr);
?>
i have just now published my app on google play store. I'm sure that the apk is well written and compiled, without any crashes. Unfortunally after i've published it on the store in beta-version it crashes on the FIRST asynctask. This is my log:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at it.mybow.SaronnoCity.Login.RegStep3$Senddata.doInBackground(RegStep3.java:358)
at it.mybow.SaronnoCity.Login.RegStep3$Senddata.doInBackground(RegStep3.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
... 4 more
And this is the class of the mysterious error:
class Senddata extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Registrazione in corso...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
int success;
MyApplication application;
application = (MyApplication) getActivity().getApplicationContext();
//String regId = application.getGCMId();
String regId = "Appenaregistrato";
String nome = application.getnome();
String sesso = application.getsesso();
String email = application.getemail();
String username = application.getusername();
String password = application.getpassword();
String telefono = application.gettelephone();
//Log.d("regId", regId);
try {
Log.d("regId", regId);
Log.d("nome", nome);
Log.d("sesso", sesso);
Log.d("email", email);
Log.d("username", username);
Log.d("password", password);
Log.d("telefono", telefono);
//Aggiungo i parametri generati dalle variabili
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("registration_id", regId));
params.add(new BasicNameValuePair("nome", nome));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("sesso", sesso));
params.add(new BasicNameValuePair("telefono", telefono));
Log.d("request!", "starting");
//Utilizzo JSON per mandare i dati delle variabili
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// Line 358 ERROR
Log.d("Login attempt", json.toString());
//Se va tutto bene...
success = json.getInt(TAG_SUCCESS);
if (success == 3) {
Log.d("User Created!", json.toString());
getActivity().finish();
return json.getString(TAG_MESSAGE);
}if(success == 0){
Log.d("Inserire tutti i campi!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
if (success == 1) {
Log.d("L'username scelto è gia in uso", json.toString());
return json.getString(TAG_MESSAGE);
}if(success == 2){
Log.d("Operazione fallita!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
//Funzione dismiss
pDialog.dismiss();
if (file_url != null){
Toast.makeText(getActivity(), file_url, Toast.LENGTH_LONG).show();
}
}
};
So two thinks make all this very strange:
1) why does my app crash after been published, while the apk does not?
2) why it crashes not on a specific asyntask, but in general on the first called?
Thanks to all.
I have two things in my project first is login page which extended with Activity and to check username and password I am using following json {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}.
Now second thing is I am using navigation drawer which is extended with Activity and it uses different Fragment file,now after user log in successfully first fragment will display in which I want to parse some data in List view and for that I am using following json {"matching":[{"name":"Dynamic Street","profile_id":"","image":"path"}]}.So the problem is I need to use user login id 2650 to parse data in List view and want to send it with request in my http URL.
public class LoginPage extends Activity implements OnClickListener{
private Button btn;
private EditText user;
private EditText pass;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
private Button btn1;
private static final String LOGIN_URL = "http://XXXXX/login";
private static final String TAG_SUCCESS = "status";
private static final String TAG_LOGIN = "login";
private static final String TAG_USERID="user_login_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
user=(EditText)findViewById(R.id.loginmailid);
pass=(EditText)findViewById(R.id.loginpwd);
btn=(Button)findViewById(R.id.login);
btn1=(Button)findViewById(R.id.btnreg);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.btnreg:
Intent i = new Intent(this, RegistrationForm.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
LOGIN_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_SUCCESS);
}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();
if(file_url.equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
for fragment class check this https://stackoverflow.com/questions/26816016/how-to-parse-json-data-from-server-using-fragment
You can send the LOGIN_ID value from Activity as:
Bundle bundle = new Bundle();
bundle.putString("LOGIN_ID", value);
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment get value in onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
return inflater.inflate(R.layout.fragment, container, false);
}
Edit :
Remove return line, check this code :
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
new LoadAlbums().execute();
return rootView;
}
You dont need NameValuePairs. remove below lines.
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
create another object.
JsonObject request = new JsonObject();
request.put("email", username));
request.put("password", password));
request.put("version", "apps"));
You can also add ID in it request.put("ID", ID_VALUE));
ask server developer format of request he will let you know exact format he is parsing on server.
change the code,
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected JsonObject doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
LOGIN_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return jobj;
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_SUCCESS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(JsonObject file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(jobj.getString("status").equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", jobj.getString("user_login_id"));
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
JSONObject object = new JSONObject();
object.put("email", username);
object.put("password", password);
object.put("version", "apps");
String dat = object.toString();
JSONObject object1 = new JSONObject();
object1.put("userAuthentication", object);
String dat1 = object1.toString();
httppost.setEntity(new StringEntity(dat1, HTTP.US_ASCII));
httppost.setHeader("Content-type", "application/json;" + HTTP.UTF_8);
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(result!=null) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
I have this login Activity that contains async task class which perform a parsing method(Post) everything is going right and my data is posted but when the user enters a wrong email and password i just need to Toast him that his email and password are wrong so my code look like this:
public class ActivityLogin extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
private static String login_tag = "login";
PostParser jsonParser = new PostParser();
// UI references.
private EditText email;
private EditText password;
static String Email="";
static String Password="";
// url to create new product
private static String login_URL = "jhdakjhdakj";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
password=(EditText)findViewById(R.id.password1);
Button login=(Button)findViewById(R.id.sign_in_button);
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Email=email.getText().toString();
Password=password.getText().toString();
(new LoginInTask()).execute();
}
});
}
class LoginInTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityLogin.this);
pDialog.setMessage("Logging IN..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args)
{
String Email = email.getText().toString();
String Password = password.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(login_URL,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success=0;
try
{
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int success)
{
if (success==1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), ActivitySignUp.class);
startActivity(i);
// closing this screen
pDialog.dismiss();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
finish();
}
}
}
your help would be appreciated. Thank you
here is my logcat
11-05 16:16:46.536: E/AndroidRuntime(5807): FATAL EXCEPTION: AsyncTask #1
11-05 16:16:46.536: E/AndroidRuntime(5807): java.lang.RuntimeException: An error occured while executing doInBackground()
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.lang.Thread.run(Thread.java:849)
11-05 16:16:46.536: E/AndroidRuntime(5807): Caused by: java.lang.NullPointerException
11-05 16:16:46.536: E/AndroidRuntime(5807): at com.asap.ActivityLogin$LoginInTask.doInBackground(ActivityLogin.java:108)
11-05 16:16:46.536: E/AndroidRuntime(5807): at com.asap.ActivityLogin$LoginInTask.doInBackground(ActivityLogin.java:1)
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-05 16:16:46.536: E/AndroidRuntime(5807): ... 4 more
please change your code with this one I've fixed many things to you taged with <--jack
public class ActivityLogin extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
private static String login_tag = "login";
PostParser jsonParser;//<-- placed in doinbackground <-- jack
// UI references.
private EditText email;
private EditText password;
static String Email="";
static String Password="";
// url to create new product
private static String login_URL = "jhdakjhdakj";
// JSON Node names
private static final String TAG_SUCCESS = "success";
//Query login <<- jack
LoginInTask query;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
password=(EditText)findViewById(R.id.password1);
Button login=(Button)findViewById(R.id.sign_in_button);
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Email=email.getText().toString();
Password=password.getText().toString();
//Cancel if already runing or dont excute its up to you <-- jack
if( query != null )
{
query.cancel(true);
}
query = ( LoginInTask ) new LoginInTask().execute();
}
});
}
class LoginInTask extends AsyncTask<String, String, String> {
//Register success here <-- jack
int success=0;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityLogin.this);
pDialog.setMessage("Logging IN..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* if canceled <-- jack
* */
#Override
protected void onCancelled() {
if ( pDialog != null )
{
pDialog.dismiss();
}
}
/**
* Creating product
* */
protected String doInBackground(String... args)
{
String Email = email.getText().toString();
String Password = password.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
//Try from here coz you are working with JSON <<-- jack
try
{
// getting JSON Object
// Note that create product url accepts POST method
//Start new Session <-- jack
jsonParse = new PostParser();
JSONObject json = jsonParser.makeHttpRequest(login_URL,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e)
{
Log.d("Create Response", "Faild");//<-- tag faild to parse JSON
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int success)
{
//Check if dialog still runing dismiss <<-- jack
if ( pDialog != null)
{
pDialog.dismiss();
}
if (success==1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), ActivitySignUp.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
//finish current activity call it on time only <<-- jack
finish();
}
}
}