【发布时间】:2013-12-06 19:38:57
【问题描述】:
我正在尝试运行基于 WorlBank API 的应用程序。我有一个 JSON URL 来获取有关国家/地区的数据,然后在 TextViews 中显示它。简单的。但是一旦我运行应用程序就关闭了。
这是我的文件:
主要活动:
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
//JSON node Names
private static final String PAGE = "page";
private static final String VALUE = "value";
private static final String NAME = "name";
private static final String GEO = "region";
JSONArray page = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
//Getting JSON Array
page = json.getJSONArray(PAGE);
JSONObject c = page.getJSONObject(0);
//Sorting JSON item in a Variable
String value = c.getString(VALUE);
String name = c.getString(NAME);
String geo = c.getString(GEO);
//Importing to TextView
final TextView id1 = (TextView) findViewById(R.id.id);
final TextView name1 = (TextView) findViewById(R.id.name);
final TextView geo1 = (TextView) findViewById(R.id.geo);
//set JSON Data in TextView
id1.setText(value);
name1.setText(name);
geo1.setText(geo);
} catch (JSONException e){
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSON解析器:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(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;
}
}
XML:
<TextView
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/id"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/geo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/id"
android:layout_alignParentTop="true"
android:layout_marginTop="76dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
有什么想法吗?
世界银行api:http://data.worldbank.org/node/18
更新:
android:minSdkVersion="8"
android:targetSdkVersion="18"
FATAL EXCEPTION: main
E/AndroidRuntime(966): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonsyctask/com.example.jsonsyctask.Main}: android.os.NetworkOnMainThreadException
E/AndroidRuntime(966): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(966): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(966): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(966): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime(966): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(966): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(966): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(966): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(966): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(966): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
【问题讨论】:
-
尝试在异步任务中运行...
-
@HarshitRathi 我不知道这个。你能解释一下吗?
-
使用此链接androidhive.info/2012/01/android-json-parsing-tutorial 它将帮助您了解如何在异步任务中解析 json...
-
首先,不要只做类似 “但只要我在关闭应用程序时运行。” 而不提供来自 logcat 的堆栈跟踪 - 向我们展示错误和代码。其次,您的问题的答案是,正如其他人所说,您正在 UI 线程上进行网络操作(在旧版本的 Android 上可以,但在更高版本的 Android 上不行)或者(无论如何这会咬你)URL 返回一个JSON 数组而不是 JSON 对象。此外,您正在执行 HTTP Post,而应该使用 HTTP GET。解决所有这些问题,您就可以开始了。
-
我同意@Squonk。您应该发布您的
log。上面提到的代码有很多问题..
标签: java android json textview