我想显示关于给定的 JSON
url,但我无法正确声明 JSONObject
以及 JSONArray
在 MainActivity
,所以请任何人帮我在上面显示数据 TextView
. 显示错误:
java.lang.runtimeexception:无法启动activity componentinfo{com.example.和\u ws\u builder/com.example.和\u ws\u builder.mainactivity}:android.os.networkonmainthreadexception
mainactivity.java类
public class MainActivity extends Activity {
private static String url ="http://myfourwalls.in/services_microsite/project_builder.php";
private static final String TAG_Name = "about_builder";
JSONArray builder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
JSONObject c = builder.getJSONObject(0);
for (int i = 0; i < json.length(); i++) {
String name = c.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonparser.java文件
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFormUrl(String url) {
try {
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 {
jobj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parse","error Parsing data" + e.toString());
}
return jobj;
}
}
主活动.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txtname"
android:layout_width="fill_parent"
android:layout_height="100dp"/>
</RelativeLayout>
2条答案
按热度按时间r9f1avp51#
您正在主线程中使用与网络相关的代码。使用异步任务。
mrphzbgm2#
您在主线程内调用网络调用意味着android不支持前台。因此请使用assynctask类,它将在后台处理网络调用。
1) 创建方法调用时的内部调用,如:
2) 在oncreate外部声明以下内容