Android应用程序中jsonObject的空值 [英] Null value for jsonObject in android app

查看:264
本文介绍了Android应用程序中jsonObject的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨晚发布了此问题,但无法解决我的问题.所以我再次发表这篇文章,希望大家可以帮助我.谢谢 ! 我有从json对象获取值的问题.json_encode将空字符串返回给android.

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

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:

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

Jsonparser:

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

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 {

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

  }

}

推荐答案

尝试使用此解析器:

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.

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

例如,带有$encoded_rows = array_map('utf8_encode', $response);的响应将如下所示:

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

{"success":"0"}

,并且只有echo json_encode($response);:

{"success":0}

所以,我认为,这:int success = json.getInt(TAG_SUCCESS);不起作用.

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

请勿使用array_map('utf8_encode', $response);或在Java中使用此行:

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

String success = json.getString(TAG_SUCCESS);

这篇关于Android应用程序中jsonObject的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆