我目前正在尝试访问我的
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; } }
提前致谢
解决方法
我建议阅读这个网址
https://stackoverflow.com/a/6343299/2530660
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(); } }