Android:Twitter授权和登录问题

时间:2014-08-13 12:46:21

标签: android twitter

我在Android应用程序中集成了twitter。在这里,我遇到了一些问题。

当我点击twitter登录按钮时,我的应用程序崩溃了,这是我得到的logcat错误。

08-13 17:42:06.893: E/AndroidRuntime(9229): FATAL EXCEPTION: AsyncTask #2
08-13 17:42:06.893: E/AndroidRuntime(9229): java.lang.RuntimeException: An error occured while executing doInBackground()
08-13 17:42:06.893: E/AndroidRuntime(9229):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at java.lang.Thread.run(Thread.java:841)
08-13 17:42:06.893: E/AndroidRuntime(9229): Caused by: java.lang.NoClassDefFoundError: twitter4j.conf.ConfigurationBuilder
08-13 17:42:06.893: E/AndroidRuntime(9229):     at com.example.studentjob.JobFinalPage$LoginToTwitterTask.doInBackground(JobFinalPage.java:173)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at com.example.studentjob.JobFinalPage$LoginToTwitterTask.doInBackground(JobFinalPage.java:1)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-13 17:42:06.893: E/AndroidRuntime(9229):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-13 17:42:06.893: E/AndroidRuntime(9229):     ... 4 more
08-13 17:42:19.225: D/AbsListView(9229): onVisibilityChanged() is called, visibility : 0
08-13 17:42:19.225: D/AbsListView(9229): unregisterIRListener() is called 
08-13 17:42:19.386: E/WindowManager(9229): Activity com.example.studentjob.JobFinalPage has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4297b660 V.E..... R......D 0,0-464,500} that was originally added here
08-13 17:42:19.386: E/WindowManager(9229): android.view.WindowLeaked: Activity com.example.studentjob.JobFinalPage has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4297b660 V.E..... R......D 0,0-464,500} that was originally added here
08-13 17:42:19.386: E/WindowManager(9229):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:450)
08-13 17:42:19.386: E/WindowManager(9229):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
08-13 17:42:19.386: E/WindowManager(9229):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
08-13 17:42:19.386: E/WindowManager(9229):  at android.app.Dialog.show(Dialog.java:287)
08-13 17:42:19.386: E/WindowManager(9229):  at com.example.studentjob.JobFinalPage$LoginToTwitterTask.onPreExecute(JobFinalPage.java:201)
08-13 17:42:19.386: E/WindowManager(9229):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
08-13 17:42:19.386: E/WindowManager(9229):  at android.os.AsyncTask.execute(AsyncTask.java:534)
08-13 17:42:19.386: E/WindowManager(9229):  at com.example.studentjob.JobFinalPage$1.onClick(JobFinalPage.java:105)
08-13 17:42:19.386: E/WindowManager(9229):  at android.view.View.performClick(View.java:4475)
08-13 17:42:19.386: E/WindowManager(9229):  at android.view.View$PerformClick.run(View.java:18786)
08-13 17:42:19.386: E/WindowManager(9229):  at android.os.Handler.handleCallback(Handler.java:730)
08-13 17:42:19.386: E/WindowManager(9229):  at android.os.Handler.dispatchMessage(Handler.java:92)
08-13 17:42:19.386: E/WindowManager(9229):  at android.os.Looper.loop(Looper.java:137)
08-13 17:42:19.386: E/WindowManager(9229):  at android.app.ActivityThread.main(ActivityThread.java:5419)
08-13 17:42:19.386: E/WindowManager(9229):  at java.lang.reflect.Method.invokeNative(Native Method)
08-13 17:42:19.386: E/WindowManager(9229):  at java.lang.reflect.Method.invoke(Method.java:525)
08-13 17:42:19.386: E/WindowManager(9229):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
08-13 17:42:19.386: E/WindowManager(9229):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
08-13 17:42:19.386: E/WindowManager(9229):  at dalvik.system.NativeStart.main(Native Method)
08-13 17:42:21.558: I/Process(9229): Sending signal. PID: 9229 SIG: 9
08-13 17:42:21.918: D/AbsListView(9795): Get MotionRecognitionManager
08-13 17:42:21.928: D/AbsListView(9795): Get MotionRecognitionManager
08-13 17:42:21.928: D/AbsListView(9795): Get MotionRecognitionManager
08-13 17:42:21.938: D/AbsListView(9795): Get MotionRecognitionManager
08-13 17:42:21.938: D/AbsListView(9795): Get MotionRecognitionManager
08-13 17:42:22.088: D/libEGL(9795): loaded /vendor/lib/egl/libEGL_adreno.so
08-13 17:42:22.088: D/libEGL(9795): loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
08-13 17:42:22.098: D/libEGL(9795): loaded /vendor/lib/egl/libGLESv2_adreno.so
08-13 17:42:22.098: I/Adreno-EGL(9795): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build:  (CL4169980)
08-13 17:42:22.098: I/Adreno-EGL(9795): OpenGL ES Shader Compiler Version: 17.01.10.SPL
08-13 17:42:22.098: I/Adreno-EGL(9795): Build Date: 09/26/13 Thu
08-13 17:42:22.098: I/Adreno-EGL(9795): Local Branch: 
08-13 17:42:22.098: I/Adreno-EGL(9795): Remote Branch: 
08-13 17:42:22.098: I/Adreno-EGL(9795): Local Patches: 
08-13 17:42:22.098: I/Adreno-EGL(9795): Reconstruct Branch: 
08-13 17:42:22.158: D/OpenGLRenderer(9795): Enabling debug mode 0

以下是代码:

SharedPreferences pref;
Editor editor;
private static SharedPreferences mSharedPreferences;
private static Twitter twitter;
private static RequestToken requestToken;
public final String consumer_key = "z2E7ISesmQsjDRah5qFA";
public final String secret_key = "IcJHyb74pYhOUupkbO7Vez5a0VxJ4aHiYOviQUDMk4";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authorize";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
String resgid,prelocation,prefdescription,prefjurl;
SharedPreferences preferences;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.jobdetails);
    Intent intent=getIntent();
    tittle=intent.getStringExtra("usertittle");
    userdescription=intent.getStringExtra("userdescription");
    joburl=intent.getStringExtra("joburl");
    location=intent.getStringExtra("location");
    if(tittle!=null)
    {
        preferences = getSharedPreferences("m_key",MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("tittle", tittle);
        editor.putString("description", userdescription);
        editor.putString("location", location);
        editor.putString("jurl", joburl);
        editor.commit();
    }
    SharedPreferences myPrefs = getSharedPreferences("m_key",
            MODE_WORLD_READABLE);
    resgid = myPrefs.getString("tittle",null);
    prelocation=myPrefs.getString("location",null);
    prefdescription=myPrefs.getString("description",null);
    prefjurl=myPrefs.getString("jurl",null);
    title=(TextView) findViewById(R.id.comapnyname);
    description=(TextView) findViewById(R.id.description);
    locationtext=(TextView) findViewById(R.id.locationname);
    company=(TextView) findViewById(R.id.tittlename);
    twit=(ImageButton) findViewById(R.id.twitter);
    jobshare=(ImageButton) findViewById(R.id.share);
    if(tittle!=null){
        company.setText(tittle);
        title.setText("N/A");
        description.setText(userdescription);
        locationtext.setText(location);
    }else{
        company.setText(resgid);
        title.setText("N/A");
        description.setText(prefdescription);
        locationtext.setText(prelocation);
    }

    mSharedPreferences = getSharedPreferences("twitter_oauth", MODE_PRIVATE);
    twit.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            //Intent intent=new Intent(getApplicationContext(),JobResult.class);
            //startActivity(intent);    
            if(isConnected())
            {
                twit.setImageResource(R.drawable.sharetwitterselected);

            }else{
                twit.setImageResource(R.drawable.sharetwitterselected);
                LoginToTwitterTask login = new LoginToTwitterTask();
                login.execute();
            }

        }
    });
    jobshare.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) 
        {
            Uri uri = getIntent().getData();            
            HandleOuthCallBack hc = new HandleOuthCallBack();
            hc.execute(uri);
            try
            {
                String Sharetext=resgid+"\nJob URL :"+prefjurl+"\nPosted By \n Student Job. ";
                new updateTwitterStatus().execute(Sharetext);
            }
            catch (Exception e) 
            {
                e.printStackTrace();

            }

        }
    });


}


private boolean isConnected()
{
    return mSharedPreferences.getString("oauth_token", null) != null;
}
private class HandleOuthCallBack extends AsyncTask<Object, Void, Void> {
    @Override
    protected Void doInBackground(Object... params) {
        try{
            Uri uri = (Uri) params[0];
            String verifier = uri.getQueryParameter("oauth_verifier");
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); 
            Editor e = mSharedPreferences.edit();
            e.putString("oauth_token", accessToken.getToken()); 
            e.putString("oauth_token_secret", accessToken.getTokenSecret()); 
            e.commit();
        }catch(Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

    }
    @Override
    protected void onPreExecute() {

    }
}
ProgressDialog dialog;
private class LoginToTwitterTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try{
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.setOAuthConsumerKey("z2E7ISesmQsjDRah5qFA");
            configurationBuilder.setOAuthConsumerSecret("IcJHyb74pYhOUupkbO7Vez5a0VxJ4aHiYOviQUDMk4");
            Configuration configuration = configurationBuilder.build();
            twitter = new TwitterFactory(configuration).getInstance();
            requestToken = twitter.getOAuthRequestToken("oauth://StudentJob");
            dialog.dismiss();
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(intent);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) 
    {
        super.onPostExecute(result);

    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(JobFinalPage.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMax(100);
        dialog.setTitle("Loading ..");
        dialog.show();  

    }
}

class updateTwitterStatus extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();

    }
    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {
        String status = args[0];
        try 
        {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey("z2E7ISesmQsjDRah5qFA");
            builder.setOAuthConsumerSecret("IcJHyb74pYhOUupkbO7Vez5a0VxJ4aHiYOviQUDMk4");
            // Access Token 
            try{
                String access_token = mSharedPreferences.getString("oauth_token", "");
                // Access Token Secret
                String access_token_secret = mSharedPreferences.getString("oauth_token_secret", "");
                AccessToken accessToken = new AccessToken(access_token, access_token_secret);
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
            }
            catch(Exception e)
            {
                e.printStackTrace();    
            }

            // Update status
            twitter4j.Status response = twitter.updateStatus(status);
        } catch (TwitterException e) {
            // Error in updating status
            e.printStackTrace();
        }
        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

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() 
            {
                Toast.makeText(getApplicationContext(),
                        "Status tweeted successfully", Toast.LENGTH_SHORT).show();
            }
        });
    } 

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

在上一次完成之前,你无法启动另一个AsyncTask。所以检查HandleOuthCallBack是否完成,然后启动你的登录任务。