how to check if logged in previosly in android app - android

i am working on android application, usually when we use different app then they requires only one time user login, and when we use next time then it does not require to login again, just like Facebook ,gmail etc
i also want to have such a functionality, so that it should save the username and password in shared preference, and i am using strong loop-back API(strong loop-back is basic requirement) following code i have just written it, but i want to use Access Token for it, can have give me the idea that how to use loop-back Access Token in android...???
public boolean checkLogin() {
final SharedPreferences prefs = this.getSharedPreferences(AndroidGPSTrackingActivity.class.getSimpleName(),
this.MODE_PRIVATE);
String userName = prefs.getString("userName", "");
if (userName.isEmpty()) {
Log.i("UserName", "UserName not found.");
return false;
}
String password = prefs.getString("password", "");
if (password.isEmpty()) {
Log.i("Password", "Password not found.");
return false;
}
mCheckTask = new CheckSavedLogin(userName, password, this);
mCheckTask.execute((Void) null);
return mCheckTask.execute((Void) null);//make this return true/false
}
and also:
public class CheckSavedLogin extends AsyncTask<Void, Void, Boolean> {
public final String mUserName;
public final String mPassword;
public boolean success;
public Context context;
CheckSavedLogin(String userName, String password, Context context) {
mUserName = userName;
mPassword = password;
this.context = context.getApplicationContext();
}
protected Boolean doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://173.242.94.66/scripts/appLogin.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userName", mUserName));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(responseStr);
success = json.getBoolean("success");
Log.d("Response", responseStr);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
storeLoginDetails(mUserName, mPassword);
//RETURN TRUE HERE?
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}

Related

App signup button not working

here is my java file and i used onclick function in my xml file as same method working for login button but not for signup please help me to solve this issue.
public class signup extends ActionBarActivity {
EditText username, pass, cpass, mail, phn;
String uname, password, confirmpass, email, phone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
username = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
cpass = (EditText) findViewById(R.id.comfirmpass);
mail = (EditText) findViewById(R.id.email);
phn = (EditText) findViewById(R.id.phone);
Button signupbutton = (Button) findViewById(R.id.signupbutton);
}
//When the send button is clicked
public void sign(View v) {
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
//Method to get list value pair and form the query
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
//Data intialization and Validation
public void validate() {
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
if (password.equals(confirmpass)) {
post();
} else {
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
public void error(boolean flag, String etext) {
if (flag == true) {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
//Code to handle failure
} else {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
setContentView(R.layout.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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Method to post data to webservice
public void post() {
try
{
// Calling async task to get json
new DownloadOperation().execute();
}
catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadOperation extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
String uname = "";
String email = "";
String password = "";
String confirmpass = "";
String phone = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
//Initiate ProgressBar
dialog = ProgressDialog.show(signup.this, "Please Wait", "Registering ...");
}
#Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
dialog.dismiss();
Log.d("tag", "Result:\n" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String message = jsonObj.getString("message");
boolean error = jsonObj.getBoolean("error");
error(error,message);
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
}
Have you mention android:onClick="sign" in your signup.xml under layout directory? Please make sure it.
I think your code is corect.
add Log to sign function:
public void sign(View v) {
Log.e("tag","sign function called");
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
if corect, you can show log is: "sign function called"
simply add this on your onCreate() method
signupbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"Button is clicked", 3000).show();
///what ever you want to do on signupbtn comes here
//add this try block if you need same functionality as `sign() method`
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
});
and every time you cliecked signupbutton this method(Listener) will called.
Or
add this line in you xml file where you define the signupbutton
android:onClick="sign"
But the best way for me is to add clickListener as it makes it very clear from java class side that what is beaing called on clicking the button.

android: how to save login credentials from server to phone cache

I have web services and I want to create a class that should takes an email and password from server after authentication in hash table, and then saves email and password in shared preferences.
Try this class to call webservice in your app, i am sharing get and post both methods you can use any one as per your need.
public class CallService {
String url;
HttpEntity str1;
String str;
Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public CallService(String url1) {
this.url = url1;
}
public String getResponceWithPost() {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,5000000);
HttpConnectionParams.setSoTimeout(httpParameters,500000);
HttpConnectionParams.setTcpNoDelay(httpParameters,true);
HttpClient hc = new DefaultHttpClient(httpParameters);
HttpPost post= new HttpPost (url);
HttpResponse rp = hc.execute(post);
// //////////////
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
str = EntityUtils.toString(rp.getEntity());
Log.e("Calling service", str);
return str;
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int getResponceWithGet() {
int code = 0;
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse rp = hc.execute(get);
code= rp.getStatusLine().getStatusCode();
return code;
} catch (IOException e) {
Log.e("calling service", e.toString());
e.printStackTrace();
}
catch(Exception e)
{
Log.e("calling service", e.toString());
}
return code;
}}
this will return response from server like email password or other details.
and you can save these details in sharedpreference .
for shared preference follow this -
http://developer.android.com/guide/topics/data/data-storage.html#pref
and in your activity call your url using my call service class like this-
declare your hashTable in activity like this
Hashtable hashtable = new Hashtable();
call this method
new checkForLogin().execute();
and your async class
class checkForLogin extends AsyncTask<Void, Void,String>
{
#Override
protected void onPreExecute() {
progress= ProgressDialog.show(LoginScreen.this,"Authenticating !","Please Wait");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Parse your json data here that will be in data
CallService cl2=new CallService("your server url here");
Log.e("login url is",""+Urls.loginurl);
data=cl2.getResponceWithPost();
Log.e("server response data","data = "+data);
hashtable.put(“email″, data.getString("email"));
hashtable.put(“pass″, data.getString("pass"));
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
i hope this ll help you.

Android Check If Logged In

I'm trying to make an easy method to check if a user's saved login credentials are correct... So far I have:
public boolean checkLogin() {
final SharedPreferences prefs = this.getSharedPreferences(AndroidGPSTrackingActivity.class.getSimpleName(),
this.MODE_PRIVATE);
String userName = prefs.getString("userName", "");
if (userName.isEmpty()) {
Log.i("UserName", "UserName not found.");
return false;
}
String password = prefs.getString("password", "");
if (password.isEmpty()) {
Log.i("Password", "Password not found.");
return false;
}
mCheckTask = new CheckSavedLogin(userName, password, this);
mCheckTask.execute((Void) null);
return mCheckTask.execute((Void) null);//make this return true/false
}
and also:
public class CheckSavedLogin extends AsyncTask<Void, Void, Boolean> {
public final String mUserName;
public final String mPassword;
public boolean success;
public Context context;
CheckSavedLogin(String userName, String password, Context context) {
mUserName = userName;
mPassword = password;
this.context = context.getApplicationContext();
}
protected Boolean doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://173.242.94.66/scripts/appLogin.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userName", mUserName));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(responseStr);
success = json.getBoolean("success");
Log.d("Response", responseStr);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
storeLoginDetails(mUserName, mPassword);
//RETURN TRUE HERE?
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
I just can't figure out how to make this all return "true" or "false" based upon the respone
Usually I will provide a callback.
public interface LoginHandler
{
onLoginComplete(boolean didLogIn);
}
Then I would register the handler in the AsyncTask before executing.
asyncTask.setHandler(new MyLoginHandler());
asyncTask.execute(0);
and then back in the calling activity when it fires, you can retrieve the result through your handler.
public class MyLoginHandler implements LoginHandler
{
public void onLoginComplete(boolean didLogIn)
{
//Do what you want with didLogIn
}
}

String Initialization for Dummies

OK I am messing something simple up here.
I have three Classes all within an Activity:
public class ActivityUserAccountCreate extends Activity implements
OnClickListener {
}
private class postToHttps extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
createUserAccount();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void createUserAccount() throws ClientProtocolException, IOException {
...
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d("Posting Username", usernameFinal);
nameValuePairs.add(new BasicNameValuePair("username", "usernameFinal"));
...
}
In my Activity class I initialize three Strings which are in the layout. Basically the user enters their username in a EditText. The strings are = to get the text form the field. That all works fine, but I am trying to use those same Strings in the createUserAccount(). I believe that the Strings are null at that point, so do I have to reinitialize these same three strings again in the createUserAccount()? If so, should I do it the same way that I did in in the Activity Class?
Thanks
OK I have edited according to the recommendation below, to:
...
new postToHttps().execute(usernameFinal,passwordFinal,userEmail);
...
private class postToHttps extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String usernameFinal = params[0];
String passwordFinal = params[1];
String userEmail = params[2];
try {
createUserAccount(usernameFinal, passwordFinal, userEmail);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void createUserAccount(String usernameFinal, String passwordFinal, String userEmail) throws ClientProtocolException, IOException {
String uri = "editedout.php";
Log.d("Action", "Posting user data to php");
HttpClient client = new DefaultHttpClient();
HttpPost getMethod = new HttpPost(uri);
Log.d("Posting Location", uri);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d("Posting Username", usernameFinal);
nameValuePairs
.add(new BasicNameValuePair("username", usernameFinal));
Log.d("Posting Pass", passwordFinal);
nameValuePairs
.add(new BasicNameValuePair("password", passwordFinal));
nameValuePairs.add(new BasicNameValuePair("email", userEmail));
getMethod
.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
client.execute(getMethod);
Log.d("Action", "Finished Posting Data to PHP");
}
but am getting a crash. it looks like it is crashing in the doInBackground, but am still learning to read the LogCat.
You shouldn't have to be reinitializing anything, but if you are trying to pass in three Strings into your AsyncTask, I suggest taking advantage of the variable arguments used in doInBackground(String... params).
For example:
...
private class PostToHttps extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String username = params[0];
String firstName = params[1];
String lastName = params[2];
createUserAccount(username, firstName, lastName);
}
...
PostToHttps httpsTask = new PostToHttps();
httpsTask.execute(usernameEditText.getText().toString(),
firstNameEditText.getText().toString(),
lastNameEditText.getText().toString);
...
public void createUserAccount(String username, String firstName, String lastName)
throws ClientProtocolException, IOException {
...

Read data from database located at server in android

I have one database file whose name is menu.db and this file is located at server now i want to read data from this database.
i also have registration page on the application i am working on, as user press submit button then all the user information should be store on that database at server.
if anyone solved this problem then please help me.
if any one knows then please help me.
I have the following code. It authenticates the user password. you should call this method inside doBackground() of AsyncTask extended Class.
public boolean authenticate(String strUsername, String strPassword)
{
boolean bReturn = false;
InputStream pInputStream = null;
ArrayList<NameValuePair> pNameValuePairs = new ArrayList<NameValuePair>();
pNameValuePairs.add(new BasicNameValuePair("userid", strUsername));
pNameValuePairs.add(new BasicNameValuePair("password", strPassword));
try
{
HttpClient pHttpClient = new DefaultHttpClient();
String strURL = p_strServerIP + "Login.php";
HttpPost pHttpPost = new HttpPost(strURL);
pHttpPost.setEntity(new UrlEncodedFormEntity(pNameValuePairs));
HttpResponse pHttpResponse = pHttpClient.execute(pHttpPost);
HttpEntity pHttpEntity = pHttpResponse.getEntity();
pInputStream = pHttpEntity.getContent();
BufferedReader pBufferedReader = new BufferedReader(new InputStreamReader(pInputStream,"iso-8859-1"),8);
StringBuilder pStringBuilder = new StringBuilder();
String strLine = pBufferedReader.readLine();
pInputStream.close();
if(strLine != null)
{
if((strLine).equals("permit"))
{
bReturn = true;
}
}
}
catch (Exception e)
{
Log.e("log_tag", "Caught Exception # authenticate(String strUsername, String strPassword):" + e.toString());
}
return bReturn;
}
The class you extend from AsyncTask should be something like
class ConnectionTask extends AsyncTask<String, Void, Boolean>
{
private SharedPreferences mSettings;
private Context mContext;
ConnectionTask(SharedPreferences settings, Context context)
{
mSettings = settings;
mContext = context;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Boolean result)
{
Toast.makeText(mContext, "Authentication over.", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... params)
{
pVerifier.authenticate(params[0], params[1]);
return true;
}
}

Categories

Resources