2015-05-01 62 views
0

昨晚我發佈了這個問題,但我無法解決我的問題。所以我再次發佈這個希望會員可以幫助我。謝謝 ! 我有問題從json對象獲取值.json_encode返回空字符串到android。Android應用程序jsonObject的空值

的logcat:

05-01 22:36:21.653: D/Create Response(801): {} 

05-01 22:36:21.653: W/System.err(801): org.json.JSONException: No value 
for success 

05-01 22:36:21.663: W/System.err(801): at 

org.json.JSONObject.get(JSONObject.java:354) 

05-01 22:36:21.663: W/System.err(801): at 

org.json.JSONObject.getInt(JSONObject.java:443) 

MyPhp.php

<?php 


header('Content-type=application/json; charset=utf-8'); 
$response = array(); 
// check for required fields 
if (isset($_POST['B_Name']) && isset($_POST['Au_Name']) && 
isset($_POST['Pub']) && isset($_POST['Pr']) && 
isset($_POST['B_Genre'])) { 

$B_Name = $_POST['B_Name']; 
$Au_Name = $_POST['Au_Name']; 
$Pub = $_POST['Pub']; 
$Pr = $_POST['Pr']; 
$B_Genre = $_POST['B_Genre']; 

// include db connect class 
require_once(__DIR__ . '/android/db_connect.php'); 

// connecting to db 
$db = new DB_CONNECT(); 

// mysql inserting a new row 
$result = mysql_query("INSERT INTO products(Book_Name, Author_Name, Book_Genre, Price, Publication) VALUES('$B_Name', '$Au_Name', '$B_Genre', '$Pr', '$Pub')"); 

// check if row inserted or not 
if ($result) { 
    // successfully inserted into database 
    $response["success"] = 1; 
    $response["message"] = "Product successfully created."; 


$encoded_rows = array_map('utf8_encode', $response); 
    echo json_encode($encoded_rows); 
} else { 
    // failed to insert row 
    $response["success"] = 0; 
    $response["message"] = "Oops! An error occurred."; 

    $encoded_rows = array_map('utf8_encode', $response); 
    echo json_encode($encoded_rows); 
    } 
} else { 

    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 
    $encoded_rows = array_map('utf8_encode', $response); 
    echo json_encode($encoded_rows); 
    } 

這裏是我的一片doInBackground的:

 String B_Name = BookName.getText().toString(); 
     String Au_Name = AuthorName.getText().toString(); 
     String Pub = Publication.getText().toString(); 
     String Pr = Price.getText().toString(); 
     String B_Genre = BookGenre.getText().toString(); 


     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("B_Name", B_Name)); 
     params.add(new BasicNameValuePair("Au_Name", Au_Name)); 
     params.add(new BasicNameValuePair("Pub", Pub)); 
     params.add(new BasicNameValuePair("Pr", Pr)); 
     params.add(new BasicNameValuePair("B_Genre", B_Genre)); 

     // getting JSON Object 
     // Note that create product url accepts POST method 
     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) { 
       Intent i = new Intent(getApplicationContext(),  
     MainActivity.class); 
       startActivity(i); 
       finish(); 


      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

編輯:

Jsonparser:

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.equals("POST")){ 

      HttpClient httpclient = getNewHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setHeader("Content-type", "application/json"); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse = httpclient.execute(httpPost); 
      if(httpResponse != null){ 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
      } 

     }else if(method.equals("GET")){ 
      // request method is GET 
      HttpClient httpclient = getNewHttpClient(); 
      String paramString = URLEncodedUtils.format(params, "utf-8"); 
      url += "?" + paramString; 
      HttpGet httpGet = new HttpGet(url); 

      HttpResponse httpResponse = httpclient.execute(httpGet); 
      if(httpResponse != null){ 
      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(); 
     sb.append("{"); 
     sb.append(StringUtils.substringBeforeLast(StringUtils.substringAfter(json, "{"), "}")); 
     sb.append("}"); 
     String line = null; 
     if(reader != 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; 

} 


public HttpClient getNewHttpClient() { 
    try { 
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
     trustStore.load(null, null); 

     SSLSocketFactory sf = new MySSLSocketFactory(trustStore); 
     sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

     SchemeRegistry registry = new SchemeRegistry(); 
     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
     registry.register(new Scheme("https", sf, 443)); 

     ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

     return new DefaultHttpClient(ccm, params); 
    } catch (Exception e) { 
     return new DefaultHttpClient(); 
    } 
} 
} 

Sale.java

public class Sale extends Activity { 

// Progress Dialog 
private ProgressDialog pDialog; 

JSONParser jsonParser = new JSONParser(); 
EditText BookName; 
EditText AuthorName; 
EditText Publication; 
EditText Price; 
EditText BookGenre; 

// url to create new product 
private static String url_create_product = "https://5.144.130.36:2083/android/create_product.php"; 

// JSON Node names 
private static final String TAG_SUCCESS = "success"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
    setContentView(R.layout.sale); 

    BookName = (EditText) findViewById(R.id.BookName); 
    AuthorName = (EditText) findViewById(R.id.AuthorName); 
    Publication = (EditText) findViewById(R.id.Publication); 
    Price = (EditText) findViewById(R.id.Price); 
    BookGenre = (EditText) findViewById(R.id.BookGenre); 


    Button confirm = (Button) findViewById(R.id.Confirm); 


    confirm.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      new CreateNewBook().execute();  
     } 


    }); 
} 

類CreateNewBook擴展的AsyncTask {

@Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(Sale.this); 
     pDialog.setMessage("?? ??? ??? ???? ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    protected String doInBackground(String... args) { 
     Sale.this.runOnUiThread(new Runnable() { 
       public void run() { 
     String B_Name = BookName.getText().toString(); 
     String Au_Name = AuthorName.getText().toString(); 
     String Pub = Publication.getText().toString(); 
     String Pr = Price.getText().toString(); 
     String B_Genre = BookGenre.getText().toString(); 


     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("B_Name", B_Name)); 
     params.add(new BasicNameValuePair("Au_Name", Au_Name)); 
     params.add(new BasicNameValuePair("Pub", Pub)); 
     params.add(new BasicNameValuePair("Pr", Pr)); 
     params.add(new BasicNameValuePair("B_Genre", B_Genre)); 

     // getting JSON Object 
     // Note that create product url accepts POST method 
     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) { 
       Intent i = new Intent(getApplicationContext(), MainActivity.class); 
       startActivity(i); 
       finish(); 


      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

       } 
    }); 

     return null; 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String result) { 
     // dismiss the dialog once done 
     pDialog.cancel(); 
     /* 
     if (result !=null && result.equals("1")) 
      Toast.makeText(getApplicationContext(), "submit ", Toast.LENGTH_LONG).show(); 
    */ 
    } 

    } 

} 
+0

你檢查JSON響應包含成功的關鍵和價值? –

+0

@hdiz你檢查過網頁瀏覽器嗎? – Wizard

+0

是你提供的路徑中的db_connect.php。 – Codelord

回答

0

試試這個解析器:

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, HTTP.UTF_8)); 

       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"), 10000); 
      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; 

    } 
} 

如果您正在使用$encoded_rows = array_map('utf8_encode', $response); 變量類型的successs從INTEGER更改爲STRING。

例如,與$encoded_rows = array_map('utf8_encode', $response);響應將是這樣的:

{"success":"0"} 

,並與只echo json_encode($response);

{"success":0} 

所以,我認爲,這樣的:int success = json.getInt(TAG_SUCCESS);將無法​​正常工作。

不要使用array_map('utf8_encode', $response);或使用該線在Java中:

String success = json.getString(TAG_SUCCESS);