I am trying to create an activity that allows a user to login by checking the username and password from a database, however after the creadentials are fetched successfully, the doInbackground doesnt stop executing.I not sure what i can do to make the onpostexecute to run. Here is the code
public class LoginActivity extends Activity{
public String username;
public String password;
public String userid;
JSONParser jParser = new JSONParser();
JSONObject json;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
context=getApplicationContext();
setContentView(R.layout.activity_login);
Button loginbutton=(Button) findViewById(R.id.loginbutton);
final EditText usernameText=(EditText) findViewById(R.id.usernameInput);
final EditText passwordText=(EditText) findViewById(R.id.passwordInput);
loginbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=usernameText.getText().toString();
password=passwordText.getText().toString();
if(username.trim().length()==0 || password.trim().length()==0){
AlertDialogManager diag=new AlertDialogManager();
diag.showAlertDialog(getApplicationContext(), "Fill Fields", "enter a username and password", false);
}else{
//send the username and password for verification
new Login().execute();
}
}
});
}
//http class starts here.
class Login extends AsyncTask<String, String, String> {
InputStream is = null;
JSONObject jObj = null;
ProgressDialog pDialog;
static final String url = "http://10.0.2.2/newptk/dalvik/auth.php";
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Authenticating...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.e("Auth", "working");
JSONArray document = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jParser.makeHttpRequest(url, "POST", params);
return null;
}
protected void onPostExecute() {
pDialog.dismiss();
SessionManager smg=new SessionManager(getApplicationContext());
int flag = 0;
try {
flag = json.getInt("success");
if(flag==1){
userid=json.getString("userid");
//set the session
smg.createLoginSession(username, userid);
//Login the user
Intent i = new Intent(getApplicationContext(), ReportFound.class);
startActivity(i);
finish();
}else{
AlertDialogManager diag=new AlertDialogManager();
diag.showAlertDialog(LoginActivity.this, "Login", "Incorrect Username/password", false);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}//end of http class
}
The first thing I see is that you are telling onPostExecute() to accept a String in your class header
class Login extends AsyncTask<String, String, String>
but aren't accepting anything or passing anything to it
protected void onPostExecute() {
if you don't want to pass it anything then change it to
class Login extends AsyncTask<Void, Void, Void>
and
protected void onPostExecute(Void result) {
...
}
#Override
protected void doInBackground(String... arg0) {
Notice this section in the Docs
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the
background computation.
Result, the type of the result of the
background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Change
protected void onPostExecute()
to
protected void onPostExecute(String result)
and you should be golden. Consider adding #Override tags in your code to prevent these subtle bugs in the future.
Related
This is my code where I am trying to login where I am using Async task to accomplish the task.
MainActivity extends Activity {
//define controls
EditText txt_uname, txt_pwd;
TextView txt_Error;
Button btnLogin;
String response = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initalise controls
txt_uname=(EditText)findViewById(R.id.txtUsername);
txt_pwd=(EditText)findViewById(R.id.txtPassword);
btnLogin =(Button)findViewById(R.id.btnLogin);
txt_Error =(TextView)findViewById(R.id.txtError);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String uname = txt_uname.getText().toString();
String pwd = txt_pwd.getText().toString();
validateUserTask task = new validateUserTask();
task.execute(new String[]{uname, pwd});
}
}); //close on listener
}// close onCreate
private class validateUserTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", params[0] ));
postParameters.add(new BasicNameValuePair("password", params[1] ));
String res = null;
try {
response = CustomHttpClient.executeHttpPost("https://xyz/restapi/login", postParameters);
res=response.toString();
res= res.replaceAll("\\s+","");
}
catch (Exception e) {
txt_Error.setText(e.toString());
}
return res;
}//close doInBackground
#Override
protected void onPostExecute(String result) {
if(result.equals("1")){
//navigate to Main Menu
Intent i = new Intent(MainActivity.this, MainMenuActivity.class);
startActivity(i);
}
else{
txt_Error.setText("Sorry!! Incorrect Username or Password");
}
}
}
}
I am not getting the response from the rest API but it is working fine when I had tested in Postman. Can any one let me know what I am missing and let me know if there are any tutorials for it?
I need to update a textView with data from remote db MYSQL, but I have a problem when I try to update the textview in AsyncTask.I tryed everything but it always give me a void textview.
This is my code:
public class Credits extends Activity implements OnClickListener{
private Button home;
private String user;
public TextView totSpesa;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String URL = "http://**********/services.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ERROR_MESSAGE = "error_msg";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_credits);
user=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("id", "");
totSpesa= (TextView)findViewById(R.id.tot_spesa);
home = (Button)findViewById(R.id.home_btn);
home.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.home_btn:
Intent i = new Intent(Credits.this, MainActivity.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptCredits extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Credits.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
//Intent in = getIntent();
//user = in.getStringExtra("id");
String tot_spesa="";
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", "get_credits"));
params.add(new BasicNameValuePair("username", user));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
URL, "POST", params);
tot_spesa=json.getString("tot_spesa");
} catch (JSONException e) {
e.printStackTrace();
}
return tot_spesa;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String tot_spesa) {
totSpesa.setText(tot_spesa);
}
}
}
Maybe I'm missing something but I don't think you're actually launching your AsyncTask.
Try to do :
new AttemptCredits().execute(user);
In onCreate,
and get your user in doInBackground with
user = args[1];
In my application I used autocompletetextview to retrieve data,the data which I display is using json,now autocompletetextview works well,but what I want is after getting name in my autocompletetextview I want to send id of category,but it sends name..following is my response..and my snippet code is here..Autocompletetextview not working
{
"category":
[
{
"id":"4",
"name":"cat1"
},
{
"id":"7",
"name":"aditya"}
]
}
Add_Catagory.java
public class MainActivity extends Activity {
private Button btns;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private MultiAutoCompleteTextView acTextView;
private static final String FEEDBACK_URL = "";
private static final String FEEDBACK_SUCCESS = "status";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acTextView = (MultiAutoCompleteTextView) findViewById(R.id.autoComplete);
acTextView.setAdapter(new SuggestionAdapter(this,acTextView.getText().toString()));
acTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
/* JsonParse jp=new JsonParse();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
list.get(0).getId();*/
btns=(Button)findViewById(R.id.btn);
btns.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
});
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
private String catid;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Sending..");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String pweighttype=acTextView.getText().toString();
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.size();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
System.out.println("Su gayu server ma"+params);
catid=list.get(i).getId().toString();
}
System.out.println("Su catid"+catid);
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
FEEDBACK_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");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(FEEDBACK_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();
//parentcat.getText().clear();
}}
try this//modify doInBackground
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.length();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
break;
}
I did log in using Facebook account by importing Facebook sdk as library in my android app but the main problem is i want to go to another activity when i do log in with Facebook account i am not understanding how to do this.
LoginActivity.java :
public class LoginActivity extends FragmentActivity {
private ProgressDialog pDialog;
Button btn_login,bnt_Register ;
EditText edt_email,edt_password;
JSONParser jsonParser = new JSONParser();
private static String url_create_product = "http://192.168.1.6/laravel/public/user";
private static final String TAG_SUCCESS = "success";
//private static final String TAG_PORTFOLIOS = "lists";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bnt_Register=(Button)findViewById(R.id.btnRegister);
btn_login =(Button)findViewById(R.id.btnLogin);
edt_email = (EditText)findViewById(R.id.loginEmail);
edt_password=(EditText)findViewById(R.id.loginPassword);
bnt_Register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(LoginActivity.this,AccountRegister.class);
startActivity(in);
}
});
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new EmailPassword().execute();
}
});
}
class EmailPassword extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String email =edt_email.getText().toString();
String password =edt_password.getText().toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("email", email));
params1.add(new BasicNameValuePair("password", password));
try{
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params1);
Log.d("Create Response", json.toString());
return json.toString();
}catch(Exception e){}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
try {
JSONObject json = new JSONObject(file_url);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
//Toast.makeText(getApplicationContext(),"Login", Toast.LENGTH_LONG).show();
// closing this screen
//finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
}
you should do that in onPostExecute method. set a flag for response for example set a boolean to true if login was successful and start your other activity in onPostExecute method if flag == true .
change your Post execute method:
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
Intent in = new Intent(LoginActivity.this,YourActivity.class);
startActivity(in);
}
This is my logcat
12-08 14:45:21.179: D/request!(6046): starting
12-08 14:45:21.719: D/Login attempt(6046): {"message":"Login successful!","success":1}
This is my Login.java
public class Login extends ActionBarActivity implements OnClickListener {
private Button login,register;
private EditText email,password;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.1.14:1234/PMSS/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.registerlauncher);
email = (EditText) findViewById(R.id.userid);
password = (EditText) findViewById(R.id.password);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Username = email.getText().toString();
String Password = password.getText().toString();
new AttemptLogin(Username,Password).execute();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
// does not behave as a button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
/*case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(Login.this, Register.class);
startActivity(i);
break;
*/
default:
break;
}
}
//AsyncTask is a seperate thread than the thread that runs the GUI
//Any type of networking should be done with asynctask.
class AttemptLogin extends AsyncTask<String, String, String> {
//three methods get called, first preExecture, then do in background, and once do
//in back ground is completed, the onPost execture method will be called.
boolean failure = false;
String res;
String Username;
String Password;
int success;
public AttemptLogin(String Username, String Password) {
this.Username = Username;
this.Password = Password;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", Username));
params.add(new BasicNameValuePair("password", Password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
System.out.print("Here");
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
res = json.getString(TAG_MESSAGE);
return res;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(int success) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (success == 1) {
Log.d("Login Successful!", res);
Intent i = new Intent(Login.this, MainMenu.class);
startActivity(i);
Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
}else{
Log.d("Login Failure!", res);
Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
}
}
}
}
As the logcat said I login succesfully but in my android phone still having the Attemping Login... and it will not go to my MainMenu interface. There is no compilation and runtime errors. I was wonder Intent i = new Intent(Login.this,MainMenu.class); and startActivity(i); does not work?
You should return success instead of res from your doInBackground. There is also something wrong with the types (arguments, return) of the various methods in AsyncTask. The return type of doInBackground should be the same as the argument type of onPostExecute.
Change your code like this:
class AttemptLogin extends AsyncTask<String, String, Integer> {
...
protected Integer doInBackground(String... args) {
...
return success;
}
protected void onPostExecute(Integer success) {
...
}
}