-1

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

Maruthi042
  • 145
  • 1
  • 5
  • 16
  • 1
    try to call this function in the Asynctask – Aashish Bhatnagar Feb 25 '13 at 07:21
  • any network interaction should be performed in separate thread than main thread, try using AyncTask or Thread – Waqas Feb 25 '13 at 07:25
  • Do you have `` in your AndroidManifest.xml file? – Red Cricket Feb 25 '13 at 07:26
  • which function.private void loginToTwitter() is this function i have to call from asynctask.i already having one asyncatask for update twitter status,you see that above link,which i take this one,and tell me how can i change – Maruthi042 Feb 25 '13 at 07:26
  • @RedCricket ya i have that manifest functionality before itself – Maruthi042 Feb 25 '13 at 07:27
  • @Waqas and @ Aashish,can you please tell me, i already having Asynctask class for update twitter status,is this possible to write one more asynctask for loging,and how can i write for that one. – Maruthi042 Feb 25 '13 at 07:29
  • My code doesnt show any error,but after clicking the sign in button,its not going to next step,some lock symbol is showing in loading area,and stay that page itself – Maruthi042 Feb 26 '13 at 08:10
  • trivial NetworkOnMainThreadException, -1 for not bothering to search – njzk2 Feb 26 '13 at 12:37
  • can you tell me,what are the changes i need to do in my code,paste some answer after edit my code – Maruthi042 Feb 26 '13 at 12:39
  • @njzk2 tell me what are the changes needed in my code or edit my code and tell the correct answer – Maruthi042 Feb 26 '13 at 12:44
  • instead of logging e.getMessage() (very bad practice btw), e.printStackTrace() and post stacktrace here – njzk2 Feb 26 '13 at 12:46
  • @njzk2 i am new to android,can you edit my code and do it for me – Maruthi042 Feb 26 '13 at 12:48

3 Answers3

1

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();
    }
}
agamov
  • 4,407
  • 1
  • 27
  • 31
  • i already used asynctask for update twitter status in my code,is this corret to use one more for login. – Maruthi042 Feb 25 '13 at 09:12
  • I edited my answer. you can create many asynctasks, or you can use one with parameters, and in your doInBackground check the parameters and decide what to do. – agamov Feb 25 '13 at 10:07
  • http://pastebin.com/SxV1R1ZF this is my java code,can you tell me,how to edit these one, – Maruthi042 Feb 25 '13 at 10:22
  • ,i think you are telling correct one,can you see my code and tell me or edit your code according to my code and tell me fully,bcz i am new to this – Maruthi042 Feb 25 '13 at 10:31
  • ,i changed my code,now its not working – Maruthi042 Feb 25 '13 at 11:05
  • http://pastebin.com/QdSjJy1p it also doesnt work – Maruthi042 Feb 25 '13 at 11:08
  • ,can you look at my code,its now showing any error,but if i click the login button,its not showing anything – Maruthi042 Feb 25 '13 at 11:16
  • you should not call to startActivity or Toast.show() in doInBackground() method! This method runs in separate (not the UI) thread. Use onPreExecute() and onPostExecute() for all the UI issues (showing toasts, starting activities etc.) – agamov Feb 25 '13 at 11:43
  • can you tell me,how can i do that one. – Maruthi042 Feb 25 '13 at 11:46
  • can you edit your code,which one is suitable for my code. – Maruthi042 Feb 25 '13 at 11:48
  • 1
    edited my code, your code should be smth similar – agamov Feb 25 '13 at 11:53
  • thank you i will make some changes now its working,but after getting my activity its returned to the first step, – Maruthi042 Feb 25 '13 at 12:22
  • tnx dude,it will working before the steps tweet we are typing,then it will come back without permission,can you look at my code its pasted in answer – Maruthi042 Feb 25 '13 at 12:51
  • right now its showing error in logcat as 02-25 13:06:28.878: E/Twitter Login Error(801): > null if i click the login button its buffering,but after some time,in the buffering area it shows lock symbol and return back. – Maruthi042 Feb 25 '13 at 13:12
  • Dude can you see my code and tellme,why its happening – Maruthi042 Feb 25 '13 at 13:13
  • Dude the problem is its returns null to the login loginToTwitter(); return null; how to solve that one dude – Maruthi042 Feb 25 '13 at 13:32
  • i have put my new code,its working but after clicking the signin button,its not loading,some lock symbol is showing – Maruthi042 Feb 26 '13 at 07:06
  • ,i am working ur code,its working but after clicking the sign in button,it is staying the same step, think that problem showing in return null;after the loginToTwitter(); line,can you tell how to solve that one – Maruthi042 Feb 26 '13 at 08:18
  • Dude r u there, protected Void doInBackground(Void... params) { loginToTwitter(); }if i used this statment,it asked return,if i code that one,my login having problem – Maruthi042 Feb 26 '13 at 09:23
  • @agamav,its not working while clicking the sign in button – Maruthi042 Feb 26 '13 at 12:07
0

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.

AsimJawaid
  • 66
  • 5
  • how can i do this in my code,have you seen my code,i already having asynctask for update status,is this possible to write another asyntask ,if it is possible means tell me how to write asynctask for login functionality – Maruthi042 Feb 25 '13 at 07:54
  • how to use the task for login – Maruthi042 Feb 25 '13 at 09:41
  • write your login code in the doInBackground method of the async task. Create an object of the async task class and run its execute method. Async task class will execute your login code in another thread. – AsimJawaid Feb 25 '13 at 10:01
  • http://pastebin.com/SxV1R1ZF this is my code,can you tell me how to do that one – Maruthi042 Feb 25 '13 at 10:28
  • http://pastebin.com/QdSjJy1p i changed my code,can you check and tell,my code is not working – Maruthi042 Feb 25 '13 at 11:07
  • Dude can you see my code,and tell me one time it woked,right now in buffering area,its showing some lock symbol and showing one error in logcat 02-25 13:06:28.878: E/Twitter Login Error(801): > null – Maruthi042 Feb 25 '13 at 13:19
  • Maruthi042 answer solve ur problem. I also have the same solution. – AsimJawaid Feb 25 '13 at 14:08
  • jawaid,do you have the solution for that one. – Maruthi042 Feb 26 '13 at 04:38
  • my error of problem is after get my login,its back to the previous one,02-26 04:44:23.044: E/Twitter Login Error(825): > null this is the error in logcat – Maruthi042 Feb 26 '13 at 04:45
0

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.

Ria
  • 873
  • 1
  • 10
  • 25
  • ,your above code is working. my log cat error is 02-26 04:44:23.044: E/Twitter Login Error(825): > null – Maruthi042 Feb 26 '13 at 04:44
  • can you see my code and tell,its shwoing log cat error inTwitter login error nulll – Maruthi042 Feb 26 '13 at 04:52
  • I used your code,its loading after that ,my application has stopped, throwing error in logcat in line 1 and return statement – Maruthi042 Feb 26 '13 at 05:26
  • 02-26 05:24:34.665: E/AndroidRuntime(1235): at com.example.twitterdemo.MainActivity$LoginTask.doInBackground(MainActivity.java:243) 02-26 05:24:34.665: E/AndroidRuntime(1235): at com.example.twitterdemo.MainActivity$LoginTask.doInBackground(MainActivity.java:1) two log cat error for your code,can you see once again – Maruthi042 Feb 26 '13 at 05:29
  • Have you used return type as RequestToken. I tested the above code and its working fine for me. Can you tell me, in which line you are getting error and from where you are calling the LoginTask class. – Ria Feb 26 '13 at 05:54
  • return requestToken = twitter .getOAuthRequestToken(TWITTER_CALLBACK_URL); and my first line showing package com.example.twitter demo,its showing error in log cat – Maruthi042 Feb 26 '13 at 05:58
  • verify whether your consumer key and consumer secret are valid one. From where you are calling the LoginTask class – Ria Feb 26 '13 at 06:03
  • `public void onClick(View arg0) { // Check if already logged in if (!isTwitterLoggedInAlready()) { new LoginTask().execute(); } else { // user already logged into twitter Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show(); } }` – Ria Feb 26 '13 at 06:06
  • I used your code only,and then my older code is also in answer section – Maruthi042 Feb 26 '13 at 06:09
  • Ria,i cant see correct below you typed your code,can you edit your code and do it correctly – Maruthi042 Feb 26 '13 at 06:13
  • i put my new code in question named as old to new code,thats my code,and then i used your code also – Maruthi042 Feb 26 '13 at 06:15
  • Ria one doubt,i gave my callback url as http:\\www.something.com, then i gave in my java file as static final String TWITTER_CALLBACK_URL = "oauth://t4jsample"; is this correct – Maruthi042 Feb 26 '13 at 06:24
  • I am using TWITTER_CALLBACK_URL = "oauth://t4jsample" in my app but I left my call back url as empty. I will post you once i find the solution. Till that pls work around on your code. Try to solve issue by yourself. – Ria Feb 26 '13 at 06:52
  • hmm ok ria,but you have to put call back url is must – Maruthi042 Feb 26 '13 at 07:01
  • ,its working somewhat,while clicking the sign in button,some lock symbol is coming at loading area,no issues are not in my code right now – Maruthi042 Feb 26 '13 at 07:04
  • have u find the solution?while clicking the signin button its not going to next step,what it might be the reason – Maruthi042 Feb 26 '13 at 08:06
  • ,can you get the solution – Maruthi042 Feb 26 '13 at 10:57