this is the LoginActivty
public class MainActivity extends Activity {
ProgressDialog prgDialog;
TextView errorMsg;
EditText emailET;
EditText pwdET;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
errorMsg = (TextView) findViewById(R.id.login_error);
emailET = (EditText) findViewById(R.id.loginEmail);
pwdET = (EditText) findViewById(R.id.loginPassword);
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Please wait...");
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btnLogin);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
// call the async task
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
}
then I am using a AsyncTask, this the code
public class HttpAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private static InputStream stream = null;
private static String API;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public HttpAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.x.xxx/xxxxService/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Log.i("Login Success", "Success message");
} else {
Log.e("Login Error", "Error converting result ");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
when I enter correct email and password, it comes to this line
Log.i("Login Success", "Success message");
from there I want to open the HomeActivty but it doesn't allow me to use intent, or even to toast
I need help to implement directing to Home Activity once the logging is success.
Here:
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Because you are getting result on Main Thread by calling AsyncTask.get() method AsyncTask.
First just call AsyncTask.execute method to start AsyncTask task :
new HttpAsyncTask(MainActivity.this).execute(email,password);
then use onPreExecute() to show progessbar and onPostExecute for starting next Activity :
#Override
protected void onPreExecute() {
// show ProgressDialog here
}
#Override
protected void onPostExecute(Void result) {
// parse json here and start Home Activity
//.........your code here
if (test.equals("200")) {
Log.i("Login Success", "Success message");
Intent intent = new Intent(contxt,HomeActivity.class);
contxt.startActivity(intent);
} else {
Log.e("Login Error", "Error converting result ");
}
}
You can start activity like this from AsyncTask, You should use the context.
mContext.startActivity(new Intent(CurrentActivity.this, Home.class));
Or try like this also
Intent intent = new Intent();
intent.setClass(getApplicationContext(),Home.class);
startActivity(intent);
I know there is another valid answer to fix your problem. But to precisely explain why your error exists, I give my answer below.
To create an Intent for startActivity(), this can be done by:
Intent i = new Intent(currentActivity, NextActivity.class);
startActivity(i);
Notice that the first parameter of constructor of Intent is android.content.Context, in which Activity is a subclass of it. So in any situation, you can always pass the Context to your custom class and start a new Activity or create a Toast with this Context.
In your question, private Context contxt; in HttpAsyncTask is the context your need to do everything.
Reference: http://developer.android.com/reference/android/content/Intent.html#Intent%28android.content.Context,%20java.lang.Class%3C?%3E%29
Related
Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(this);
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
public String POST(String url, Person person)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httppost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_name", person.getUsername());
jsonObject.accumulate("email", person.getEmail());
jsonObject.accumulate("password", person.getPassword());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httppost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httppost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Error! email exist";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
#Override
public void onClick(View view) {
if(validate() == 1)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 2)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 3)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 4)
{
//Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
new HttpAsyncTask().execute("http://ip-addressses/api/register");
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setUsername(signupInputName.getText().toString());
person.setEmail(signupInputEmail.getText().toString());
person.setPassword(signupInputPassword.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONObject jObject;
try {
jObject = new JSONObject(result);
if (jObject.has("error")) {
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private int validate() {
if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
{
code = 1;
message = "Complete the form!";
}
else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
{
code = 2;
message = "Re-check password";
}
else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
code = 3;
message = "Invalid email";
}
else
code = 4;
return code;
}
public final static boolean isValidEmail(String target)
{
if (target == null) {
return false;
} else {
Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
return match.matches();
}
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
Postman response when email exist
Just change this code:
jObject = new JSONObject(result);
if (jObject.has("error"))
{
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
}
So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.
I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}
I have this code working with me, I am confused with the control flow.
How is the interface used here as a Response Listener? How is the overridden method responseObject(JSONObject resp, String type) in LoginActivity class triggering?
And after calling AsyncTask where the control goes?
public class LoginActivity extends Activity implements ResponseListener{
login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String username = mUsernameField.getText().toString();
String password = mPasswordField.getText().toString();
String[] param = {username, password};
new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);
}
#Override
public void responseObject(JSONObject resp, String type) {
try{
if (resp.has("api_key")) {
String api_key = resp.getString("api_key");
String user_id = resp.getString("user");
Log.i("api_key", api_key);
SharedPreferences settings = LoginActivity.this.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Constants.NADA_API_KEY, api_key);
editor.putString(Constants.NADA_USER_ID, user_id);
editor.putBoolean(Constants.NADA_IS_LOGGED_IN, true);
editor.commit();
Log.i("first Visit", "False");
String should_show_questions_screen = resp.getString("should_set_basic_questions");
if (should_show_questions_screen.compareToIgnoreCase("true")==0){
Intent intent=new Intent(LoginActivity.this,RegistrationSuccessfulScreen.class);
startActivity(intent);
finish();
}else {
Intent intent = new Intent(LoginActivity.this, UserNavigationActivity.class);
startActivity(intent);
finish();
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
//Heres my ServerRequest Class which uses AsyncTask
public class ServerRequests {
public static class LoginUserAsyncTask extends AsyncTask<String, Void, String> {
static JSONObject udetails;
Context mContext;
ResponseListener mResponseListener;
SweetAlertDialog progressDialog;
public LoginUserAsyncTask(Context mContext,ResponseListener listener) {
this.mContext = mContext;
this.mResponseListener = listener;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog =new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
progressDialog.setTitleText("please wait connecting..");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
udetails = new JSONObject();
String response_data = "";
if (params.length == 2) {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login");
udetails.put("username", params[0]);
udetails.put("password", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login_with_fb");
udetails.put("fb_id", params[0]);
udetails.put("fb_auth_token", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
StringEntity se = new StringEntity(udetails.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
int response_code = response.getStatusLine().getStatusCode();
response_data = EntityUtils.toString(response.getEntity());
Log.i("api_token", response_data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response_data;
}
#Override
protected void onPostExecute(String response) {
progressDialog.dismiss();
JSONObject resp = new JSONObject();
try {
resp = new JSONObject(response);
if (resp.has("status")) {
if (resp.getString("status").compareToIgnoreCase("unauthorised")==0){
AppMsg appMsg = AppMsg.makeText((Activity)mContext, resp.getString("message"), style);
appMsg.show();
}
}
mResponseListener.responseObject(resp,"LOGIN");
} catch (JSONException e) {
AppMsg appMsg = AppMsg.makeText((Activity)mContext, "Something went wrong", style);
appMsg.show();
e.printStackTrace();
}
}
}
//Here's Interface Which has this method
public interface ResponseListener {
public void responseObject(JSONObject data,String type);
}
Your LoginActivity implements ResponseListener. In this line: new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);, you pass your activity twice into the LoginUserAsyncTask constructor. Notice that the constructor takes in a Context and a ResponseListener. You can do this because your activity implements ResponseListener.
Now LoginUserAsyncTask can call the responseObject method on your activty because it has a refrence to it as a ResponseListener. It does that in the onPostExecute method of the AsyncTask. The activity is kind of listning to when the task is done, then it's responseObject method is called.
Becaus the work of the AsyncTask is done asynchronously it returns "straight away" and the next statement is executed.
I also think your missing part of the first method.
this is my LoginActivity class, i want to do add remember me option to this class.
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_email);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxx/xxxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
After some research I was able to come up with this code to do the remember me option using shared preference.
public class MainActivity extends Activity {
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void doLogin(View view) {
EditText txtuser = (EditText) findViewById(R.id.txt_user);
EditText txtpwd = (EditText) findViewById(R.id.txt_pwd);
String email = "u";
String password = "p";
if (txtuser.getText().toString().equals(email)
&& txtpwd.getText().toString().equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email and password
// show logout activity
showLogout(email);
} else {
Toast.makeText(this, "Invalid email or password", Toast.LENGTH_LONG)
.show();
}
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
}
I need help to integrate these 2 classes. I tried but didn't work
this is my out put
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_user);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email
// and
// password
// show logout activity
showLogout(email);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxxx/xxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Please have read so many on this,(it says i should not put the dialog in the doInbackground) But have been trying to get this done for a while,Its actually my first android app(with java). Please how do i show the loading bar,disable button (till there's response) and redirect to another activity on success.
public class Index extends Activity implements OnClickListener {
EditText username, password;
Button login;
String uname,pass;
TextView login_err;
HttpClient httpclient;
HttpPost htpost;
ArrayList <NameValuePair> namearray;
HttpResponse response;
HttpEntity entity;
int Server_response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
login_err= (TextView) findViewById(R.id.login_err);
initialise();
}
private void initialise() {
username = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login= (Button) findViewById(R.id.login_btn);
login.setOnClickListener(this);;
}
public void onClick(View v) {
String umail=username.getText().toString();
String pass= password.getText().toString();
if(umail.length()!=0 && pass.length()!=0){
new MyAsyncTask().execute();
}else{
Toast.makeText(getBaseContext(), "Please provide username and password",Toast.LENGTH_SHORT).show();
}
}//END onClick()
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//END convertStreamToString()
private class MyAsyncTask extends AsyncTask <Void, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
if(Server_response==1){
mProgressDialog.dismiss();
}
}
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(Index.this, "Loading...", "Logging In...");
}
protected Void doInBackground(Void... params) {
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php");
//Assign input text to strings
uname= username.getText().toString();
pass= password.getText().toString();
//Next block of code needs to be surrounded by try/catch block for it to work
try {
//Create new Array List
namearray = new ArrayList<NameValuePair>();
//place them in an array list
namearray.add(new BasicNameValuePair("username", uname));
namearray.add(new BasicNameValuePair("password", pass));
//Add array list to http post
htpost.setEntity(new UrlEncodedFormEntity(namearray));
//assign executed form container to response
response= httpclient.execute(htpost); //response from the PHP file
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode()==200){
//assign response entity to http entity
entity= response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
JSONObject jresponse = new JSONObject(convertStreamToString(instream));
//assign json responses to local strings
String logged= jresponse.getString("logged");
if(logged.equals("true")){
Server_response=1;
//Please i want to redirect to a new activity here
}else{
Log.d("Error Invalid credentials",logged);
Server_response=0;
}
}
}
} catch(Exception e){
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
return null;
}
return null;
}
}
}
You should take a look at the loginActivity class from the android sdk there's a template that do what you want.
They have a method that shows an animation while the asynctask is running, you just have to call it before executing your asynctask like that
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute();
here's the method:
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
and then in your asynctask you use onPostExecute which will be called after the asynctask is completed and you can stop the login animation and launch a new activity from there
protected void onPostExecute(String[] userDetails) {
showProgress(false);
}