我正在關注thenewboston Android tutorials on Youtube,並且在解析JSON數據方面遇到了一些問題。NullPointerException在Android中執行HTTP GET請求..任何想法?
從我所知道的,問題似乎是在TwitterTask子類行:
r = client.execute(get);
我相當肯定我用的URL是正確的,因爲鏈接我的一部分發送GET請求工作在我的瀏覽器:
http://api.twitter.com/1/statuses/user_timeline.json?screen_name=ssjunejo
我會非常感謝任何幫助。提前謝謝了。這裏是我的代碼:
public class JSONMainActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsonmain);
httpStuff = (TextView) findViewById(R.id.tvJson);
new TwitterReadTask().execute("text");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_jsonmain, menu);
return true;
}
public class TwitterReadTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
try {
json = lastTweet("ssjunejo");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public JSONObject lastTweet(String username)
throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
System.out.println("YOLO " + url.toString());
HttpGet get = new HttpGet(url.toString());
System.out.println("GET CREATED");
HttpResponse r = null;
try {
r = client.execute(get);
} catch (Exception e) {
System.out.println("OOPS. ERROR");
e.printStackTrace();
}
System.out.println("Executed get request");
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
} else {
Toast.makeText(JSONMainActivity.this, "error",
Toast.LENGTH_SHORT);
return null;
}
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
System.out.println(result);
httpStuff.setText(result);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
System.out.println("TESTING");
}
}
}
怎麼樣堆棧跟蹤:
setContentView
後或調用client.execute
方法之前初始化它作爲活動的onCreate方法?錯誤日誌? – 2013-04-04 11:09:19請顯示堆棧跟蹤。否則很難說 – PSR 2013-04-04 11:09:33
npe =>堆棧跟蹤。沒有stacktrace => -1 – njzk2 2013-04-04 11:25:46