AsyncTask,doInBackground()不运行

时间:2012-12-01 14:03:22

标签: android android-asynctask

我正在阅读AsyncTask,我尝试了一个程序。但它似乎没有用。我是编程新手,如果可能,请你帮我解决。

public class MainActivity extends Activity {

TextView title;
TextView date;
TextView cat;
TextView desc;
Button rss;

difficultTask doBack;

private static final String TAG_ITEM = "item";
private static final String TAG_TITLE = "title";
private static final String TAG_LINK = "link";
private static final String TAG_DESC = "description";
private static final String TAG_DATE = "pubDate";
private static final String TAG_CAT = "category";


JSONArray rssFeed = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);           
    title = (TextView)findViewById(R.id.title);                  
    date = (TextView)findViewById(R.id.date);        
    cat = (TextView)findViewById(R.id.cat);        
    desc = (TextView)findViewById(R.id.description);        
    rss = (Button)findViewById(R.id.rss);
    rss.setOnClickListener(new Button.OnClickListener() {            
        @Override
        public void onClick(View v) {
            doBack = new difficultTask();
            doBack.execute();                
            }
        });        
}

class difficultTask extends AsyncTask<Void, Void, Void>{
    @Override
    protected Void doInBackground(Void... params) {        

        JSONObject json = getJSONFromUrl("http://example.com/mysite/rss.js");

        String categ = "";String t = "";String d = "";String da = "";String a = ""; 

        try {    
            JSONArray jsonArray = json.getJSONArray(TAG_ITEM);
            for(int i = 0; i<jsonArray.length(); i++){
                JSONObject c = rssFeed.getJSONObject(i);
                 t = c.getString(TAG_TITLE);
                 a = c.getString(TAG_LINK);
                 d = c.getString(TAG_DESC);
                 da = c.getString(TAG_DATE);
                 categ = c.getString(TAG_CAT);

            }

            Log.d("Log", t+"/n"+a+"/n"+d+"/n"+da+"/n"+categ);
        } catch (JSONException e) {
            Log.d("Log", e.getMessage());
            e.printStackTrace();
        }            
        Log.d("Log", "Background");
        return t;
    }

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

    public JSONObject getJSONFromUrl(String url){
        InputStream ips = null;
        JSONObject jsonObj = null;
        String json = "";

        try{
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);               
            HttpResponse respone = httpClient.execute(httppost);
            HttpEntity entity = respone.getEntity();

            ips = entity.getContent();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            BufferedReader bufff = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = bufff.readLine()) != null){
                sb.append(line + "\n");
            }
            ips.close();
            json = sb.toString();
        }
        catch(Exception e){
            Log.d("Log", e.toString());
        }
            try {
                jsonObj = new JSONObject(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        return jsonObj;        
    }


}

}

doInBackground()无效,请提供帮助。 我怎样才能从背景中返回一些String s,a,c,d,da?

UPD:抱歉Logcat没有用,现在我看到了错误

12-01 19:17:30.109: E/AndroidRuntime(2500): FATAL EXCEPTION: AsyncTask #1
12-01 19:17:30.109: E/AndroidRuntime(2500): java.lang.RuntimeException: An error occured while executing doInBackground()
12-01 19:17:30.109: E/AndroidRuntime(2500):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at java.lang.Thread.run(Thread.java:856)
12-01 19:17:30.109: E/AndroidRuntime(2500): Caused by: java.lang.NullPointerException
12-01 19:17:30.109: E/AndroidRuntime(2500):     at com.example.mytwitter.MainActivity$difficultTask.doInBackground(MainActivity.java:99)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at com.example.mytwitter.MainActivity$difficultTask.doInBackground(MainActivity.java:1)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-01 19:17:30.109: E/AndroidRuntime(2500):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-01 19:17:30.109: E/AndroidRuntime(2500):     ... 4 more

2 个答案:

答案 0 :(得分:0)

好的,我已经为你添加了一些简单的Asynctask ..并告诉我这是否适合你。

public class SenderActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SenderActivity.Sender.execute();
    }

    class Sender extends AsyncTask<Void, Integer, Integer> {
        ProgressDialog pd = null;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = new ProgressDialog(SenderActivity.this);
            pd.setTitle("Sending...");
            pd.setMessage("Please wait..");
            pd.setCancelable(false);
            pd.show();
        }
        @Override
        protected Integer doInBackground(Void... params) {
            System.out.println("Try some simple operation to learn well");
            //check whether this printing in your logcat
            return 3;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            pd.dismiss();
        }
    }
}

答案 1 :(得分:0)

JSONObject json = getJSONFromUrl("http://example.com/mysite/rss.js");

你的AsyncTask是完美的,你应该在这个语句之前做一个日志来检查getJSONFromUrl()返回什么,我认为这个方法返回 null 这就是为什么你面临错误。