after logged in ,remain in home_screen until logout - java

I want to send the username and password to the server and it returns a response whether the username and password matches. I do not want to ask for login each time my app starts, instead I want to remain in the home_screen until I logout from my android app. How can I do this? any example will be thankfull..
package com.example.test5;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener{
private EditText username;
private EditText password;
private Button login;
static String u;
static String p;
Context context = MainActivity.this;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);//Visibility
password = (EditText)findViewById(R.id.editText2);//Visibility
login = (Button)findViewById(R.id.button1);//Visibility
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
u = username.getText().toString();
p = password.getText().toString();
Toast.makeText(MainActivity.this, "Checking User Login",Toast.LENGTH_SHORT).show();
new MyAsyncTask_Login(context).execute(u,p);
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
my asynctask class
package com.example.test5;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.widget.Toast;
public class MyAsyncTask_Login extends AsyncTask<String, Void, String>{
public static final String MyPREFERENCES = "MyPrefs" ; //editor: never used
public static final String userName = "name";
public static final String Password = "password";
SharedPreferences sharedpreferences; //editor: never used
private Context context;
public MyAsyncTask_Login(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... params) {
String response = new Login_WebService().checkLogin(params[0], params[1]);
return response;
}
#Override
protected void onPostExecute(String result) {
String strResponse = result;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(strResponse));
List<String> tags = new LinkedList<String>();
tags.add("valid");
for (int type = parser.next(); type != XmlResourceParser.END_DOCUMENT; type = parser.next()) {
if (type == XmlResourceParser.START_TAG) {
String name = parser.getName();
if (tags.contains(name)) {
type = parser.next();
if (parser.getText().trim().equals("1")) {
Toast.makeText(context, "logged in succesfully.",Toast.LENGTH_SHORT).show();
try {
String user = MainActivity.u;
String pass = MainActivity.p;
Intent i = new Intent(context,Home_page.class);
context.startActivity(i);
}
catch (Exception e) {
Toast.makeText(context, e.toString(),Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(context, "Invalid User",Toast.LENGTH_SHORT).show();
}
}
}
}
}
catch (Exception e) {
}
}
}

You can do like this:
Save your login data in shared Preferences.
When the user login:
protected void doInBackground(Activity... params) {
Activity activity = (Activity) params[0];
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);//Pass activity in params o
Editor editor = prefs.edit();
editor.putString("username",u);
editor.putString("password",p);
editor.commit();
}
in on create when the user restart the app read the shared preferences:
u = prefs.getString("username", "");
p = prefs.getString("password", "");
if(u.equals("") || p.equals(""))
//user needs new login
else
//user already login
To make logout put "" in sharedpreferences.

Related

update one or more fields inside of a document, without updating all the fields

I have a feature in my program where I have to enter the user's details such as the user's age, height, and weight. This data will be stored in Firestore.
this is how the user will input their details
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.button.MaterialButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class account_information extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_create;
FirebaseFirestore db;
FirebaseAuth mAuth;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_information);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_create = findViewById(R.id.btn_create);
btn_create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
if(age.isEmpty()){
et_age.setError("Age is mandatory");
et_age.requestFocus();
return;
}
if(height.isEmpty()){
et_height.setError("Height is mandatory");
et_height.requestFocus();
return;
}
if(weight.isEmpty()){
et_weight.setError("Weight is mandatory");
et_weight.requestFocus();
return;
}
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = db.collection("userDetail").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("Age",age);
user.put("Height",height);
user.put("Weight",weight);
user.put("UserId", userID);
documentReference.set(user)
.addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(account_information.this, MainActivity.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}
}
And this is how it will store in firebase
https://imgur.com/a/wtCJt8X
However, when the user decides to update their profile (for example his weight) the rest of the input will pass an empty string at the firebase
like this:
https://imgur.com/oskucbl
And this is how the user can update their details
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
public class UpdateProfile extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_update;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_update = findViewById(R.id.btn_update);
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
documentReference
.update("Age",age, "Height",height, "Weight",weight)
.addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(UpdateProfile.this, MainActivity.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}}
Update: I've tried the method of #zen_of_kermit but I got the same problem, maybe there's something in the code that I've missed
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class UpdateProfile extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_update;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_update = findViewById(R.id.btn_update);
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
Map<String, Object> dataToUpdateMap = new HashMap<>();
if (isValidAndChanged(documentReference, "Age", age)) {
dataToUpdateMap.put("Age", age);
}
if (isValidAndChanged(documentReference, "Height", height)) {
dataToUpdateMap.put("Height", height);
}
if (isValidAndChanged(documentReference, "Weight", weight)) {
dataToUpdateMap.put("Weight", weight);
}
documentReference.update(dataToUpdateMap).addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(UpdateProfile.this, readProfileData.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}
boolean isValidAndChanged(DocumentReference docRef, String key, Object value) {
return true;
}
}
You are passing all three fields (age, height, weight) without checking if they are valid or contain changes to the existing data. You should make those checks before calling update, similar to how you did in the create function.
For example, create a function to check if new data is valid and different than old data:
boolean isValidAndChanged(DocumentReference docRef, String key, String value) {
// TODO get snapshot of data and compare to new value
}
And then use that to update (passing a Map to update instead of var-args):
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
Map<String, String> dataToUpdateMap = new HashMap<>();
if (isValidAndChanged(documentReference, "Age", age)) {
dataToUpdateMap.put("Age", age);
}
if (isValidAndChanged(documentReference, "Height", height)) {
dataToUpdateMap.put("Height", height);
}
if (isValidAndChanged(documentReference, "Weight", weight)) {
dataToUpdateMap.put("Weight", weight);
}
documentReference.update(dataToUpdateMap)
// ...
Also, best practice is to use constants instead of passing magic strings around all over your code (e.g. "Age" becomes AGE.)
You're getting all the data overwritten because you're passing empty strings to the update() method. Firestore can indeed hold null values, but the values of Age and Height after the update are not null, but empty strings.
If you want to update a single field and leave the other ones untouched, then you should simply pass to the update() method only values for the fields you need to update. In code, it should look like this:
documentReference.update("Weight", weight).addOnSuccessListener(/* ... /*);

Is there a way to save the data on SharedPreference?

I am trying to save data on button toggle, so that if pokemon is caught, when i run the application again, pokemon is caugt, and when released, It toggles back to "catch". But all my pokemon are displaying caught (button shows "release")
package com.example.pokedex;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PokemonActivity extends AppCompatActivity {
private TextView nameTextView;
private TextView numberTextView;
private TextView type1TextView;
private TextView type2TextView;
private String url;
private RequestQueue requestQueue;
Button button;
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon);
requestQueue = Volley.newRequestQueue(getApplicationContext());
url = getIntent().getStringExtra("url");
nameTextView = findViewById(R.id.pokedex_name);
numberTextView = findViewById(R.id.pokedex_number);
type1TextView = findViewById(R.id.pokedex_type);
type2TextView = findViewById(R.id.pokedex_type2);
button = findViewById(R.id.catcher);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
load();
}
public void load() {
type1TextView.setText("");
type2TextView.setText("");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, response -> {
try {
nameTextView.setText(response.getString("name"));
numberTextView.setText(String.format("#%03d", response.getInt("id")));
JSONArray typeEntries = response.getJSONArray("types");
for (int i = 0; i < typeEntries.length(); i++) {
JSONObject typeEntry = typeEntries.getJSONObject(i);
int slot = typeEntry.getInt("slot");
String type = typeEntry.getJSONObject("type").getString("name");
if (slot == 1) {
type1TextView.setText(type);
} else if (slot == 2) {
type2TextView.setText(type);
}
}
} catch (JSONException e) {
Log.e("cs50", "Pokemon json error", e);
}
}, error -> Log.e("cs50", "Pokemon details error", error));
requestQueue.add(request);
if (sharedpreferences.contains(nameTextView.getText().toString()))
button.setText("Release");
}
public void toggleCatch(View view) {
String name = nameTextView.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
if (button.getText().toString().toLowerCase().equals("Catch".toLowerCase())) {
//editor.clear();
editor.putString(name, name);
editor.apply();
editor.commit();
button.setText("Release");
} else if (button.getText().toString().toLowerCase().equals("Release".toLowerCase())){
editor.remove(name);
editor.apply();
editor.commit();
button.setText("Catch");
}
}
}
I have tried everything i know how to, please help.
Unmodified source code at "https://cdn.cs50.net/2019/fall/tracks/android/pokedex/pokedex.zip"
The following line of code
if (sharedpreferences.contains(nameTextView.getText().toString()))
button.setText("Release");
should go into your onResponseListener() that is your response -> ....
Currently you are calling the if statement above synchronously. This means that you are searching for not any valid Pokemon name but "" (empty string) inside SharedPreferences. In one of your tests, you probably saved empty string as a key, and you cannot undo that because any transaction after you load your pokemons includes a non-empty string Pokemon name.
If taht is indeed the case, you can easily add a temporary code inside your activity onCreate() method to remove that entry from SharedPreferences.

Where is this LoginActivity retrieving phoneno. and password from?

The LoginActivity.java is the first thing that gets run after I open the android app and a login screen is seen asking for phonenumber and password which it retrieves from a database. I have a mysql database related to this project running in my computer but how do I find exactly from where in the database the app is retrieving the phoneno. and password from?
LoginActivity.java
package com.example.ankit.mrestro.Controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.squareup.otto.Subscribe;
import com.example.ankit.mrestro.Bus.BusProvider;
import com.example.ankit.mrestro.Bus.LoginEvent;
import com.example.ankit.mrestro.Bus.LoginSuccessEvent;
import com.example.ankit.mrestro.Bus.PushRegisterEvent;
import com.example.ankit.mrestro.R;
import com.example.ankit.mrestro.model.LoginResult;
import com.example.ankit.mrestro.services.DataService;
import com.example.ankit.mrestro.services.RESTrepository;
public class LoginActivity extends Activity {
public static final String PREF_ACCOUNT_ID = "cust_id";
public static final String PREF_TOKEN = "accessToken";
public static final String SHARED_PREF_DB_NAME = "loginResult";
private ProgressDialog progressDialog;
public static Intent createIntent(Context c) {
return new Intent(c, LoginActivity.class);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataService.init();
progressDialog = new ProgressDialog(this);
/**
* Check either we are already logged in
*/
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DB_NAME, 0);
if (sharedPreferences.getString(PREF_TOKEN, "").length() != 0) {
RESTrepository.setToken(sharedPreferences.getString(PREF_TOKEN, ""));
RESTrepository.setUser_id(sharedPreferences.getInt(PREF_ACCOUNT_ID, 0));
goToMainActivity();
}
setContentView(R.layout.activity_login);
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
"hwfeocSIPlgKTasIuARPREnS");
//SharedPreferences preferences=getSharedPreferences("pushService",0);
//String userId=preferences.getString("user_id","no data");
//Toast.makeText(this,"user id is:"+userId,Toast.LENGTH_SHORT).show();
Button loginButton=(Button)findViewById(R.id.email_sign_in_button);
loginButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String phoneno=((TextView)findViewById(R.id.email)).getText().toString();
String password=((TextView)findViewById(R.id.password)).getText().toString();
// Toast.makeText(getBaseContext(),"login..."+phoneno+"..."+password,Toast.LENGTH_SHORT).show();
progressDialog.show();
BusProvider.get().post(new LoginEvent(phoneno,password));
}
});
}
#Override
protected void onResume(){
super.onResume();
BusProvider.get().register(this);
}
#Override
protected void onPause(){
super.onPause();
BusProvider.get().unregister(this);
}
#Subscribe
public void onLoginSuccessEvent(LoginSuccessEvent loginSuccessEvent){
progressDialog.hide();
LoginResult result=loginSuccessEvent.getResult();
if (result != null) {
// Toast.makeText(this,result.getCust_id()+result.getCust_name()+result.getCust_access_token(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,"Login Success",Toast.LENGTH_SHORT).show();
SharedPreferences preferences = this.getSharedPreferences(SHARED_PREF_DB_NAME, MODE_PRIVATE);
preferences.edit().putString(PREF_TOKEN,result.getCust_access_token()).commit();
preferences.edit().putInt(PREF_ACCOUNT_ID,result.getCust_id()).commit();
SharedPreferences pushPreferences=this.getSharedPreferences("pushService",0);
BusProvider.get().post(new PushRegisterEvent
(result.getCust_id(),result.getCust_access_token(),pushPreferences.getString("user_id","")));
goToMainActivity();
} else {
Toast.makeText(this, "Unable to login, please retry", Toast.LENGTH_SHORT).show();
}
}
private void goToMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
In Login Activity your on button click your are getting the the phone number and password of your sending it to the server and onLoginSuccessEvent you are getting your response and save it to the sharePreferences

Why is the password entered not comparing within my IF statement?(sharedpreference)

I am doing my my assignment, and I am not sure why If statement not getting password stored in shredpreference and compare with the password entered in this page. I really want to know which variable(s) or particular part(s) I did wrong? please help guys!!!
package com.wheresmyphone;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Check_Activity extends Activity {
public static final String passwdfile = "passwd";
String passwd;
private static final String PREF_PASSWORD = "PassWord";
protected EditText PassWordField;
protected Button EnterButton;
SharedPreferences sharedpref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_);
final EditText userpassword = (EditText)findViewById(R.id.editText1);
Button b = (Button)findViewById(R.id.button1);
sharedpref = getSharedPreferences(passwdfile, 0);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String passwd = userpassword.getText().toString();
SharedPreferences passwdfile = getSharedPreferences("passwd",0);
SharedPreferences.Editor editor = sharedpref.edit();
editor.putString(PREF_PASSWORD, passwd);
editor.commit();
//commit data
String storedpassword = passwdfile.getString(passwd, null) ;
if (passwd.equals(storedpassword)) {
startActivity(new Intent(Check_Activity.this, MainActivity.class));
finish();
}else {
Toast.makeText(Check_Activity.this, "Incorrect Password, Please try again!", Toast.LENGTH_LONG).show();
return;
}
}
});
}
You're trying to retrieve the stored password with the wrong key. That is, change:
String storedpassword = passwdfile.getString(passwd, null);
To:
String storedpassword = passwdfile.getString(PREF_PASSWORD, null);

Twitter: "This page contains too many server redirects" error

I'm trying to share some data using twitter in android app, so what ever the basic information like redirecting url, application given in the "Twitter app registration page", everything works fine but after giving the username and password in the LOGIN PAGE of twitter it doesn't redirects to the next page, instead getting "this page contains too many server redirects" error message.
My redirect url looks like this "https://www.example.com/".
Any suggestions?
public class constants {
public static final String CONSUMER_KEY = "key";
public static final String CONSUMER_SECRET= "secret";
public static final String REQUEST_URL = "http://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
public static final String OAUTH_CALLBACK_URL = "x-latify-oauth-twitter";
private static final String CALLBACK_SCHEME = null;
public static final Object OAUTH_CALLBACK_SCHEME = CALLBACK_SCHEME + "://callback";
}
MainActivity
import java.util.Date;
import oauth.signpost.OAuth;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract.Constants;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private SharedPreferences prefs;
private final Handler mTwitterHandler = new Handler();
private TextView loginStatus;
final Runnable mUpdateTwitterNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.ls);
Button tweet = (Button) findViewById(R.id.tweet);
Button clearCredentials = (Button) findViewById(R.id.cc);
tweet.setOnClickListener(new View.OnClickListener() {
* to the twitter login page. Once the user authenticated, he'll authorize the Android application to send
* tweets on the users behalf.
*/
public void onClick(View v) {
if (TwitterUtils.isAuthenticated(prefs)) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
}
});
clearCredentials.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearCredentials();
updateLoginStatus();
}
});
}
#Override
protected void onResume() {
super.onResume();
updateLoginStatus();
}
public void updateLoginStatus() {
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
private String getTweetMsg() {
return "Tweeting from Android App at " + new Date().toLocaleString();
}
public void sendTweet() {
Thread t = new Thread() {
public void run() {
try {
TwitterUtils.sendTweet(prefs,getTweetMsg());
mTwitterHandler.post(mUpdateTwitterNotification);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
private void clearCredentials() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Editor edit = prefs.edit();
edit.remove(OAuth.OAUTH_TOKEN);
edit.remove(OAuth.OAUTH_TOKEN_SECRET);
edit.commit();
}
}
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
/**
*
* We pass the OAuth consumer and provider.
*
* #param context
* Required to be able to start the intent to launch the browser.
* #param provider
* The OAuthProvider object
* #param consumer
* The OAuthConsumer object
*/
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
/**
*
* Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
*
*/
#Override
protected Void doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, constants.OAUTH_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
}
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
public class PrepareRequestTokenActivity extends Activity {
final String TAG = getClass().getName();
private OAuthConsumer consumer;
private OAuthProvider provider;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.consumer = new CommonsHttpOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(constants.REQUEST_URL,constants.ACCESS_URL,constants.AUTHORIZE_URL );
} catch (Exception e) {
Log.e(TAG, "Error creating consumer / provider",e);
}
Log.i(TAG, "Starting task to retrieve request token.");
new OAuthRequestTokenTask(this,consumer,provider).execute();
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
* The callback URL will be intercepted here.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs=prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
* for future API calls.
*/
protected Void doInBackground(Uri...params) {
final Uri uri = params[0];
final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
provider.retrieveAccessToken(consumer, oauth_verifier);
final Editor edit = prefs.edit();
edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
edit.commit();
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
consumer.setTokenWithSecret(token, secret);
context.startActivity(new Intent(context,MainActivity.class));
executeAfterAccessTokenRetrieval();
Log.i(TAG, "OAuth - Access Token Retrieved");
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
private void executeAfterAccessTokenRetrieval() {
String msg = getIntent().getExtras().getString("tweet_msg");
try {
TwitterUtils.sendTweet(prefs, msg);
} catch (Exception e) {
Log.e(TAG, "OAuth - Error sending to Twitter", e);
}
}
}
twitterUtils.java
import oauth.signpost.OAuth;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.content.SharedPreferences;
import android.provider.SyncStateContract.Constants;
public class TwitterUtils {
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
twitter.updateStatus(msg);
}
}
Change Your Call Back URL and write below Call back URL instead of your URL.
public static final String CALLBACK_URL = "x-oauthflow-twitter://callback";
And see below link for more information.
Twitter Integration in Android

Categories

Resources