1

In my android application i want to upload image to twitpic. There are some images to my sd card. When i click a button then a image will be uploaded to twitpic. Here is my code...

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    uploadImage = (Button) findViewById(R.id.uploadImage);
    uploadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) 
        {
        new ImageSender().execute();

        }
    });
}

private class ImageSender extends AsyncTask<URL, Integer, Long> {
     private String url;

     protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this, "", "Sending image...", true);

mProgressDialog.setCancelable(false);
mProgressDialog.show();
}

        protected Long doInBackground(URL... urls) {
            long result = 0;

            TwitterSession twitterSession   = new TwitterSession(MainActivity.this);
            AccessToken accessToken = twitterSession.getAccessToken();

Configuration conf = new ConfigurationBuilder()
            .setOAuthConsumerKey(twitter_consumer_key)
            .setOAuthConsumerSecret(twitter_secret_key)
            .setOAuthAccessToken(accessToken.getToken())
            .setOAuthAccessTokenSecret(accessToken.getTokenSecret())
            .build();

OAuthAuthorization auth = new OAuthAuthorization (conf, conf.getOAuthConsumerKey (), conf.getOAuthConsumerSecret (),
new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()));

ImageUpload upload = ImageUpload.getTwitpicUploader (twitpic_api_key, auth);

Log.d(TAG, "Start sending image...");

try {
    String ExternalStorageDirectoryPath = Environment
              .getExternalStorageDirectory()
              .getAbsolutePath();

    String targetPath = ExternalStorageDirectoryPath + "/Friends/"+"image2.jpg";


    File targetDirector = new File(targetPath);
url = upload.upload(new File(targetDirector.getAbsolutePath()));
result = 1;

Log.d(TAG, "Image uploaded, Twitpic url is " + url);    
} catch (Exception e) { 
Log.e(TAG, "Failed to send image");

e.printStackTrace();
}

            return result;
        }

        protected void onProgressUpdate(Integer... progress) {
        }

        protected void onPostExecute(Long result) {
         mProgressDialog.cancel();

         String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";

         Toast.makeText(getApplicationContext(), text, 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;
}

}

TwitterSession class is here...

public class TwitterSession {
private SharedPreferences sharedPref;
private Editor editor;

private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";

public TwitterSession(Context context) {
    sharedPref    = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);

    editor        = sharedPref.edit();
}

public void storeAccessToken(AccessToken accessToken, String username) {
    editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
    editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
    editor.putString(TWEET_USER_NAME, username);

    editor.commit();
}

public void resetAccessToken() {
    editor.putString(TWEET_AUTH_KEY, null);
    editor.putString(TWEET_AUTH_SECRET_KEY, null);
    editor.putString(TWEET_USER_NAME, null);

    editor.commit();
}

public String getUsername() {
    return sharedPref.getString(TWEET_USER_NAME, "");
}

public AccessToken getAccessToken() {
    String token        = sharedPref.getString(TWEET_AUTH_KEY, null);
    String tokenSecret  = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);

    if (token != null && tokenSecret != null) 
    {
        AccessToken accessToken =  new AccessToken(token, tokenSecret);
        int userID = accessToken.getUserId();
        User user = null;
        try {
            user = twitter.showUser(userID);
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String username = user.getName();

        storeAccessToken(accessToken, username);
        return accessToken;
    }
    else
        return null;
}

} Here is my log-

03-27 11:47:34.427: E/AndroidRuntime(2676): FATAL EXCEPTION: AsyncTask #1 03-27 11:47:34.427: E/AndroidRuntime(2676): java.lang.RuntimeException: An error occured while executing doInBackground() 03-27 11:47:34.427: E/AndroidRuntime(2676): at android.os.AsyncTask$3.done(AsyncTask.java:299) 03-27 11:47:34.427: E/AndroidRuntime(2676): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 03-27 11:47:34.427: E/AndroidRuntime(2676): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 03-27 11:47:34.427: E/AndroidRuntime(2676): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 03-27 11:47:34.427: E/AndroidRuntime(2676): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 03-27 11:47:34.427: E/AndroidRuntime(2676): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 03-27 11:47:34.427: E/AndroidRuntime(2676): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 03-27 11:47:34.427: E/AndroidRuntime(2676): at java.lang.Thread.run(Thread.java:856) 03-27 11:47:34.427: E/AndroidRuntime(2676): Caused by: java.lang.NullPointerException 03-27 11:47:34.427: E/AndroidRuntime(2676): at com.my.androidtwitpicapplication.MainActivity$ImageSender.doInBackground(MainActivity.java:78) 03-27 11:47:34.427: E/AndroidRuntime(2676): at com.my.androidtwitpicapplication.MainActivity$ImageSender.doInBackground(MainActivity.java:1) 03-27 11:47:34.427: E/AndroidRuntime(2676): at android.os.AsyncTask$2.call(AsyncTask.java:287) 03-27 11:47:34.427: E/AndroidRuntime(2676): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 03-27 11:47:34.427: E/AndroidRuntime(2676): ... 4 more

Null Pointer is coming here

.setOAuthAccessToken(accessToken.getToken())

How can i remove the error? Thanks...

andDev
  • 275
  • 2
  • 5
  • 15

1 Answers1

0

In your method getAccessToken() either of token or tokenSecret or both are coming up null from the sharedpreference.

public AccessToken getAccessToken() {


     // either or both of them below are coming up as null
    String token        = sharedPref.getString(TWEET_AUTH_KEY, null);
    String tokenSecret  = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);

    if (token != null && tokenSecret != null) 
        //here you are retreiving the accesstoken when it is not there in the shared preference then you need to save it as well because otherwise it will create a new AccessToken every time

        AccessToken accToken =  new AccessToken(token, tokenSecret);

        storeAccessToken(accToken, userName); /// you need to sort out where the userName will come from as it is needed by your StoreAccessToken method so next time getAccessToken is called it will retrieve the AccessToken from SharedPreference

        return 
    else
        return null;
}

Now I can see from the code that storeAccessToken is storing all the information that you need above. And I can't see if it is being called. So please have look whether it is being called?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user_CC
  • 4,686
  • 3
  • 20
  • 15
  • still not. i tried to solve it in another ways but problem with sharedpreference. can u help me in this regard? – andDev Apr 07 '13 at 05:26
  • yes ofcourse i am willing to help..where is the method storeAccessToken is called from? – user_CC Apr 07 '13 at 11:28
  • actually i have to call storeAccesstoken method to store accesstoken and secret to sharedpreference. Here is my problem – andDev Apr 07 '13 at 11:52
  • so where you get the accesstoken and secret then call the storeAccessToken. But later in the code ImageSender I can see you are creating an object of AccessToken which is new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()), why are u creating a new object also you are getting the values from conf object?? can you share the AccessToken class ? and the place where you are getting the accessToken and secret values – user_CC Apr 07 '13 at 13:23
  • In both classes from import twitter4j.http.AccessToken i get AccessToken. But here is the issue to retrieve this AccessToken Token and secret from TwitterSession class. – andDev Apr 08 '13 at 04:49
  • you are creating the AccessToken in getAccessToken class that is the place where you need to store it and call the storeAccessToken method – user_CC Apr 09 '13 at 11:30
  • where i have to call the method? – andDev Apr 10 '13 at 05:58
  • in the getAccessToken() method look at my answer I have edited it and placed the call to store the token. – user_CC Apr 10 '13 at 07:53