请帮忙 即时通讯新手为Android 并尝试使用此代码使用微调器进行json解析,但我有一条错误消息“java.lang.NullPointerException”,请帮助修复我的代码..
@SuppressWarnings("deprecation")
public class evaluasi extends Activity{
InputStream is = null;
String result = null;
String line = null;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> worldlist;
@Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_evaluasi);
/*parsing ke broker*/
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "Sucsess..");
}catch (Exception e){
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_SHORT).show();
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) !=null )
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("Pass 2", "Connection Sucess");
}catch (Exception e){
Log.e("Fail 2", "Failed Connection");
}
try{
worldlist =new ArrayList<String>();
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
worldlist.add(jsonobject.optString("country"));
}
Spinner spinbro = (Spinner) findViewById(R.id.spinbrokced);
spinbro.setAdapter(new ArrayAdapter<String>(evaluasi.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
}catch (Exception e){
Log.e("Fail 3", e.toString());
Toast.makeText(getApplicationContext(), "cant load data", Toast.LENGTH_SHORT).show();
}
}
//end parsin broker
答案 0 :(得分:0)
-Hello您已完成jsonobject
的声明,但您尚未初始化,因此您的代码应为......
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) !=null )
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
// your object should be initialized like this
jsonobject= new JSONObject(result);
Log.e("Pass 2", "Connection Sucess");
}catch (Exception e){
Log.e("Fail 2", "Failed Connection");
}