【发布时间】:2014-01-17 03:27:37
【问题描述】:
这是我的代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.os.AsyncTask;
import android.util.Log;
public class JsonController
{
private JSONObject inputData, json, finalResult;
private String authentication;
public JsonController()
{
json = new JSONObject();
inputData = new JSONObject();
}
public void createAuthentication(String userName, String apiKey)
{
authentication = "";
}
public void setModel(String model) throws JSONException
{
json.put("model",model);
}
public void setData(String id, String deviceType) throws JSONException
{
inputData.put(id, deviceType);
}
public void getPrediction()
{
new sendJSon().execute("");
return finalResult.toString();
}
private class sendJSon extends AsyncTask<String,Void,String>
{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(authentication);
httppost.setHeader("Content-type", "application/json; charset=utf-8");
try {
// Add your data
json.put("input_data", inputData);
StringEntity se = new StringEntity( json.toString());
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String jsonString = reader.readLine();
JSONTokener tokener = new JSONTokener(jsonString);
finalResult = new JSONObject(tokener);
}
catch(Exception e)
{
Log.d("Error here", "Error is here",e);
}
return null;
}
}
}
由于NulPointerException,此代码总是在getPrediction() 中崩溃。 NullPointerException 是因为 Async 任务需要时间来生成 String,而 getPrediction() 方法在它准备好之前返回了字符串。所有这些方法都是通过外部类调用的,那么我该如何解决呢?
【问题讨论】:
-
onPostExecute(),谷歌!在这里你会找到一个参考:developer.android.com/reference/android/os/AsyncTask.html
-
哪一行得到NPE?发布
logcat,您将从void类型函数返回字符串.. -
发布您的
onPostExecute()方法。 @FlowOverStack。 -
getPrediction 无效。它不能返回字符串
标签: java android android-asynctask android-internet