include ("/var/www/html/groups.php")
这是我的Json解析器 公共类JSONParser {
public class NewProductActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
Button createBtn;
private static String url_create_product = "http://10.0.2.2/create_product.php";
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
inputName = (EditText)findViewById(R.id.nameEt);
createBtn = (Button)findViewById(R.id.createBt);
createBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new CreateNewProduct().execute();
}
});
}
class CreateNewProduct extends AsyncTask<String,String,String>{
String name = inputName.getText().toString();
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args){
inputName = (EditText)findViewById(R.id.nameEt);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name",name ));
JSONObject json = jsonParser.makeHttprequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivty.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
这是我的php文件
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser(){}
public JSONObject makeHttprequest(String url, String method, List<NameValuePair> params){
try {
if (method.equals( "POST")){
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 .equals( "GET")){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params,"url");
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");
}
try {
jObj = new JSONObject(json);
}catch (JSONException e){
Log.e("JSON Parser","Error parsing");
}
return jObj;
}
}
这是我的错误日志
<?php
$response = array();
if(isset($_POST['name'])){
$name = $_POST['name'];
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("db");
$result = mysql_query("INSERT INTO product(name) VALUES ('$name')");
if($result){
$response["success"] = 1;
$response["message"] = "successfully inserted";
echo json_encode($respone);
}
else {
$response["success"] = 0;
$response["message"] ="error occured";
echo json_encode($response);
}
} else{
$response["success"] = 0;
$response["message"] = "required feild missing";
echo json_encode($response);
}
?>
我能够创建一个新产品,我的产品列表json正在更新,但我看不到产品列表
这是产品列表活动
06-27 18:35:55.097 3462-4317/com.example.joel339.sample E/JSON Parser: Error parsing
--------- beginning of crash
06-27 18:35:55.097 3462-4317/com.example.joel339.sample E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.joel339.sample, PID: 3462
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.doInBackground(NewProductActivity.java:70)
at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.access$dispatch(NewProductActivity.java)
at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:0)
at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:50)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
}
答案 0 :(得分:1)
错误就在这一行。
Log.d("Create Response", json.toString());
由于null
对象,它会为您提供空指针异常。
仔细检查此行,只需添加安全检查,如下所示
if (json == null || json == JSONObject.NULL){
// error handling..
}
else
{
// Your code
}
建议:(与崩溃无关)
只需在inputName = (EditText)findViewById(R.id.nameEt);
中删除此行doInBackground()
即可。您已在onCreate()中初始化此变量,因此只需将其删除即可。