duanmibei1929 2015-05-01 09:37
浏览 71

android app中jsonObject的空值[重复]

This question is an exact duplicate of:

I posted this problem last night but I can't solve my problem . so I post this again hope members can help me . Thanks ! I have problem with getting value from json object .json_encode return null string to android.

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);
  }

And here is my piece of 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();
        }

Edit :

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 + "
");
        }
        }
        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();      
        }


    });
}

class CreateNewBook extends 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();
    */
    }

  }

}
</div>
  • 写回答

1条回答 默认 最新

  • duanhuantong8278 2015-05-01 11:08
    关注

    Try this parser:

    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 + "
    ");
                }
                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;
    
        }
    }
    

    If you are using $encoded_rows = array_map('utf8_encode', $response); the variable type of successs is changed from INTEGER to STRING.

    for example, the response with $encoded_rows = array_map('utf8_encode', $response); will look like this:

    {"success":"0"}
    

    and, with only echo json_encode($response);:

    {"success":0}
    

    So, I think, this: int success = json.getInt(TAG_SUCCESS); won't work.

    Don't use array_map('utf8_encode', $response); or use this line in Java:

    String success = json.getString(TAG_SUCCESS);

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题