I've searched out over internet. I found many solution in order to send tweets and I got that using intent it's much better.
String tweetUrl = "https://twitter.com/intent/tweet?text=PUT TEXT HERE &url="+ "https://www.google.com";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
But I just want to send tweets in background. If anybody have done this ever please share with me. my requirement is to send tweets in background when a post is posted into my social networking based application. I am able to do it in case of facebook but still struggling with Twitter.
Here below is my code to take authentication for Twitter Application:-
class twAsyn extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
askOAuth();
return null;
}
}
private void checkForSavedLogin() {
// Get Access Token and persist it
new accessUser().execute();
}
class accessUser extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
AccessToken a = getAccessToken();
// storeAccessToken(a);
loggedIUser.setTwSharing(true);
if (a!=null) {
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((TwitterApplication)getApplication()).setTwitter(twitter);
final User user;
finish();
}
return null;
}
}
private AccessToken getAccessToken() {
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
String token = settings.getString("accessTokenToken", "");
String tokenSecret = settings.getString("accessTokenSecret", "");
if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
return new AccessToken(token, tokenSecret);
}
return null;
}
private void getConsumerProvider() {
OAuthProvider p = ((TwitterApplication)getApplication()).getProvider();
if (p!=null){
provider = p;
}
CommonsHttpOAuthConsumer c = ((TwitterApplication)getApplication()).getConsumer();
if (c!=null){
consumer = c;
}
}
private void setConsumerProvider() {
if (provider!=null){
((TwitterApplication)getApplication()).setProvider(provider);
}
if (consumer!=null){
((TwitterApplication)getApplication()).setConsumer(consumer);
}
}
private void storeAccessToken(AccessToken a) {
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accessTokenToken", a.getToken());
editor.putString("accessTokenSecret", a.getTokenSecret());
editor.commit();
}
#Override
protected void onResume() {
super.onResume();
System.out.println("RESUMING!!");
if (this.getIntent()!=null && this.getIntent().getData()!=null){
Uri uri = this.getIntent().getData();
new twUserAcces(uri).execute();
}
}
class twUserAcces extends AsyncTask<String, Void, String>{
Uri uri;
String verifier;
public twUserAcces(Uri uri) {
// TODO Auto-generated constructor stub
this.uri = uri;
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
checkForSavedLogin();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
// this will populate token and token_secret in consumer
provider.retrieveAccessToken(consumer, verifier);
// Get Access Token and persist it
System.out.println(">>>>>>>> accesstoker "+consumer.getToken());
System.out.println(">>>>>>>> accesstoker "+consumer.getTokenSecret());
AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
storeAccessToken(a);
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((TwitterApplication)getApplication()).setTwitter(twitter);
Log.e("Login>>>>>>>>>>>>>>>>>>>>>.", "Twitter Initialised");
User user = null;
long h=twitter.getId();
user = (User)twitter.getUserLists(0);
finish();
} catch (Exception e) {
//Log.e(APP, e.getMessage());
e.printStackTrace();
System.out.println("e.getMessage()=="+e.getMessage());
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return null;
}
}
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider("https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token", "https://twitter.com/oauth/authorize");
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
//Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
setConsumerProvider();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
For sending tweet in java, you can use Twitter4J
Create a Twitter application: Refer here
Initialize your object: Fill in credentials by using twitter app credentials
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("")
.setOAuthConsumerSecret("")
.setOAuthAccessToken("")
.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Send your tweet
Twitter twitter = TwitterFactory.getSingleton();
Status status = twitter.updateStatus(latestStatus);
For best practices, please refer here
Related
I am using twitter4j lib,but it is not working in fragment.I have created a twitterShare java class but the fragment class is not migrating to the twitter class.I also added the twitter class but its not working.
Here is my code of fragment class. #Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button8:
try{
Intent intent=new Intent(getActivity(),TwitterView.class);
startActivity(intent);
}
catch (NullPointerException e){
AlertDialog alert=new AlertDialog.Builder(context).create();
alert.setMessage(e.getMessage());
}
break;
Here is my code of TwitterView.java.
`
public class TwitterView extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "twitter_oauth";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
private static final String PREF_USER_NAME = "befriendtest";
/* Any number for uniquely distinguish your request */
public static final int WEBVIEW_REQUEST_CODE = 100;
private ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private EditText mShareEditText;
private TextView userName;
private View loginLayout;
private View shareLayout;
private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initTwitterConfigs();
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/* Check if required twitter keys are set */
if (TextUtils.isEmpty(consumerKey) || TextUtils.isEmpty(consumerSecret)) {
Toast.makeText(this, "Twitter key and secret not configured", LENGTH_LONG).show();
return ;
}
loginLayout= findViewById(R.id.login_layout);
shareLayout= findViewById(R.id.share_layout);
mShareEditText=(EditText)findViewById(R.id.share_text);
userName=(TextView)findViewById(R.id.user_name);
loginLayout.setOnClickListener(this);
shareLayout.setOnClickListener(this);
/* Initialize application preferences */
mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
/* if already logged in, then hide login layout and show share layout */
if (isLoggedIn) {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
String username = mSharedPreferences.getString(PREF_USER_NAME, "");
userName.setText(getResources ().getString(R.string.hello) + username);
} else {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(callbackUrl)) {
String verifier = uri.getQueryParameter(oAuthVerifier);
try {
/* Getting oAuth authentication token */
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
/* Getting user id form access token */
long userID = accessToken.getUserId();
final User user = twitter.showUser(userID);
final String username = user.getName();
/* save updated token */
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
userName.setText(getString(R.string.hello) + username);
} catch (Exception e) {
Log.e("Failed to login Twitter!!", e.getMessage());
}
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_layout:
loginToTwitter();
break;
case R.id.share_layout:
final String status = mShareEditText.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(this, "Message is empty!!", Toast.LENGTH_SHORT).show();
}
}
}
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = twitter.showUser(userID);
String username = user.getName();
/* Storing oAuth tokens to shared preferences */
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.putString(PREF_USER_NAME, username);
e.apply();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
/* Reading twitter essential configuration parameters from strings.xml */
private void initTwitterConfigs() {
consumerKey = BuildConfig.CONSUMER_KEY;
consumerSecret = BuildConfig.CONSUMER_SECRET;
callbackUrl = getString(R.string.twitter_callback);
oAuthVerifier = BuildConfig.OUTH_VERIFIER;
}
private void loginToTwitter() {
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (!isLoggedIn) {
final ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
final Configuration configuration = builder.build();
final TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(oAuthVerifier);
/**
* Loading twitter login page on webview for authorization
* Once authorized, results are received at onActivityResult
* */
final Intent intent = new Intent(this, WebActivity.class);
intent.putExtra(WebActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
String verifier = data.getExtras().getString(oAuthVerifier);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
long userID = accessToken.getUserId();
final User user = twitter.showUser(userID);
String username = user.getName();
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
userName.setText(TwitterView.this.getResources().getString(
R.string.hello) + username);
} catch (Exception e) {
Log.e("Twitter Login Failed", e.getMessage());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
class updateTwitterStatus extends AsyncTask<String,String,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TwitterView.this);
pDialog.setMessage("Posting to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
String status = params[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
StatusUpdate statusUpdate = new StatusUpdate(status);
twitter4j.Status response = twitter.updateStatus(statusUpdate);
Log.d("Status", response.getText());
} catch (TwitterException e) {
Log.d("Failed to post!", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
/* Dismiss the progress dialog after sharing */
pDialog.dismiss();
Toast.makeText(TwitterView.this, "Posted to Twitter!", LENGTH_SHORT).show();
// Clearing EditText field
mShareEditText.setText("");
}
}
}
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();
}
}
}
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 10 years ago.
I followed this tutorial fully for accesing twitter api in my android application, http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tweet = txtUpdate.getText().toString();
new LoginTask().execute(tweet);
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
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();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_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());
}
}
}
}
/**
* Function to login twitter
* */
public class LoginTask extends AsyncTask<String, String, String> {
protected void onPostExecute(Bitmap result) {
boolean everythingGood = false;
if (everythingGood) {
showToast("Success!");
startActivity(new Intent());
} else {
showAlert("Error!");
}
}
private void showToast(String string) {
// TODO Auto-generated method stub
}
private void showAlert(String string) {
// TODO Auto-generated method stub
}
#Override
protected String doInBackground(String... args) {
String tweet = args[0];
loginToTwitter();
return null;
}
private void startActivity(Intent intent) {
// TODO Auto-generated method stub
}
}
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();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
public void showToast(String string) {
// TODO Auto-generated method stub
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
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(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_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());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
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);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
**Is this code is correct or not?after logged in it has to show my tweet column like update status,like that,but its not going to next stage
Android 4 throws such an exception when you do network operations in main thread.
Consider using AsyncTasks or Handlers or any other way of threading.
You can start from here:
http://android-developers.blogspot.com/2009/05/painless-threading.html
Sample:
#Override
public void onClick(View arg0) {
new LoginTask.execute();
});
class LoginTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Bitmap result) {
if (everythingGood) {
showToast("Success!");
startActivity(new Intent());
} else {
showAlert("Error!");
}
}
#Override
protected Void doInBackground(Void... params) {
loginToTwitter();
}
}
Use the async task to do this in separate thread.
http://developer.android.com/reference/android/os/AsyncTask.html
You can define another class which extends the async task and do your work in that class.
Find the below working code
public class LoginTask extends AsyncTask<Void, Void, RequestToken> {
private ProgressDialog progressDialog;
public LoginTask() {
progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading. Please wait...", false);
}
#Override
protected RequestToken doInBackground(Void... params) {
// TODO Auto-generated method stub
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
return requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
MainActivity.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected void onPostExecute(RequestToken result) {
// TODO Auto-generated method stub
MainActivity.this.setProgressBarIndeterminateVisibility(false);
progressDialog.dismiss();
try {
requestToken = result;
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch(Exception e) {
e.printStackTrace();
alert.showAlertDialog(MainActivity.this, "Internet Connection Timeout Error",
"Please try later.", false);
}
}
}
Can you put your logcat error. So that it will easy to find why you are getting null pointer exception.
Been trying to use twitter4j to post a tweet for couple days now without luck, what i want to do is for a person to post their new top score on their timeline from the app at the end of a round. Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweetr);
Button tweetr = (Button)findViewById(R.id.tweetr);
//create a new twitter configuration using user details
tweetTwitter = new TwitterFactory().getInstance();
tweetTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//create a twitter instance
// tweetTwitter = new TwitterFactory(twitConf).getInstance();
tweetr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dt.execute();
}
});
}
public class TweetTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object... values) {
/* try {
//requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
*/
try {
requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("URI", "DONE");
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
final Uri uri = getIntent().getData();
if(uri != null ){
Log.d("URI", uri.toString());
Thread th = new Thread(){
public void run(){
try {
String verifier = uri.getQueryParameter("oauth_verifier");
String oauthToken = uri.getQueryParameter("oauth_token");
RequestToken reqToken = tweetTwitter.getOAuthRequestToken(oauthToken,verifier);
AccessToken accessToken = tweetTwitter.getOAuthAccessToken(reqToken);
String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}};
th.start();
}else
Log.d("URI", "FAILED");
}
}
This is my error print out
10-23 15:35:18.661: D/TWIT ER(2392): No authentication challenges foundRelevant discussions can be found on the Internet at:
refer to the javadoc of Twitter4J
In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api#twitter.com — all other applications will receive an HTTP 401 error.