NullPointerException异常通过解析JSON [英] NullPointerException by parsing JSON
问题描述
我尝试做这个教程<一个href="http://www.mybringback.com/tutorial-series/13193/android-mysql-php-json-part-5-developing-the-android-application/"相对=nofollow> Tuturial第5 ,然后我得到了Regisert.java NullPointerException异常在与code线:
I try to do this tutorial Tuturial Part 5 and I got a NullPointerException in Regisert.java at the line with the code:
Log.d("Login attempt", json.toString());
我使用WAMP的服务器和我已经保存在目录WWW我的PHP文件。这意味着我的字符串变量的网址北京时间
I am using WAMP server and I already save my php file under the directory www. that means my string variable URL ist
"http://10.0.2.2:80/www/login_tutorial/register.php"
。北京时间HIER我的log.txt
. Hier ist my log.txt
07-13 19:56:20.266: E/AndroidRuntime(29385): FATAL EXCEPTION: AsyncTask #1
07-13 19:56:20.266: E/AndroidRuntime(29385): java.lang.RuntimeException: An error occured while executing doInBackground()
07-13 19:56:20.266: E/AndroidRuntime(29385): at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-13 19:56:20.266: E/AndroidRuntime(29385): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.lang.Thread.run(Thread.java:856)
07-13 19:56:20.266: E/AndroidRuntime(29385): Caused by: java.lang.NullPointerException
07-13 19:56:20.266: E/AndroidRuntime(29385): at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:105)
07-13 19:56:20.266: E/AndroidRuntime(29385): at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:1)
07-13 19:56:20.266: E/AndroidRuntime(29385): at android.os.AsyncTask$2.call(AsyncTask.java:264)
07-13 19:56:20.266: E/AndroidRuntime(29385): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-13 19:56:20.266: E/AndroidRuntime(29385): ... 5 more
有人可以告诉我,为什么它不适合我?!
can somebody tell me why it doesn't work for me?!
感谢
我把code从上面的链接,但我会在这里再次张贴它的确定。
I took the code from the link above but it's ok I'll post it here again.
public class Register extends Activity implements OnClickListener {
private EditText user, pass;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://10.0.2.2:80/www/login_tutorial/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
mRegister = (Button) findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
new CreateUser().execute();
}
@Override
protected void onPause() {
super.onPause();
if (pDialog != null) {
pDialog.dismiss();
}
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating user...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User created", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}
else {
Log.d("Login Failure", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
*/
@Override
protected void onPostExecute(String result) {
if (pDialog != null) {
pDialog.dismiss();
}
if (result != null) {
Toast.makeText(Register.this, result, Toast.LENGTH_LONG).show();
}
}
}
}
在梅索德为考取JSON是在这里:
the methode for pasing JSON is here:
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP Request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHTTPClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer error", "Error converting result" + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
为什么它给了我null作为结果JSON?
why it gives me null as result for JSON?
推荐答案
我觉得你jsonParser没有抛出异常,而它返回null作为您的要求。修改您的jsonParser总是在错误的情况下抛出一个异常,在这里补充的空值处理你的JSON对象
I think your jsonParser is not throwing an exception rather it is returning null for your request. Modify your jsonParser to always throw an exception in case of errors or add null handling for your json object here
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
if(json == null)
return null;
这篇关于NullPointerException异常通过解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!