android shared preference getting error - android

i need to store user login and password details in shared preference but i am getting error. I need to maintain user login details in session. When user login user mail and password should be get stored in edit text. From next time user can click on login button to enter directly. What i need to do now. Here is my code. When i try below code i am getting unfortunately closed error. Where i need to modify the code. What is the problem in this code.
public class MainActivity extends Activity {
Button b;
EditText email,password;
HttpPost httppost;
StringBuffer buffer;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
String email1,passw;
SharedPreferences sh_Pref;
Editor toEdit;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
DBHelper db = new DBHelper(this);
private boolean isValidEmaillId(String email){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
email = (EditText)findViewById(R.id.username);
password= (EditText)findViewById(R.id.password);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!isValidEmaillId(email.getText().toString().trim())){
Toast.makeText(getApplicationContext(), "Invalid Email Address", Toast.LENGTH_SHORT).show();
}
else if(password.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter password", Toast.LENGTH_SHORT).show();
}
else
{
email1 = email.getText().toString().trim();
passw = password.getText().toString().trim();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +Name+Phone);
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
}
});
}
void login(){
try{
final User user = new User();
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://ip:8080/ActCFWeb/login"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("email",email1)); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("pass",passw));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
System.out.println(response);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}

I suppose that You call views methods from thread. You have login method in witch you probably call to dialog or other views .You cannot access from not main thread to ui elements. You have to use handler or asynck task.

May be you are talking about this
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +sharedpreferences.getString(Name, "def").toString()+ ", "sharedpreferences.getString(Phone, "def");

Getting values from SharedPreferences storage.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String emailString = sharedPreferences.getString("email", null);
String passwordString = sharedPreferences.getString("password", null);
In the onCreate method, first check whether the preferences has values for email and password.
if((emailString != null) && (passwordString != null)) {
//Populate the email and password edit texts using stored email and password values.
etEmail.setText(emailString);
etPassword.setText(passwordString);
}
Starting an activity should be performed in main(UI) thread. You can use Handler or runOnUiThread.
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}
});
}else{
showAlert();
}

Related

how to save android SharedPreferences using retrofit and get id

I made a validation to log in using retrofit, and I have already placed sharedpreferences in the login class and in the second class. can log in, but I can't get the user ID when logging in. There have been various ways but it didn't work. anyone know the solution?
ValidationLogin Class
public void LoginUser() {
//membuat progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Tunggu proses login ...");
pDialog.show();
//mengambil data dari edittext
final String username = txtusername.getText().toString();
String password = txtpassword.getText().toString();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL).client(client)
.addConverterFactory(GsonConverterFactory.create(new Gson())).build();
RequestInterface api = retrofit.create(RequestInterface.class);
Call<ResponseLogin> call = api.login_member(id, username , password);
call.enqueue(new Callback<ResponseLogin>() {
#Override
public void onResponse(Call<ResponseLogin> call, Response<ResponseLogin> response) {
pDialog.dismiss();
if(response.isSuccessful()){
if(response.body().getResult() != null){
// menyimpan login ke session
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_EMAIL, email);
editor.apply();
//login start main activity
Intent intent = new Intent(LoginUser.this, Second.class);
Toast.makeText(LoginUser.this, "Selamat datang "+username, Toast.LENGTH_SHORT).show();
// Toast.makeText(LoginUser.this, "Selamat datang "+id, Toast.LENGTH_SHORT).show();
intent.putExtra("email", email);
intent.putExtra("id", id);
intent.putExtra("username", username);
intent.putExtra(TAG_EMAIL, email);
startActivity(intent);
finish();
} else {
Toast.makeText(LoginUser.this, "The username or password is incorrect", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginUser.this, "Error! Please try again!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseLogin> call, Throwable t) {
t.printStackTrace();
pDialog.dismiss();
Toast.makeText(LoginUser.this, "Koneksi internet terputus.", Toast.LENGTH_SHORT).show();
}
});
}
onCreate
// Cek session login jika TRUE maka langsung buka MainActivity
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, "id tidak ditemukan");
email = sharedpreferences.getString(TAG_EMAIL, "email tidak ditemukan");
if (session) {
Intent intent = new Intent(LoginUser.this, MenuUtama.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_EMAIL, email);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = txtusername.getText().toString();
String password = txtpassword.getText().toString();
if (isEmpty(username))
txtusername.setError("Username harap diisi");
else if (isEmpty(password))
txtpassword.setError("Password harap diisi");
else
LoginUser();
//Intent intent = new Intent(LoginUser.this, Second.class);
///startActivity(intent);
}
});
Second Class
sharedpreferences = getApplication().getSharedPreferences(ValidationLogin.my_shared_preferences, Context.MODE_PRIVATE);
id = sharedpreferences.getString("id", "0");
Toast.makeText(getApplication(), "ini id ke-"+ id, Toast.LENGTH_SHORT).show();
And this respon json, I was struggling to get ID
{
"status": 200,
"reason": "OK",
"success": true,
"message": null,
"result": "eyJ0eXAiOiJKV1QiLCJhbGciOiJITUFDLVNIQTI1NiJ9.eyJpZCI6IjQ5OSIsImVtYWlsIjoiYmlzbWlsbGFoYmlzYUBleGFtcGxlLmNvbSIsIm1zaXNkbiI6IjA3OTc5Nzg0NjQ5NCIsInVzZXJuYW1lIjoiYmlzbWlsbGFoYmlzYSIsInZlcmlmaWVkTWVtYmVyIjpudWxsLCJwcm9maWxlIjp7ImlkIjoiMzE2IiwiaWRfZ2VvZGlyZWN0b3J5IjpudWxsLCJmdWxsbmFtZSI6ImJpc21pbGxhaGJpc2EiLCJudW1iZXIiOiIyNzQyNDciLCJpbWFnZSI6Imh0dHBzOlwvXC9kZW1vLmtyZWRpdGltcGlhbi5jb21cL3N0b3JhZ2VcL2ltYWdlc1wvZGVmYXVsdFwvYXZhdGFyLmpwZyIsInJlY29yZCI6eyJzdGF0dXMiOiJQVUJMSVNIIiwiY3JlYXRlIjp7InVzZXIiOm51bGwsInRpbWVzdGFtcCI6eyJkYXRlIjoiMjAxOS0xMi0wMyAxNTowODozMi4wMDAwMDAiLCJ0aW1lem9uZV90eXBlIjozLCJ0aW1lem9uZSI6IkFzaWFcL0pha2FydGEifX0sInVwZGF0ZSI6eyJ1c2VyIjpudWxsLCJ0aW1lc3RhbXAiOm51bGx9fSwibWV0YWRhdGEiOnsidXNlcm5hbWUiOiJiaXNtaWxsYWhiaXNhIiwiZW1haWwiOiJiaXNtaWxsYWhiaXNhQGV4YW1wbGUuY29tIiwicGhvbmUiOiIwNzk3OTc4NDY0OTQifSwic3RhdGlzdGljIjpudWxsfX0.zIEhdU5MyNjReG_9_661FWf0_R5eZuJweyl0JNFd7X0"
}

clicking report activity nothing was happening in android

Hi in the below code when clicking the report button not going to login activity even though it's not happening anything.
In login activity first of all I am checking the login username and password using session object.
if the username and password working fine and then want to move to next activity.
Can any one help me from this issue.
Mainactivity.java
report1=(TextView)findViewById(R.id.report1);
report=(ImageView)findViewById(R.id.report);
report1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
In the below when I am putting comment for session then it's moving but after entering the username and password it was showing logcat Admin user found but not going to next activity.it was staying in same activity itself.
update Login
public class Login extends Activity {
ImageButton login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword,ustype;
TextView tv,tv1;
Boolean isInternetPresent = false;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String queryString;
String data="";
int i;
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
SessionManager session;
private ProgressDialog progressDialog;
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// session = new SessionManager(getApplicationContext());
// session.checkLogin();
// final HashMap<String, String> user = session.getUserDetails();
login = (ImageButton)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
ustype= (EditText)findViewById(R.id.usertype);
tv = (TextView)findViewById(R.id.tv);
tv1 = (TextView)findViewById(R.id.tv1);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
cd = new ConnectionDetector(getApplicationContext());
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
String username = usname.getText().toString();
String password = pword.getText().toString();
// String name = user.get(SessionManager.KEY_USERNAME);
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
queryString = "username=" + username + "&password="
+ password ;
String usertype = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.print(usertype);
if(usertype.equalsIgnoreCase("Admin user Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this, "Login Sucess",
Toast.LENGTH_LONG).show();
}
});
Intent in=new Intent(Login.this, Reports.class);
startActivity(in);
}
else if(usertype.equalsIgnoreCase("No User Found")){
runOnUiThread(new Runnable() {
public void run() {
tv1.setText("InValid UserName and Password");
}
});
}
}
}
});
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Do not use the application's context, use the context the view currently be presented.
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(v.getContext(), Login.class);
startActivity(i);
}
});

Not Moving to next Activity

Hi In my application login form with username and password checking username and password existing in the database or not.If Exist means showing one text message user found and I want to move to next activity.otherwise No such user found.
Now,clicking login button it's showing user found and not moving to next activity.
Can any one please help me to resolve this issuse.
Login.java
public class Login extends Activity {
Button login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword;
TextView tv;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String data="";
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
login = (Button)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = usname.getText().toString();
String password = pword.getText().toString();
if (username.equals("") || password.equals("")) {
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
} else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
final String queryString = "username=" + username + "&password="
+ password;
final String data = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.println("data :: "+data);
tv.setText("Response from PHP : " + data);
if(data.equalsIgnoreCase("User Found"))
{
Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login.this, Home.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(),"User not found, check query", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
}
I think you are doing mistake here :
if(data.equalsIgnoreCase("User Found")){
Toast.makeText(getApplicationContext(),"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
}
in place of getApplicationContext() write :
if(data.equalsIgnoreCase("User Found")){
Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
I think you are missing
<activity
android:name="package_name.Home"></activity>
In AndroidManifest.xml
You must define all activities in AndroidManifest.xml.
EDIT
System.out.println("data :: "+data);
if(data.equalsIgnoreCase("User Found"))
{
Toast.makeText(getApplicationContext(),"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(),"User not found, check query", Toast.LENGTH_SHORT).show();
}

Android Tweet message is not Showing on Twitter Wall

i know i have aske dthis question,but i am not getting any satisfaction solution till yet.,i registered in twitter for getting consumer key,and secret key.,i am getting login ,but when i update any message on twitter it show sme message has been updated,but when i am checkinh in my twitterid.,i am not getting any message.
public class MainActivity extends Activity {// Constants
static String TWITTER_CONSUMER_KEY = ""; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = ""; // place your consumer secret here
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String oauth_token = "";
static final String oauth_token_secret = "";
static final String PREF_KEY_TWITTER_LOGIN = "";
static final String TWITTER_CALLBACK_URL = "";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "oauth_autherize";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
private Button btnLoginTwitter;
// Update status button
private Button btnUpdateStatus;
// Logout button
private Button btnLogoutTwitter;
// EditText for update
private EditText txtUpdate;
// lbl update
private TextView lblUpdate;
private TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
new updateTwitterStatus().execute(status);
}
});
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
final String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
// Get the access token
MainActivity.this.accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
// Shared Preferences
Editor e = mSharedPreferences.edit();
e.putString(oauth_token, accessToken.getToken());
e.putString(oauth_token_secret,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
e.printStackTrace();
}
}
}
}
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
twitter4j.conf.Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
class updateTwitterStatus extends AsyncTask<String, String, String> {
private int statusId;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(oauth_token,"");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(oauth_token_secret, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
txtUpdate.setText("");
}
});
}
}
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(oauth_token);
e.remove(oauth_token_secret);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
here i am getting this image.,when i get logedin..
I think you forget to add the OAuth consumer keys and secrets into Assets in oauth_consumer.properties file, that you can get by registering your application with twitter. They have bundled keys so that you can test quickly, but it is strongly recommended that you change these keys. First, it is a security issue for your application and secondly sometimes our keys give errors because too many developers are testing.
SocialAuth Android is an Android version of popular SocialAuth Java library. Now you do not need to integrate multiple SDKs if you want to integrate your application with multiple social networks. You just need to add few lines of code after integrating the SocialAuth Android library in your app. Go to this socialauth-android. One of the best approach to integrate all social media.
Go to this link for better understanding socialauth-android .also, code available in Github

when a user exit my android app without clicking logout button the user still appears loggedin in my online database

when a user exit my android app without clicking log out button the user still appears logged in in my online database, when next he opens the app he will be directed to the log in page and he can't log in since he appears logged in in the database, please how do i solve this problem, am using the 1 and 0 form of log in. thanks
enter code here
public class MainActivity extends Activity {
private EditText username;
private EditText password;
private TextView reg;
//private TextToSpeech myTTS;
//status check code
//private int MY_DATA_CHECK_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (TextView)findViewById(R.id.reger);
username = (EditText)findViewById(R.id.UserText1);
password = (EditText)findViewById(R.id.PassText2);
// String Userid;
//String Passid= password.toString();
Button login = (Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SharedPreferences userid = getSharedPreferences("prefs",0);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username.getText().toString()));
postParameters.add(new BasicNameValuePair("password", password.getText().toString()));
postParameters.add(new BasicNameValuePair("login", "1"));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.website.com/login4.php", postParameters);
String res=response.toString();
res = res.trim();
res= res.replaceAll("\\s+","");
//reg.setText(res);
//error.setText(res);
if(username.getText().toString().equals("") || password.getText().toString().equals("")){
reg.setText("Sorry!! Incorrect Username or Password");
}
else if(res.equals(username.getText().toString()+password.getText().toString())){
SharedPreferences.Editor editor = userid.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
//speakWords("You are logged in succesfully");
startActivity(new Intent(MainActivity.this, HomePage.class));
}
else {
reg.setText(res);
}
} catch (Exception e) {
reg.setText("You have a network failure");
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, Registration.class);
startActivity(intent);
}
});
TextView freeview =(TextView)findViewById(R.id.Samp);
freeview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, Sample_year.class);
startActivity(intent);
}
});
}
// Set up an instance of SystemUiHider to control the system UI for
}
?
change the value to 0 in the onStop() method of the activity class which is called when your user navigates away from the app!
For anyone else in the future I'm using firebase so this is what I did:
if (firebaseAuth.getCurrentUser()!= null)
{
startActivity(new Intent(getApplicationContext(),NavActivity.class));
}

Categories

Resources