每次我尝试打开应用程序时,都会说
"Unfortunately, (appName) has stopped."
我正在尝试解析一些json数据,并将其显示在“ram”textView中,但它无效。我做错了什么?
public class Index extends Activity {
TextView ram = (TextView) findViewById(R.id.RAM_Text);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://admin.isdata.dk/jscalls/dashboard.php?auth=215e82a271f225df31ce2c358ec26a49");
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
JSONObject jObject = null;
try {
jObject = new JSONObject(result);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
double aJsonDouble = jObject.getDouble("ram");
String valueOfRam = String.valueOf(aJsonDouble);
ram.setText(valueOfRam);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
提前致谢!
答案 0 :(得分:1)
更改为
TextView ram;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ram = (TextView) findViewById(R.id.RAM_Text);
另外
HttpResponse response = httpclient.execute(httppost);
应该在Thread
或Asynctask
。
http://developer.android.com/reference/android/os/AsyncTask.html
所有与网络相关的操作都应在thread
或Asynctask