[英]getting a null pointer exception when trying to parse JSON data from a url in a Async Class android
[英]Getting null pointer exception on getting Async Task JSON using Android
當我嘗試使用AsyncTask請求JSON時,我收到NullPointerException。 我正在使用loopj和AsyncTask
這是我的代碼:
String str = null;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
try{
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", "Token token=Wa5sfwP3ku7c15qkZTsd**");
client.get("http://*********.com/api/v1/***", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
str = response;
Log.v("==========RESULT==========", response);
}
});
} catch(Exception e){
Log.v("========== ERROR ==========", e.toString());
}
return str;
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText("Result: " + result);
}
}
}
你做錯了。 在doInBackground()
方法中,您應該使用同步方法,並且您正在使用異步:
client.get("http://*********.com/api/v1/***", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
str = response;
Log.v("==========RESULT==========", response);
}
這就是你的doInBackground()
返回null的原因,你試圖在onPostExecute()
處理null
你應該使用類的方法SyncHttpClient
從循環J-異步庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.