我目前正在尝试访问Android应用程序上的JSON对象。但是,我一直收到以下错误:
android.os.NetworkOnMainThreadException
从稍微研究一下,我目前唯一的信息是我需要异步执行此操作(?)
这是我的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView dynamictext;
dynamictext = (TextView) findViewById(R.id.dynamictext);
dynamictext.setText(getJSON("my url here"));
}
public String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (Exception ex) {
return ex.toString();
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
//disconnect error
}
}
}
return null;
}
}
提前致谢
答案 0 :(得分:7)
我建议阅读这个网址 https://stackoverflow.com/a/6343299/2530660
添加AsyncTask;
public class TestAsyncTask extends AsyncTask<Void, Void, String> {
private Context mContext;
private String mUrl;
public TestAsyncTask(Context context, String url) {
mContext = context;
mUrl = url;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dynamictext = (TextView) findViewById(R.id.dynamictext);
}
@Override
protected String doInBackground(Void... params) {
String resultString = null;
resultString = getJSON(mUrl);
return resultString;
}
@Override
protected void onPostExecute(String strings) {
super.onPostExecute(strings);
dynamictext.setText(strings);
}
private String getJSON(String url) { ... }
}
使用AsyncTask;
public class MainActivity ... {
private TextView dynamictest;
onCreate() {
...
TestAsyncTask testAsyncTask = new TestAsyncTask(MainActivity.this, "my url here");
testAsyncTask.execute();
}
}
答案 1 :(得分:0)
从Android 3及更高版本开始,不允许在UI线程上运行网络操作,因此您的应用程序将因NetworkOnMainThreadException
而崩溃。
在这里,您可以找到一个Asyntask
的简单示例,您将异步处理代码:Android: AsyncTask to make an HTTP GET Request?
答案 2 :(得分:0)
要执行耗时的任务,您需要实现将在非UI线程上运行的异步任务,因为您无法在UI线程上执行此类操作。
您可以在活动的onStart()方法中执行异步任务,并覆盖异步任务的onPostMethod(),以便在网络操作后实现您希望在UI上执行的任何更改 检查http://developer.android.com/reference/android/os/AsyncTask.html以获取有关异步任务的详细信息。
答案 3 :(得分:0)
private void taskPostExecute(String url)
{
myTask2=(RequestTask)new RequestTask().execute(url);
}
class RequestTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... uri) {
try {
postData(uri[0]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onCancelled() {
myTask2.cancel(true);
}
@Override
protected void onPostExecute(String url) {
LinearLayouts();
}
}
public static String postData(String url) throws UnsupportedEncodingException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
String responseString = "";
try {
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
InputStream inputStream = null;
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
inputStream = response.getEntity().getContent();
if(inputStream != null)
responseString = convertInputStreamToString(inputStream);
else
responseString = "Did not work!";
JSONObject reader = null;
JSONArray sys = null;
try {
reader = new JSONObject(responseString);
String res_metar = reader.getString("TAG");
} catch (JSONException e) {
e.printStackTrace();
}
//a = responseString;
} else{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
// process execption
}
return responseString;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
你可以尝试一下,它有效。