Use android sharedpreference in AsyncTask - android

I have been developing web pages with php and MySQL for years but am new to developing for Android projects. I have searched and read through all previous questions that I found concerning the subject but have not found the answer that works for my project. Currently when I run the app, all I get is errors and no download. I am posting the complete code for my Main Activity and ask if anyone can explain what I have done wrong. The data in sharedpreferences for UserId is a integer and the Date/session is a number string and the Email/eaddress is a string
package com.example.logintest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
String IgidPreference = "IgidPreference";
String UserId = "userId";
String Date = "session";
//OR SHOULD THE DECLEARATION BE??
//public static final String UserId = "userId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new VerifyLogin().execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
});
}
public class VerifyLogin extends AsyncTask<String, Void, String> {
Context ctx;
SharedPreferences pref;
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
String eaddress = arg0[0];
String today = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?Email=" + URLEncoder.encode(eaddress, "UTF-8");
data += "&Date=" + URLEncoder.encode(today, "UTF-8");
link = "http://domain.com/verifylogin.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String userId = jsonObj.getString("user_id");
String session = jsonObj.getString("session");
String error_type = jsonObj.getString("error");
String error_msg = jsonObj.getString("error_msg");
if (error_type.equals("FALSE")) {
pref = context.getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(UserId, userId);
editor.putString(Date, session);
editor.apply();
Intent intent = new Intent(MainActivity.this, Account.class);
startActivity(intent);
} else if (error_type.equals("TRUE")) {
Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

I know it has been some time since posting on the topic but I had to replace the computer, along with Android Studio and make all new project.
Here is what I have found to handle the original issue. I am putting comments inside the code to help anyone else who wants to use code for their next project.
public class LoginActivity extends Activity { //Standard Activity code
Button BtnLaunchSigninActivity; //Button to click
private EditText etLoginUserName, etLoginPassword; // data to submit
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etLoginUserName = (EditText) findViewById(R.id.etLoginUserName);
etLoginPassword = (EditText) findViewById(R.id.etLoginPassword);
BtnLaunchSigninActivity = (Button) findViewById(R.id.btnLoginSignin);
BtnLaunchSigninActivity.setOnClickListener(onClickListener);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnLoginSignin) {
signin(v);
}
}
};
public void signin(View v) {
String userName = etLoginUserName.getText().toString();
String passWord = etLoginPassword.getText().toString();
Toast.makeText(this, "Signing In...", Toast.LENGTH_SHORT).show();
new SignIn(this).execute(userName, passWord); // Send data to AsyncTask
}
private class SignIn extends AsyncTask<String, Void, String> {
private Context context; // context is for the SignIn()
SignIn(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String userName = arg0[0];
String passWord = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
link = "url/login.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result; // My php returns jsonobjects
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result; //turn object into string
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String status = jsonObj.getString("status");
String userid = jsonObj.getString("uid");
String hash = jsonObj.getString("security");
Log.d("tag", jsonObj.toString(4));
if (status.equals("Good")) {
Toast.makeText(context, "Sign In successful.", Toast.LENGTH_SHORT).show();
//YOU HAVE TO USE JSONSTR TO GET USERID AND SECHASH FOR UPDATING SHARED PREFERENCES
//DUE TO ANY POSSIBLE DELAYS OF PROCESSING doInBackground() SEND JSON TO NEXT ACTIVITY TO SET PREFERENCES
//ADD THE STRING TO THE INTENT BELOW, THEN PROCESS THE DATA FOR SETTING SHAREDPREFERENCES IN THE NEXT ACTIVITY
Log.d("UserID",userid);
Log.d("SecHash", hash);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Bundle extras = new Bundle();
extras.putString("USERID",jsonObj.getString("uid"));
extras.putString("SECHASH",jsonObj.getString("security"));
extras.putString("USERID","userid");
extras.putString("SECHASH","hash");
intent.putExtras(extras);
startActivity(intent);
} else if (status.equals("Wrong")) {
Toast.makeText(context, "Username/Password is incorrect, could not be verified. Sign In failed.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
}
In next activity get the extras from the intent and add them to the sharedPreferences. That is all there is to it.
Thanks to everyone for their assistance before. I hope this will help others who find themselves with the same problem in the future.

In doInBackground() you define a locale variable but use a members variable
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
Since you only assign pref in onPostExecute() you'll get NullPointerExceptions everytime. Also ctx is null and context is not even declared. So make sure you have pref defined as early as possible.
public class VerifyLogin extends AsyncTask<String, Void, String> {
private final SharedPreferences pref;
VerifyLogin() {
pref = getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
}
[...]
}
But in the end you should not implement it like this at all. You'll leak your activity here!

Related

android java : persisitent login application

I am trying to make an persistent login application which then read sms from my phone and sends them to the an api with meaage body as well as the date and sender information. How can I proceed for the same.
I have made the login app but persistent login like facebook and other applications is not working.
Here is my code for the login application:
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class LoginActivity extends ActionBarActivity {
private EditText un,pw;
private Button sign;
private TextView msg;
private String resp, errorMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_Username);
pw = (EditText) findViewById(R.id.et_Password);
sign = (Button) findViewById(R.id.bt_SignIn);
msg = (TextView) findViewById(R.id.tv_error);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
pw.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
url,
postParameters);
String res = response.toString();
System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I tried this now,got the idea for shred prefernece but somewhow its not working for me
I tried this it doesn't show my main activity:
Can you find the problem:
MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class MainActivity extends Activity {
private String resp, errorMsg;
private EditText username,password;
/*public static final String MyPREFERENCES = "MyPrefs" ;
public static final String name = "nameKey";
public static final String pass = "passwordKey";
SharedPreferences sharedpreferences;*/
SessionManager session;
private TextView msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
msg = (TextView) findViewById(R.id.tv_error);
session = new SessionManager(this);
}
#Override
protected void onResume() {
//sharedpreferences=getSharedPreferences(MyPREFERENCES,
// Context.MODE_PRIVATE);
if (session.getuser()!=null)
{
if(session.getpassword()!=null){
Intent i = new Intent(this,
Welcome.class);
startActivity(i);
}
}
super.onResume();
}
public void login(View view){
String u = username.getText().toString();
String p = password.getText().toString();
{
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
username.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
password.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
"<url>",
postParameters);
String res = response.toString();
//System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
if (resp.contains("false")) {
session.saveSession(u, p);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Welcome:
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class Welcome extends Activity {
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//. getMenuInflater().inflate(R.menu, menu);
return true;
}
public void logout(View view){
session.logoutUser();
moveTaskToBack(true);
Welcome.this.finish();
}
public void exit(View view){
moveTaskToBack(true);
Welcome.this.finish();
}
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/inbox");
ContentResolver cr = this.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
this.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
if(c.getString(c.getColumnIndexOrThrow("address")).contains("icicib")|| c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk") || c.getString(c.getColumnIndexOrThrow("address")).contains("dbalrt")
||c.getString(c.getColumnIndexOrThrow("address")).contains("citibk")||c.getString(c.getColumnIndexOrThrow("address")).contains("unionb")||c.getString(c.getColumnIndexOrThrow("address")).contains("atmsbi")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbiinb") || c.getString(c.getColumnIndexOrThrow("address")).contains("indusb") ||c.getString(c.getColumnIndexOrThrow("address")).contains("fedbnk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("kotakb")||c.getString(c.getColumnIndexOrThrow("address")).contains("axisbk")||c.getString(c.getColumnIndexOrThrow("address")).contains("pnbsms")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("hsbcin") || c.getString(c.getColumnIndexOrThrow("address")).contains("canbnk") || c.getString(c.getColumnIndexOrThrow("address")).contains("idbi")
||c.getString(c.getColumnIndexOrThrow("address")).contains("iob") || c.getString(c.getColumnIndexOrThrow("address")).contains("citibk") || c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk")
||c.getString(c.getColumnIndexOrThrow("address")).contains("fromsc") ||c.getString(c.getColumnIndexOrThrow("address")).contains("myamex") || c.getString(c.getColumnIndexOrThrow("address")).contains("26463872")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbicrd") || c.getString(c.getColumnIndexOrThrow("address")).contains("icici?") || c.getString(c.getColumnIndexOrThrow("address")).contains("syndbk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("121") || c.getString(c.getColumnIndexOrThrow("address")).contains("best deal(121)") || c.getString(c.getColumnIndexOrThrow("address")).contains("airtel")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("vfcare") || c.getString(c.getColumnIndexOrThrow("address")).contains("vodafone") || c.getString(c.getColumnIndexOrThrow("address")).contains("mytsky")||c.getString(c.getColumnIndexOrThrow("address")).contains("dishpy") ) {
objSms = new Sms();
objSms.setAddress(c.getString(c .getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
lstSms.add(objSms);
}
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS");
// }
c.close();
return lstSms;
}
}
SessionManager:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREFER_NAME = "AndroidExamplePref";
public static final String KEY_USER = "username";
public static final String KEY_PWD = "password";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void saveSession(String user, String pwd){
editor.putString(KEY_USER, user);
editor.putString(KEY_PWD, pwd);
editor.commit();
}
public String getuser()
{
String s = pref.getString(KEY_USER,"");
return s;
}
public String getpassword()
{
String p = pref.getString(KEY_PWD,"");
return p;
}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context,.MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package=".sample" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.read_sms" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Welcome"
android:label="#string/title_activity_welcome" >
</activity>
</application>
</manifest>
UPDATED ANSWER:
IT works now
i made session as static and before logging I am checking the shared preference value and accordingly going ahead. Everything is working now.
I guess you are meaning "persistent login application" -> User will log in once & for the next time they will not need to log in again with user name & password, right?
For this the naive approach would be storing the username & password in shared preference / db. But its not a good approach as it stores the password.
Instead of doing this, you can store, the userId/access token (obtained from the response). You should also have an expiration time so that you can prompt for log in validating the userId/access token after certain time.
Facebook seems to do the same thing I guess. E.g. if you clear data from on facebook app, then you does need to log in again.
I hope this gives you a direction.
Updated Answer
I guess you are not clear about pref.getString() method. The overloaded method (with 2 param) will return the 2nd param you sent, if any value with the query KEY (the 1st param)is not found.
In your case, in
public String getuser()
{
String s = pref.getString(KEY_USER,""); // here is the error, "" is not null, its an empty String.
return s;
}
So you can change this trouble causing line into either of the following line-
String s = pref.getString(KEY_USER,null);
or
String s = pref.getString(KEY_USER);
Same problem in the getuser(). Hopefully this will solve your problem :)

How do I post and retrieve tweets in an Android app?

I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
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.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#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 class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
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;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation

Facebook login fragment closes application, using Facebook SDK 3.0.1

I'm developing an Android app that should integrate with Facebook. I have gone through official guide and several other guides and I think I have implemented everything correctly with the Facebook login framgent.
However the SDK performs a successful login only the first time. If I log out and try again the application just closes without any exception. The same happens if I kill my app and start it from the application list.
I can reproduce it in both the emulator and on the real device (Nexus 7).
LoginActivity.java:
package com.everporter.everporter;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import com.everporter.everporter.FBLoginFragment.OnFBAccessTokenPass;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivity extends FragmentActivity
implements OnFBAccessTokenPass {
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
private static final String REST_METHOD_NAME = "/login/";
private static final String SOCIAL_REST_METHOD_NAME = "/validation/";
private static final String TAG = "UserLoginTask";
private static final String FB_TAG = "UserFacebookLoginTask";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
private UserFacebookLoginTask mFacebookAuthTask = null;
private String mFacebookAccessToken;
private String mFacebookUserId;
// API URL read from the settings (set in main activity)
private String mRestApiUrl;
private int mConnectionTimeout;
private int mReadTimeout;
private SharedPreferences mPrefs;
// Error message set by the async task, if the error does happen indeed
private String mAsyncTaskErrorMsg;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
private String mSessionCookie; // our session
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mPrefs = getSharedPreferences("settings", MODE_PRIVATE);
mRestApiUrl = mPrefs.getString("api_url", "");
mConnectionTimeout = mPrefs.getInt("connection_timeout", 3000);
mReadTimeout = mPrefs.getInt("read_timeout", 3000);
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Handle Facebook login
*/
#Override
public void onFBAccessTokenPass(String accessToken, String uid) {
// we are passed Facebook access token, successful login
Log.i(TAG, "Facebook access token: " + accessToken);
mFacebookAccessToken = accessToken;
mFacebookUserId = uid;
// Show a progress spinner, and kick off a background task to
// sent the FB token to the server.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mFacebookAuthTask = new UserFacebookLoginTask(this);
mFacebookAuthTask.execute((Void) null);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
mAsyncTaskErrorMsg = "";
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address or phone number.
if (TextUtils.isEmpty(mEmail)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(mEmail).matches() &&
!PhoneNumberUtils.isGlobalPhoneNumber(mEmail)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask(this);
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
public UserLoginTask(Context context) {
this.mContext = context;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.i(TAG, "Begin auth...");
HttpURLConnection conn = null;
StringBuilder sb = new StringBuilder();
BufferedOutputStream printout;
boolean signedInOk = false;
try {
URL url = new URL(mRestApiUrl + REST_METHOD_NAME);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(mConnectionTimeout);
conn.setReadTimeout(mReadTimeout);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("password", mPassword);
jsonParam.put("username", mEmail);
// Send POST output.
printout = new BufferedOutputStream(conn.getOutputStream());
printout.write(jsonParam.toString().getBytes("UTF-8"));
printout.flush();
printout.close();
int httpCode = conn.getResponseCode();
if (httpCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
Log.i(TAG, sb.toString());
JSONObject jsonResponse = new JSONObject(sb.toString());
int resultCode = jsonResponse.getInt("code");
if (resultCode == 0) {
// get the session id
String cookie = conn.getHeaderField("Set-Cookie");
if (cookie != null) {
Log.i(TAG, cookie);
signedInOk = true;
mSessionCookie = cookie;
Log.i(TAG, "Authenticated");
}
} else if (resultCode == 2 || resultCode == 3) {
signedInOk = false; // wrong login and password
} else {
// get the error message
if (!jsonResponse.isNull("message")) {
mAsyncTaskErrorMsg = jsonResponse.getString("message");
} else {
mAsyncTaskErrorMsg = getString(R.string.internal_error);
}
}
} else{
Log.e(TAG, conn.getResponseMessage());
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} finally {
if (conn != null)
conn.disconnect();
}
Log.i(TAG, "End auth...");
return signedInOk;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// store the userId
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("session_cookie", mSessionCookie);
ed.putLong("session_cookie_time", System.currentTimeMillis());
ed.apply();
// start main
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
} else {
if (!mAsyncTaskErrorMsg.isEmpty()) {
// show the error message
new AlertDialog.Builder(mContext)
.setTitle("Error occured")
.setMessage(mAsyncTaskErrorMsg)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
/**
* Represents an asynchronous login task used to authenticate
* the user via Facebook.
*/
public class UserFacebookLoginTask extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
public UserFacebookLoginTask(Context context) {
this.mContext = context;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.i(FB_TAG, "Begin Facebook validation...");
HttpURLConnection conn = null;
StringBuilder sb = new StringBuilder();
BufferedOutputStream printout;
boolean signedInOk = false;
try {
URL url = new URL(mRestApiUrl + SOCIAL_REST_METHOD_NAME);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(mConnectionTimeout);
conn.setReadTimeout(mReadTimeout);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("provider", "facebook");
jsonParam.put("token", mFacebookAccessToken);
jsonParam.put("uid", mFacebookUserId);
// Send POST output.
printout = new BufferedOutputStream(conn.getOutputStream());
printout.write(jsonParam.toString().getBytes("UTF-8"));
printout.flush();
printout.close();
int httpCode = conn.getResponseCode();
if (httpCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
Log.i(FB_TAG, sb.toString());
JSONObject jsonResponse = new JSONObject(sb.toString());
int resultCode = jsonResponse.getInt("code");
if (resultCode == 0) {
// get the session id
String cookie = conn.getHeaderField("Set-Cookie");
if (cookie != null) {
Log.i(FB_TAG, cookie);
signedInOk = true;
mSessionCookie = cookie;
Log.i(FB_TAG, "Authenticated");
}
} else if (resultCode == 2 || resultCode == 3) {
signedInOk = false; // no such user in the database
mAsyncTaskErrorMsg = "";
} else {
// get the error message
if (!jsonResponse.isNull("message")) {
mAsyncTaskErrorMsg = jsonResponse.getString("message");
} else {
mAsyncTaskErrorMsg = getString(R.string.internal_error);
}
}
} else{
Log.e(FB_TAG, conn.getResponseMessage());
}
} catch (JSONException e) {
Log.e(FB_TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} catch (IOException e) {
Log.e(FB_TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} finally {
if (conn != null)
conn.disconnect();
}
Log.i(FB_TAG, "End auth...");
return signedInOk;
}
#Override
protected void onPostExecute(final Boolean success) {
mFacebookAuthTask = null;
showProgress(false);
if (success) {
// store the userId
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("session_cookie", mSessionCookie);
ed.putLong("session_cookie_time", System.currentTimeMillis());
ed.apply();
// start main
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
} else {
if (!mAsyncTaskErrorMsg.isEmpty()) {
// show the error message
new AlertDialog.Builder(mContext)
.setTitle("Error occured")
.setMessage(mAsyncTaskErrorMsg)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
}
}
#Override
protected void onCancelled() {
mFacebookAuthTask = null;
showProgress(false);
}
}
}
FBLoginFragment.java:
package com.everporter.everporter;
import java.util.Arrays;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class FBLoginFragment extends Fragment {
private static final String TAG = "FBLoginFragment";
private UiLifecycleHelper mUiHelper;
private OnFBAccessTokenPass mTokenPasser;
private String mSessionToken;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
mSessionToken = session.getAccessToken();
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// pass the access token to the activity
// with the user id
mTokenPasser.onFBAccessTokenPass(mSessionToken, user.getId());
}
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
mSessionToken = "";
}
}
public interface OnFBAccessTokenPass {
public void onFBAccessTokenPass(String accessToken, String uid);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
mTokenPasser = (OnFBAccessTokenPass) a;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUiHelper = new UiLifecycleHelper(getActivity(), callback);
mUiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fb_login_fragment, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("email"));
return view;
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
mUiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mUiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
mUiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mUiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mUiHelper.onSaveInstanceState(outState);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.everporter.everporter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.everporter.everporter.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.everporter.everporter.LoginActivity"
android:label="#string/title_activity_login"
android:noHistory="true"
android:excludeFromRecents="true"
android:windowSoftInputMode="adjustResize|stateVisible" >
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/fb_app_id"/>
<activity android:name="com.facebook.LoginActivity" android:label="#string/app_name"></activity>
</application>
</manifest>
After spending a day on this issue I have found the reason: my activity had android:noHistory="true" in the manifest which prevented Facebook SDK from launching my activity when the session was opened. Whew!!

Android Async Task Error with ClientService

I am creating simple system that has a windows service running, complete with a table of users, and I want to validate someone's login credentials by sending something to the service. I am trying to send their username and password, but I keep getting an error with my Async Task. I know that you're not supposed to mess with UI stuff in there and I am not. Originally I had a call to another activity in there but I commented it out. Now the only thing in doInBackground is setting a boolean value to true if the validation was good. From there I read the value after the async has executed, and then put together a bundle to move to the next place. I just don't know what's wrong here. It has been awhile since I've programmed in Android so maybe I'm missing something stupid. If anyone could help me out I would greatly appreciate it! Thank you. This could also be an issue with sending the information to the service?
UPDATE: After adding in the internet usage in the manifest, if I have the log.d in the program in my doInBackground, it prints out. If I don't have it, the result value stays false. It looks like there is some issue with the connection between my service and android app...
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final int DATA_FROM_MAIN_ACTIVITY = 1;
private static final String SERVICEURL = "http://localhost:56638/ClientService.svc";
private EditText userTextBox, passTextBox;
private Button loginButton;
private String uName, pass;
private Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userTextBox = (EditText) findViewById(R.id.userTextBox);
passTextBox = (EditText) findViewById(R.id.passTextBox);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
if (result.equals(true)) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).show();
}
}
});
}
#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;
}
private class SendLoginMessage extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// Log.d("message almost at server, " + textFromArea, selected,
// null);
}
#Override
protected Void doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals(true)) {
result = true;
// creating an intent to take user to next page.
// load their DB objects on the
// on create in other activity
// pass the username/password to next activity
// then make a request to the server for their database
// objects.
// Intent goToMainScreen = new
// Intent(getApplicationContext(), MainActivity.class);
// goToMainScreen.putExtra("username", names[0]);
// goToMainScreen.putExtra("password", names[1]);
// startActivityForResult(goToMainScreen,
// DATA_FROM_MAIN_ACTIVITY);
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Toast.makeText(getApplicationContext(),
// .show();
}
}
}
Do it like this:
private class SendLoginMessage extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals("true")) {
return true;
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).show();
}
}
}
and in your onClick() just call execute()
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
After execution is finished onPostExecute() will be called and your Activity will start depending on result variable.
Don't check your result variable after you invoke execute() because execute() is invoked asynchronously. By the time you check your global result variable, your doInBackground() might not have been finished. Using my approach you don't need a global variable. Please read doc carefully before using any component.

want to interrupt a thread but thread is null

I want to interrupt a thread1 from another thread2 but when I try make the thread1.interrupt(); call I get a null pointer error.
I'm making an android app, I'm on an android login page and when I login I create and start a thread called sessionTimer (which does a session countdown say 2min). What I want is that when I press logout in a different activity that I go to the login page and my sessionTimer thread should be interrupted so that I can start a new login session with max time.
package com.AndroidApp.Login;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.AndroidApp.R;
import com.AndroidApp.domain.Utente;
import com.AndroidApp.pagine.MenuPagina;
public class LoginActivity extends Activity {
final String TAG = "LogIN";
ArrayList<HashMap<String, String>> mylist;
private Button bLogin, bExit;
private EditText utente, passwd;
private MediaPlayer mpButtonClick = null;
private SharedPreferences mPreferences;
public volatile Thread sessionTimer;
public long tId = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
editor.commit();
String nome = mPreferences.getString("nome", "Nessuno");
setTitle("Sessione di : " + nome);
Log.w("TotThreads", Integer.toString(Thread.activeCount()));
/*
final SessionTimer st = new SessionTimer();
*/
if(MenuPagina.reset){
Log.w("sessionTimer ID", Long.toString(sessionTimer.getId()));
if (sessionTimer == null)
Log.w("sessionTimer", "sessionTimer is NULL");
sessionTimer.interrupt();
System.out.println("end current session");
//st.stopRequest();
}
if (!checkLoginInfo()) {
mpButtonClick = MediaPlayer.create(this, R.raw.button);
bLogin = (Button)findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mpButtonClick.start();
Log.v(TAG, "Trying to Login");
utente = (EditText)findViewById(R.id.etUtente);
passwd = (EditText)findViewById(R.id.etPassword);
String username = utente.getText().toString();
username = ("ccce#eex.it");
String password = md5(passwd.getText().toString());
password = md5("12345");
XMLFunctionsLogin.getInstance().setNewURL("u=" + username + "&p=" + password);
String xml = XMLFunctionsLogin.getXML();
Document doc = XMLFunctionsLogin.xmlFromString(xml);
int status = XMLFunctionsLogin.errStatus(doc);
Log.v("status", Integer.toString(status));
if ((status == 0)) {
NodeList nodes = doc.getElementsByTagName("login");
Element e = (Element) nodes.item(0);
Utente utente = new Utente();
utente.setIdUtente(XMLFunctionsLogin.getValue(e, "idUtente"));
utente.setNome(XMLFunctionsLogin.getValue(e, "nome"));
utente.setCognome(XMLFunctionsLogin.getValue(e, "cognome"));
Log.v("utente", utente.getCognome().toString());
List<NameValuePair> nvps = new ArrayList<NameValuePair>(2);
nvps.add(new BasicNameValuePair("utente", username));
nvps.add(new BasicNameValuePair("password", password));
Log.v(TAG, nvps.get(0).toString());
Log.v(TAG, nvps.get(1).toString());
// Store the username and password in SharedPreferences after the successful login
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("userName", username);
editor.putString("password", password);
editor.putString("idUtente", utente.getIdUtente());
editor.putString("nome", utente.getNome());
editor.putString("cognome", utente.getCognome());
editor.commit();
Log.v(TAG, "timer");
Log.v("RESET", Boolean.toString(MenuPagina.reset));
/*
Thread t = new Thread(st);
t.start();
*/
sessionTimer = new Thread() {
#Override
public void run() {
long tId = Thread.currentThread().getId();
Log.w("TTthread Id", Long.toString(tId));
for (int i = 30; i >= 0; i -= 1) {
if ((i == 0) || (MenuPagina.reset)) {
System.out.print("timer finito");
Log.i("Timer", "timer finito");
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this, "ti si รจ scaduta la sessione", Toast.LENGTH_LONG).show();
}
});
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//System.exit(0);
} try {
Thread.sleep(1000);
Log.i("Timer", Integer.toString(i));
} catch (InterruptedException e) {
Log.i("Catch", "Catchhhhhhhhhhhh");
e.printStackTrace();
Thread.currentThread().interrupt();
return;
}
}
}
};
sessionTimer.start();
Log.v(TAG, "Successo2");
Toast.makeText(LoginActivity.this, "LogIn con successo", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext()/*LoginActivity.this*/, MenuPagina.class);
startActivity(intent);
} else {
final String errorMessage = XMLFunctionsLogin.errStatusDesc(doc);
Log.v("fallimento", errorMessage);
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
});
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
});
bExit = (Button)findViewById(R.id.bExit);
bExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mpButtonClick.start();
finish();
}
});
}
}
//Checking whether the username and password has stored already or not
private final boolean checkLoginInfo() {
boolean username_set = mPreferences.contains("UserName");
boolean password_set = mPreferences.contains("PassWord");
if ( username_set || password_set ) {
return true;
}
return false;
}
//md5 for crypting and hash
private static String md5(String data) {
byte[] bdata = new byte[data.length()];
int i;
byte[] hash;
for (i = 0; i < data.length(); i++)
bdata[i] = (byte) (data.charAt(i) & 0xff);
try {
MessageDigest md5er = MessageDigest.getInstance("MD5");
hash = md5er.digest(bdata);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
StringBuffer r = new StringBuffer(32);
for (i = 0; i < hash.length; i++) {
String x = Integer.toHexString(hash[i] & 0xff);
if (x.length() < 2)
r.append("0");
r.append(x);
}
return r.toString();
}
}
So what happens is when I logout and I come back to the login page and MenuPagina.reset = true I get an error saying that sessionTimer is null. Why?
I've tried also using a seperate class for the thread but I get the same null pointer error.
onCreate runs when your Activity is being created or re-created, either way it's a new object, so any local variables have to be initialized again, in your case sessionTimer would be null until the new Thread() {} call.
If you need to persist a reference to your thread, use more global object than your Activity is - Application, that's a base class for maintaining global application state. You can always access it by calling Context.getApplicationContext(). Anyway, read the docs.

Categories

Resources