Getting error in fetching response using AsyncTask? - android

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?

Related

How to go to nextactivity after login with facebook account

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

Login should be succesful but does not link to my main menu interface

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) {
...
}
}

onPostExecute() not executing in AsyncTask

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.

ProgressDialog onClick not working

ProgressDialog onClick not working.. here is my code .. Basically i want to show loading dialog when user submits login form and waits for response
public class LoginLayout extends MenuActivity {
ProgressDialog progress;
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
ok=(Button)findViewById(R.id.btn_login);
error=(TextView)findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress = ProgressDialog.show(LoginLayout.this, "Login","please...wait",true);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.mysite.com/api/login.php", postParameters);
String res=response.toString();
res= res.replaceAll("\\s+","");
progress.dismiss();
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
}
}
You have to use Hanlders or AsyncTask. There are numerous questions regarding this here. Try to follow the below snippet,
Do this in your onCreate()
Handler handler;
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
Pdialog.dismiss();
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
}
};
And now use a thread to upload files to server. Modify this piece of code,
public class Activity001 extends Activity
{
ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
ProgressDialog progressDialog = ProgressDialog.show(Activity001.this, "", "wait ", true, false);
Thread ProgressThread = new Thread() {
#Override
public void run() {
try {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.mysite.com/api/login.php", postParameters);
String res=response.toString();
res= res.replaceAll("\\s+","");
} catch(InterruptedException e) {
// do nothing
} finally {
handler.sendEmptyMessage(0);
}
}
};
ProgressThread.start();
} };
}
If not go for AsyncTask,
Here are few links,
http://www.vogella.de/articles/AndroidPerformance/article.html
http://labs.makemachine.net/2010/05/android-asynctask-example/
http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask, HttpClient and ProgressDialog

I'm creating a AsyncTask to login user to a server.
The login works fine, but the ProgressDialog does not show until the end of the process.
As soon as the user taps the button, the UI freezes, and my dialog does not show up.
I appreciate any help. Here's my code.
public class MyApp extends Activity {
private ProgressDialog dialogo = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button loginButton = (Button) findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String webAddress = preferencias.getString("webAddress", "");
if (webAddress.isEmpty()) {
Toast.makeText(getBaseContext(), "Please, configure a Web Address.", Toast.LENGTH_LONG).show();
} else {
EditText edtUsername = (EditText) findViewById(R.id.edtUsername);
EditText edtPassword = (EditText) findViewById(R.id.edtPassword);
HashMap<String, String> parametros = new HashMap<String, String>();
parametros.put("username", edtUsername.getText().toString());
parametros.put("password", edtPassword.getText().toString());
Requisicao requisicao = new Requisicao(parametros);
AsyncTask<String, Void, String> resposta = requisicao.execute(webAddress + "/login");
try {
Toast.makeText(getBaseContext(), resposta.get(), Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
Toast.makeText(getBaseContext(), "InterruptedException (login)", Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(getBaseContext(), "ExecutionException (login)", Toast.LENGTH_LONG).show();
}
}
}
});
ImageView engrenagem = (ImageView) findViewById(R.id.imgEngrenagem);
engrenagem.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent preferenciasActivity = new Intent(getBaseContext(), Preferencias.class);
startActivity(preferenciasActivity);
}
});
}
public class Requisicao extends AsyncTask<String, Void, String> {
private final HttpClient clienteHttp = new DefaultHttpClient();
private String resposta;
private HashMap<String, String> parametros = null;
public Requisicao(HashMap<String, String> params) {
parametros = params;
}
#Override
protected void onPreExecute() {
dialogo = new ProgressDialog(MyApp.this);
dialogo.setMessage("Aguarde...");
dialogo.setTitle("Comunicando com o servidor");
dialogo.setIndeterminate(true);
dialogo.setCancelable(false);
dialogo.show();
}
#Override
protected String doInBackground(String... urls) {
byte[] resultado = null;
HttpPost post = new HttpPost(urls[0]);
try {
ArrayList<NameValuePair> paresNomeValor = new ArrayList<NameValuePair>();
Iterator<String> iterator = parametros.keySet().iterator();
while (iterator.hasNext()) {
String chave = iterator.next();
paresNomeValor.add(new BasicNameValuePair(chave, parametros.get(chave)));
}
post.setEntity(new UrlEncodedFormEntity(paresNomeValor, "UTF-8"));
HttpResponse respostaRequisicao = clienteHttp.execute(post);
StatusLine statusRequisicao = respostaRequisicao.getStatusLine();
if (statusRequisicao.getStatusCode() == HttpURLConnection.HTTP_OK) {
resultado = EntityUtils.toByteArray(respostaRequisicao.getEntity());
resposta = new String(resultado, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
} catch (Exception e) {
}
return resposta;
}
#Override
protected void onPostExecute(String param) {
dialogo.dismiss();
}
}
}
Try to comment out resposta.get() call in the button listener. I guess it just blocks the main UI thread untill the task is finished.
Couple things. First of all, don't make an instance for ASyncClass because you can only ever call it once, as per the android documentation. So execute like this: new Requisicao().execute(webAddress + "/login");
Also, instead of calling requisicao.get(), which will, again according to documentation "Waits if necessary for the computation to complete, and then retrieves its result" (also known as blocking), from within your async class add an override:
protected void onProgressUpdate(Long... progress) {
CallBack(progress[0]); // for example
}
Where CallBack is a function in your UI thread which will handle processing your progress long, or string, or whatever else you want to throw back. Mind you, your ASync class will have to be defined within the UI class instead of separately.
move your
private ProgressDialog dialogo = null;
into the AsyncTask's fields as you did it with HTTPClient because you don't
seem to use it anywhere and
try to create your dialog in the constructor
public Requisicao(HashMap<String, String> params) {
parametros = params;
dialogo = new ProgressDialog(MyApp.this);
}
in postExecute
if (dialogo .isShowing()) {
dialogo .dismiss();
}
hope it helps.

Categories

Resources