我是Android的新手 我试图通过json显示我从服务器获取的数据。我使用lazylist与JSONparser.my应用程序在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放在哪里 任何人都可以帮助我吗?
答案 0 :(得分:0)
1.首先定义类并创建类
的对象 MyFirstMethod myfirst;
myfirst = new MyFirstMethod();
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();
}
}
答案 1 :(得分:0)
阅读asyncTask的这些教程: -
these linkl! &安培; this is a stackoverflowlink 试试这些asynctask的教程
答案 2 :(得分: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);