我试图通过我在eclipse上的Android应用程序连接到localhost上的数据库。 (我对这一切都很陌生)。我的代码中没有错误,但是当我运行应用并输入我的详细信息并点击“保存”Button
时,应用停止响应并提供以下错误
Error Parsing Data Org.Json.JSONException: End Of Input At Charac
我不确定错误问题是我的Json数组还是我的实际php文件。我在网上看过很多类似的问题,但仍然没有找到解决办法,有人可以建议我试试吗?
我的课程是:
package com.example.independentretailers;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.independentretailers.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class retailersignup extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText etRetailName, etTypeofBusiness, etLocation, etGPS, etPhoneNumber, etEmail, etPassword;
Button bSave;
private static String url_create_reatiler = "http://10.0.2.2/tutorial2.php";
private static final String TAG_SUCCESS = "success";
// @SuppressLint("NewApi")
@Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setup strict mode policy
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
setContentView(R.layout.retailersignup);
//for Retail name
etRetailName = (EditText) findViewById(R.id.editText1);
//for type of business
etTypeofBusiness = (EditText) findViewById(R.id.editText2);
//for Location
etLocation = (EditText) findViewById(R.id.editText3);
//for GPS
etGPS = (EditText) findViewById(R.id.editText4);
//for Phone Number
etPhoneNumber = (EditText) findViewById(R.id.editText5);
//for email
etEmail = (EditText) findViewById(R.id.editText6);
//for password
etPassword = (EditText) findViewById(R.id.editText7);
//setting up ID for the button
bSave = (Button) findViewById(R.id.button1);
//setting up onclick listener
bSave.setOnClickListener(new View.OnClickListener(){
InputStream is = null;
@Override
public void onClick(View arg0){
new CreateNewRetailer().execute();
}
});
}
class CreateNewRetailer extends AsyncTask<String, String, String>{
protected String doInBackground(String...args){
//storing values inside edit texts inside strings
String RetailName = etRetailName.getText().toString();
String TypeofBusiness = etTypeofBusiness.getText().toString();
String Location = etLocation.getText().toString();
String GPS = etGPS.getText().toString();
String PhoneNumber = etPhoneNumber.getText().toString();
String Email = etEmail.getText().toString();
String Password = etPassword.getText().toString();
//setting name pair values
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//adding string values inside the name value pairs
nameValuePairs.add(new BasicNameValuePair("Retail Name", RetailName));
nameValuePairs.add(new BasicNameValuePair("Type of Business", TypeofBusiness));
nameValuePairs.add(new BasicNameValuePair("Location", Location));
nameValuePairs.add(new BasicNameValuePair("GPS", GPS));
nameValuePairs.add(new BasicNameValuePair("Phone Number", PhoneNumber));
nameValuePairs.add(new BasicNameValuePair("Email", Email));
nameValuePairs.add(new BasicNameValuePair("Password", Password));
JSONObject json = jsonParser.makeHttpRequest (url_create_reatiler, "POST", nameValuePairs);
//setting up the connection inside the try catch
try{
//setting up the default client
int success = json.getInt(TAG_SUCCESS);
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExcute(String file_url){
pDialog.dismiss();
}
}
}
我的JsonParser类是: package com.example.independentretailers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
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"){
// request method is 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 JSON String
return jObj;
}
}
<?php
$response = array();
$con=mysql_connect("localhost", "root");
mysql_select_db("independentretailers",$con);
if (isset($_POST['Retail Name']) && isset($_POST['Type of Business']) && isset($_POST['Location'])&& isset($_POST['GPS'])&& isset($_POST['Phone Number'])&& isset($_POST['Email'])&& isset($_POST['Password'])) {
$RetailName = $_POST['Retail Name'];
$TypeofBusiness = $_POST['Type of Business'];
$Location = $_POST['Location'];
$GPS = $_POST['GPS'];
$PhoneNumber = $_POST['Phone Number'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$result = mysql_query("INSERT INTO retailer(Retail Name, Type of Business, Location, GPS, Phone Number, Email, Password) VALUES('$RetailName','$TypeofBusiness','$Location','$GPS','$PhoneNumber','$Email ','$Password')");
//检查是否插入了行 if($ result){ //成功插入数据库 $ response [“success”] = 1; $ response [“message”] =“零售商已成功创建。”;
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
我的完整logcat错误是:
04-17 15:45:54.393: D/dalvikvm(555): Not late-enabling CheckJNI (already on)
04-17 15:45:55.263: I/dalvikvm(555): threadid=3: reacting to signal 3
04-17 15:45:55.393: I/dalvikvm(555): Wrote stack traces to '/data/anr/traces.txt'
04-17 15:45:55.775: I/dalvikvm(555): threadid=3: reacting to signal 3
04-17 15:45:55.854: I/dalvikvm(555): Wrote stack traces to '/data/anr/traces.txt'
04-17 15:45:56.264: I/dalvikvm(555): threadid=3: reacting to signal 3
04-17 15:45:56.354: I/dalvikvm(555): Wrote stack traces to '/data/anr/traces.txt'
04-17 15:45:56.635: D/gralloc_goldfish(555): Emulator without GPU emulation detected.
04-17 15:45:56.763: I/dalvikvm(555): threadid=3: reacting to signal 3
04-17 15:45:56.863: I/dalvikvm(555): Wrote stack traces to '/data/anr/traces.txt'
04-17 15:47:12.763: I/dalvikvm(555): threadid=3: reacting to signal 3
04-17 15:47:12.783: I/dalvikvm(555): Wrote stack traces to '/data/anr/traces.txt'
04-17 15:47:15.883: D/dalvikvm(555): GC_CONCURRENT freed 169K, 5% free 6749K/7047K, paused 8ms+6ms
04-17 15:47:32.033: D/dalvikvm(555): GC_CONCURRENT freed 386K, 8% free 6785K/7303K, paused 5ms+26ms
04-17 15:47:37.123: E/JSON Parser(555): Error parsing data org.json.JSONException: End of input at character 0 of
04-17 15:47:37.123: W/dalvikvm(555): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
04-17 15:47:37.166: E/AndroidRuntime(555): FATAL EXCEPTION: AsyncTask #1
04-17 15:47:37.166: E/AndroidRuntime(555): java.lang.RuntimeException: An error occured while executing doInBackground()
04-17 15:47:37.166: E/AndroidRuntime(555): at android.os.AsyncTask$3.done(AsyncTask.java:278)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-17 15:47:37.166: E/AndroidRuntime(555): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.lang.Thread.run(Thread.java:856)
04-17 15:47:37.166: E/AndroidRuntime(555): Caused by: java.lang.NullPointerException
04-17 15:47:37.166: E/AndroidRuntime(555): at com.example.independentretailers.retailersignup$CreateNewRetailer.doInBackground(retailersignup.java:97)
04-17 15:47:37.166: E/AndroidRuntime(555): at com.example.independentretailers.retailersignup$CreateNewRetailer.doInBackground(retailersignup.java:1)
04-17 15:47:37.166: E/AndroidRuntime(555): at android.os.AsyncTask$2.call(AsyncTask.java:264)
04-17 15:47:37.166: E/AndroidRuntime(555): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-17 15:47:37.166: E/AndroidRuntime(555): ... 5 more
04-17 15:47:40.524: I/dalvikvm(579): threadid=3: reacting to signal 3
04-17 15:47:40.582: I/dalvikvm(579): Wrote stack traces to '/data/anr/traces.txt'
04-17 15:47:40.753: D/gralloc_goldfish(579): Emulator without GPU emulation detected.
答案 0 :(得分:0)
解析您的JSON时出错。我建议记录您的JSON响应,可能是这样的:
// try parse the string to a JSON object
try {
Log.d("My JSON", json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
从那里,您可以看到问题是在您的PHP中还是在您的应用中。