I have build 2 projects my main one and a twitter posting one. I have imported the twitter one into the main and am now trying to hook it up. Below is the import code. The problem is I know I am missing something possibly to do with the context? I have just summarised what is contained in my main project below so you understand better (Hopefully).
import com.tweet.t.TweetToTwitterActivity;
TweetToTwitterActivity twitter = new TweetToTwitterActivity();
twitter.buttonLogin(v);
Here is the TweetToTwitterActivity
public class TweetToTwitterActivity extends Activity {
private SharedPreferences mPrefs;
/** Twitter4j object */
private Twitter mTwitter;
private RequestToken mReqToken;
public void buttonLogin(View v) {
mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
// Load the twitter4j helper
mTwitter = new TwitterFactory().getInstance();
// Tell twitter4j that we want to use it with our app
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
Log.i(TAG, "Repeat User");
loginAuthorisedUser();
} else {
Log.i(TAG, "New User");
loginNewUser();
}
}
The Logcat produces this error
09-23 11:27:40.034: ERROR/AndroidRuntime(229): java.lang.NullPointerException
09-23 11:27:40.034: ERROR/AndroidRuntime(229): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
09-23 11:27:40.034: ERROR/AndroidRuntime(229): at com.tweet.t.TweetToTwitterActivity.buttonLogin(TweetToTwitterActivity.java:74)
and point to this line.
mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
getSharedPreferences() is a method of the Context class. You are just creating an instance of TweetToTwitterActivity which extends Activity but this activity is not presently started.
One way to solve this will be to pass a Context object also to buttonLogin:
Change
public void buttonLogin(View v)to
public void buttonLogin(View v, Context context)and
mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);to
mPrefs = context.getSharedPreferences("twitterPrefs", MODE_PRIVATE);and
twitter.buttonLogin(v);to
twitter.buttonLogin(v, this);