0

我是 android 的新手,我正在尝试用 Json 做一些异步任务,我想从 tke Json 文件中获取数据。我的代码是:

package com.example.httpsample;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.httpsample.HttpExample.Read;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView httpsetup;
    HttpClient client;
    JSONObject json;

    //url tanımlama:
    final static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.httpex);
        httpsetup = (TextView) findViewById(R.id.tvHttp);
        //client açıyoruz.
        client = new DefaultHttpClient();
        //hangi datayı almak istiyorsak onun keyini alıyoruz
        new Read().execute("text");
    }

    public JSONObject lastTweet(String username) throws ClientProtocolException, IOException, JSONException{

        //call url
        StringBuilder url = new StringBuilder(URL);

        url.append(username);

        //url ye request gönderme
        HttpGet get = new HttpGet(url.toString());
        //response from url
        HttpResponse r = client.execute(get);

        int status = r.getStatusLine().getStatusCode();
        if (status == 200){

            HttpEntity e = r.getEntity();
            String data = EntityUtils.toString(e);
            JSONArray timeline = new JSONArray(data);
            JSONObject last = timeline.getJSONObject(0);
            return last;
        }else{
            Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    public class Read extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... params) {

            // TODO Auto-generated method stub
        try {
            json = lastTweet("mybringback");
            return json.getString(params[0]);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {

            // TODO Auto-generated method stub
            httpsetup.setText(result);
        }
    }

}

但是当我运行该项目时,我遇到了 Force close 问题,我的 eclipse 说:

- 09-26 07:17:17.964: E/AndroidRuntime(275): FATAL EXCEPTION: AsyncTask
   #1 09-26 07:17:17.964: E/AndroidRuntime(275): java.lang.RuntimeException: An error occured while executing
   doInBackground() 09-26 07:17:17.964: E/AndroidRuntime(275):  at
   android.os.AsyncTask$3.done(AsyncTask.java:200) 09-26 07:17:17.964:
   E/AndroidRuntime(275):   at
   java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   java.util.concurrent.FutureTask.setException(FutureTask.java:124)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   java.util.concurrent.FutureTask.run(FutureTask.java:137) 09-26
   07:17:17.964: E/AndroidRuntime(275):     at
   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   java.lang.Thread.run(Thread.java:1096) 09-26 07:17:17.964:
   E/AndroidRuntime(275): Caused by: java.lang.RuntimeException: Can't
   create handler inside thread that has not called Looper.prepare()
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   android.os.Handler.<init>(Handler.java:121) 09-26 07:17:17.964:
   E/AndroidRuntime(275):   at android.widget.Toast.<init>(Toast.java:68)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   android.widget.Toast.makeText(Toast.java:231) 09-26 07:17:17.964:
   E/AndroidRuntime(275):   at
   com.example.httpsample.MainActivity.lastTweet(MainActivity.java:67)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   com.example.httpsample.MainActivity$Read.doInBackground(MainActivity.java:79)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   com.example.httpsample.MainActivity$Read.doInBackground(MainActivity.java:1)
   09-26 07:17:17.964: E/AndroidRuntime(275):   at
   android.os.AsyncTask$2.call(AsyncTask.java:185) 09-26 07:17:17.964:
   E/AndroidRuntime(275):   at
   java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
   09-26 07:17:17.964: E/AndroidRuntime(275):   ... 4 more 09-26
   07:17:18.184: D/dalvikvm(275): GC_FOR_MALLOC freed 2898 objects /
   203488 bytes in 211ms 09-26 07:22:18.404: I/Process(275): Sending
   signal. PID: 275 SIG: 9

错误。

任何人都可以帮助我吗?

4

2 回答 2

5

删除线

 Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();

不允许从 trhead 访问 gui 元素。onPreExecute您可以通过覆盖or来在 asynctask 类中显示 Toast onPostExecute,但不能在您的 Web 服务doInBackground

也有问题,因为状态代码不是 200 :-)

于 2012-09-26T07:30:08.787 回答
1

错误是这一行:

Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();

您应该将其从方法中删除,lastTweet因为您无法从doInBackground..调用 UI 方法,onPostExecute而是将其添加到 ..

protected void onPostExecute(String result) {

        if(result == null)
            Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
        else
            httpsetup.setText(result);
    }
于 2012-09-26T07:30:24.943 回答