以下代码有一个输出“JassonArrayFail”


The following code has a output "JassonArrayFail"

>我正在构建一个安卓应用程序,它将在表"产品"中搜索mysql DB。如果我输入产品名称,它将检索产品价格,增值税和序列号。但是代码给出了"jassonArrayFail"输出。我无法理解错误。请帮忙。问题出在//parse json data try{} 块中。

java代码是:

package selva.db;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class select extends Activity
{
StrictMode.ThreadPolicy policy = new      
 StrictMode.ThreadPolicy.Builder().permitAll().build();
 public void onCreate(Bundle savedInstanceState)
 {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select);
        Button button = (Button) findViewById(R.id.button1);
        StrictMode.setThreadPolicy(policy); 
        button.setOnClickListener(new View.OnClickListener()
        {
        public void onClick(View view)
          {
             String result = null;
            InputStream is = null;
            EditText editText = (EditText)findViewById(R.id.e1);
            String v1 = editText.getText().toString();
            EditText editText1 = (EditText)findViewById(R.id.e2);
            EditText editText2 = (EditText)findViewById(R.id.e3);
            EditText editText3 = (EditText)findViewById(R.id.e4);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("f1",v1));
                try
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://crimereport.site88.net/select123.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost); 
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    Log.e("log_tag", "connection success ");
                 //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                }
            catch(Exception e)
                {
                    Log.e("log_tag", "Error in http connection "+e.toString());
                    Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
                }
            //convert response to string
                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");
                          // Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
                    }
                    is.close();
                    result=sb.toString();
                }
                catch(Exception e)
                {
                   Log.e("log_tag", "Error converting result "+e.toString());
                Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
                }
            //parse json data
            try{

                  JSONObject object = new JSONObject(result);
                   String ch=object.getString("re");
                   if(ch.equals("success"))
                   {
                      JSONObject no = object.getJSONObject("0");
                    //long q=object.getLong("f1");
                     int w=no.getInt("price");
                            int e=no.getInt("vat");
                    int s=no.getInt("serial");
                   // editText1.setText(w);
                    String myString1 = NumberFormat.getInstance().format(w);
                    editText1.setText(myString1);
                   String myString = NumberFormat.getInstance().format(e);

                    editText2.setText(myString);
                   String myString2 = NumberFormat.getInstance().format(s);

                editText3.setText(myString2);
                     }

                   else
                   {
                        Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();
                   }

            }
            catch(JSONException e)
            {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                    Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
            }

       }
       });

 }

}

PHP代码是:

    <?php
     $con = mysql_connect("mysql1.000webhost.com","a4879149_crime","myprojects333");
     if (!$con)
       {
         die('Could not connect: ' . mysql_error());
       }
       mysql_select_db("a4879149_info", $con);
$v1=$_REQUEST['f1'];
//$v1='111';
if($v1==NULL)
 {

            $r["re"]="Enter the product!!!";
             print(json_encode($r));
            die('Could not connect: ' . mysql_error());


}

else
{




         // $v1="530";

       $i=mysql_query("SELECT * FROM product WHERE '$v1'=product",$con);
       $check='';
      while($row = mysql_fetch_array($i))
        {
              $r[]=$row;
              $check=$row['product'];
            // print(json_encode($r));

         }


     if($check==NULL)
       {            
                  $r["re"]="Product is not available";
                  print(json_encode($r));
         }
        else
         {

             $r["re"]="success";
//print(json_encode($r));
            // die('Could not connect: ' . mysql_error());

          } 

 }
 mysql_close($con);
 ?> 

您的代码不会总是返回 json(来自 php),这意味着很有可能没有适当的 json 字符串来解析。我会将您的代码 (php) 更改为以下内容:

$response = array();
$con = mysql_connect("mysql1.000webhost.com","a4879149_crime","myprojects333");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("a4879149_info", $con);
$v1 = $_REQUEST['f1'];
if (empty($v1)) {
    $response["re"] = "Enter the product!!!";
} else {
    $i = mysql_query("SELECT * FROM product WHERE '$v1' = product", $con);
    while($row = mysql_fetch_array($i)) {
        $response[] = $row;
    }
    if (empty($response)) {            
        $r["re"] = "Product is not available";
    } else {
        $r["re"] = "success";
    }   
}
mysql_close($con);
echo json_encode($response);
die;

如果成功,这应该始终返回如下响应:

{"re":"success","0":{"productId":1},"1":{"productId":2}}

或者在出现错误的情况下:

{"re":"Enter the product!!!"}