2014-04-24 40 views
0

我有一些asynstask是在我的主要活動中定義的。我試圖通過將這些類中的每一個放在單獨的文件中來使代碼更加模塊化。不幸的是,我不斷收到一些錯誤,例如無法獲得工作意圖。如何將此代碼與我的主要活動連接起來。順便說一句,如果我把這個代碼原樣(沒有導入)在mainActivity它工作得很好。謝謝如何將每個AsyncTask類放在一個單獨的文件中?

package com.example.food4thought; 

import java.net.URL; 

import twitter4j.TwitterException; 
import twitter4j.auth.RequestToken; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.Toast; 



// Starts an intent that loads up a web browser and asks the user to log in to twitter 
    // and get a pin# 
    public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> { 



     protected RequestToken doInBackground(URL... arg0) { 

      try { 
       requestToken = twitter.getOAuthRequestToken(); 
       Log.i("Got Request Token", "food4thought"); 
      } catch (TwitterException e) { 
       Log.i("Failed to get Request Token", "food4thought"); 
      } 

      //Log.i(requestToken.getAuthorizationURL(), "food4thought"); 
      //requestToken.getAuthorizationURL(); 
      //log_in.setText(); 

      try { 
      Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthorizationURL())); 
      startActivity(browserIntent); 
      } 

      catch(NullPointerException e) { 
       runOnUiThread(new Runnable() { 
        public void run() { 
         Toast.makeText(getApplicationContext(), "Unable to log in, No access to the Internet.", Toast.LENGTH_LONG).show(); 

        } 
       }); 

      } 

      return null; 
     } 

    } 
+0

你可以添加「一些錯誤」部分來解決你的問題嗎? –

+0

另外,請注意您的編譯錯誤。如果你明白髮生了什麼,你可以解決錯誤。 –

回答

1

爲此,您需要了解您的AsyncTask具有哪些依賴關係。

要啓動你需要的intents Context intance。我也看到一些twitter變量。

因此,您需要聲明適當的字段並將這些對象傳遞給您的TwitterLogin構造函數。

類似的東西:

public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> { 
    private Context context; 
    //other fields here 

    public TwitterLogin(Context context, ...){ // other variables here 
     this.context = context; 
     //other fields assignment 
    } 
} 

以後你可以解僱意圖:

context.startActivity(browserIntent); 

明白最重要的是,所有這些類似startActivity方法是不是有些「全局函數」,而他們是一些類實例的方法,你不能從AsycTask實例中調用這些方法。

相關問題