2

我是android的新手,我正在尝试显示我通过json从服务器获取的数据。我使用lazylist和JSONparser。我的应用程序在android 2.3上工作,但在4.0上工作......所以我试图在我的代码中添加AsyncTask。我的代码是:

package dlmbg.pckg.tampil.gambar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject AmbilJson(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

当我在 4.0 中运行时,它的错误

11-01 12:16:19.063: E/AndroidRuntime(623): FATAL EXCEPTION: main
11-01 12:16:19.063: E/AndroidRuntime(623): java.lang.RuntimeException: Unable to start activity ComponentInfo{dlmbg.pckg.tampil.gambar/dlmbg.pckg.tampil.gambar.TampilkanGambarActivity}: android.os.NetworkOnMainThreadException
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.os.Looper.loop(Looper.java:137)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.main(ActivityThread.java:4424)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.lang.reflect.Method.invokeNative(Native Method)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.lang.reflect.Method.invoke(Method.java:511)
11-01 12:16:19.063: E/AndroidRuntime(623):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-01 12:16:19.063: E/AndroidRuntime(623):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-01 12:16:19.063: E/AndroidRuntime(623):  at dalvik.system.NativeStart.main(Native Method)
11-01 12:16:19.063: E/AndroidRuntime(623): Caused by: android.os.NetworkOnMainThreadException
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-01 12:16:19.063: E/AndroidRuntime(623):  at dlmbg.pckg.tampil.gambar.JSONParser.AmbilJson(JSONParser.java:38)
11-01 12:16:19.063: E/AndroidRuntime(623):  at dlmbg.pckg.tampil.gambar.TampilkanGambarActivity.onCreate(TampilkanGambarActivity.java:38)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.Activity.performCreate(Activity.java:4465)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-01 12:16:19.063: E/AndroidRuntime(623):  ... 11 more

我不知道我必须把 AsyncTask 放在哪里有人可以帮助我吗?

4

3 回答 3

0

1.首先你定义类并创建类的对象

 MyFirstMethod myfirst;
  1. 现在你执行这个类添加

我的第一个=新的我的第一个方法();

myfirst.execute(你的网址);

public class MyFirstMethod extends AsyncTask<String, Void, String> {
            ProgressDialog dialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = new ProgressDialog(context);
                dialog.setMessage("Loading....");
                dialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                String url = params[0];
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    ResponseHandler<String> resHandler = new  BasicResponseHandler();
                    String page = httpClient.execute(httpGet, resHandler);
                    Log.d("result", page);

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String result) {

                super.onPostExecute(result);
                dialog.dismiss();
                dialog.cancel();


            }

        }
于 2012-11-01T06:50:25.543 回答
0

阅读这些关于 asyncTask 的教程:-

这些链接!&这是一个 stackoverflowlink 试试这些 asynktask 教程

于 2012-11-01T06:50:25.870 回答
0

您应该在代码中尝试类似下面的AsyncTask ...

private class BackgroundTask extends AsyncTask<String, Void, String> {
@Override
  protected String doInBackground(String... urls) {
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        String result = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

   return result;
 }

 @Override
 protected void onPostExecute(String result) {
  // try parse the string to a JSON object
    try {
        jObj = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

}

并在您需要的地方通过下面的行调用它...

 new BackgroundTask().execute(url);
于 2012-11-01T06:56:15.947 回答