【问题标题】:Cannot list the data in my android application from Mysql无法从 Mysql 列出我的 android 应用程序中的数据
【发布时间】:2014-03-10 04:13:30
【问题描述】:
                Am new in Android development. I trying to do database CRUD  operation in my android application.
                I can successfully insert the data to the mysql.Am using PHP and JSON parsing for it.When the data inserted into database, the next activity should be listing the data.The problem is no data is coming into my listing activity. only the Activity is coming without data. kindly help me .



                Also  my java code for the listing products is



                public class AllProductsActivity extends ListActivity {

                    // Progress Dialog
                    private ProgressDialog pDialog;

                    // Creating JSON Parser object
                    JSONParser jParser = new JSONParser();

                    ArrayList<HashMap<String, String>> productsList;

                    // url to get all products list
                    private static String url_all_products = "http://10.0.2.2/get_all_products.php";

                    // JSON Node names
                    private static final String TAG_SUCCESS = "success";
                    private static final String TAG_PRODUCTS = "products";
                    private static final String TAG_PID = "pid";
                    private static final String TAG_NAME = "name";

                    // products JSONArray
                    JSONArray products = null;

                    @Override
                    public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.all_products);

                        // Hashmap for ListView
                        productsList = new ArrayList<HashMap<String, String>>();

                        // Loading products in Background Thread
                        new LoadAllProducts().execute();

                        // Get listview
                        ListView lv = getListView();

                        // on seleting single product
                        // launching Edit Product Screen
                        lv.setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                                // getting values from selected ListItem
                                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                                        .toString();

                                // Starting new intent
                                Intent in = new Intent(getApplicationContext(),
                                        EditProductActivity.class);
                                // sending pid to next activity
                                in.putExtra(TAG_PID, pid);

                                // starting new activity and expecting some response back
                                startActivityForResult(in, 100);
                            }
                        });

                    }

                    // Response from Edit Product Activity
                    @Override
                    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                        super.onActivityResult(requestCode, resultCode, data);
                        // if result code 100
                        if (resultCode == 100) {
                            // if result code 100 is received
                            // means user edited/deleted product
                            // reload this screen again
                            Intent intent = getIntent();
                            finish();
                            startActivity(intent);
                        }

                    }

                    /**
                     * Background Async Task to Load all product by making HTTP Request
                     * */
                    class LoadAllProducts extends AsyncTask<String, String, String> {

                        /**
                         * Before starting background thread Show Progress Dialog
                         * */
                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            pDialog = new ProgressDialog(AllProductsActivity.this);
                            pDialog.setMessage("Loading products. Please wait...");
                            pDialog.setIndeterminate(false);
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }

                        /**
                         * getting All products from url
                         * */
                        protected String doInBackground(String... args) {
                            // Building Parameters
                            List<NameValuePair> params = new ArrayList<NameValuePair>();
                            // getting JSON string from URL
                            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

                            // Check your log cat for JSON reponse
                            Log.d("All Products: ", json.toString());

                            try {
                                // Checking for SUCCESS TAG
                                int success = json.getInt(TAG_SUCCESS);

                                if (success == 1) {
                                    // products found
                                    // Getting Array of Products
                                    products = json.getJSONArray(TAG_PRODUCTS);

                                    // looping through All Products
                                    for (int i = 0; i < products.length(); i++) {
                                        JSONObject c = products.getJSONObject(i);

                                        // Storing each json item in variable
                                        String id = c.getString(TAG_PID);
                                        String name = c.getString(TAG_NAME);

                                        // creating new HashMap
                                        HashMap<String, String> map = new HashMap<String, String>();

                                        // adding each child node to HashMap key => value
                                        map.put(TAG_PID, id);
                                        map.put(TAG_NAME, name);

                                        // adding HashList to ArrayList
                                        productsList.add(map);
                                    }
                                } else {
                                    // no products found
                                    // Launch Add New product Activity
                                    Intent i = new Intent(getApplicationContext(),
                                            NewProductActivity.class);
                                    // Closing all previous activities
                                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(i);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            return null;
                        }

                        /**
                         * After completing background task Dismiss the progress dialog
                         * **/
                        protected void onPostExecute(String file_url) {
                            // dismiss the dialog after getting all products
                            pDialog.dismiss();
                            // updating UI from Background Thread
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    /**
                                     * Updating parsed JSON data into ListView
                                     * */
                                    ListAdapter adapter = new SimpleAdapter(
                                            AllProductsActivity.this, productsList,
                                            R.layout.list_item, new String[] { TAG_PID,
                                                    TAG_NAME},
                                            new int[] { R.id.pid, R.id.name });
                                    // updating listview
                                    setListAdapter(adapter);
                                }
                            });

                        }

                    }

                    }


                Here in this code , am trying to display three data , "name, price, description. The PHP file will 
                retrieve the data from the database mysql  , and convert the strings into JSon objects. Then my javacode will call the json class and list the data. I can successfully insert the data to the mysql.Am using PHP and JSON parsing for it.When the data inserted into database, the next activity should be listing the data.The problem is no data is coming into my listing activity. only the Activity is coming without data. kindly help me .


 My JSON class for parsing or converting is as follows

            This is my JSON parsing code .In this code first i created a function for get json from the url . then the code for making http request for GET and POST method by using if , else statement . In else method i put the code for get method . i converted it into json object , and the above android code will call it and display it in the activity..
        I used a JSON Parser class to get JSON from URL. This class supports two http request methods GET and POST to get json from url.
    As we are getting the JSON by making HTTP call, I am adding a Async method to make http calls on background thread. Add the follwing method in your main activity class

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

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

                    }
                }    


            This is my JSON parsing code .In this code first i created a function for get json from the url . then the code for making http request for GET and POST method by using if , else statement . In else method i put the code for get method . i converted it into json object , and the above android code will call it and display it in the activity..
    I used a JSON Parser class to get JSON from URL. This class supports two http request methods GET and POST to get json from url.
As we are getting the JSON by making HTTP call, I am adding a Async method to make http calls on background thread. Add the follwing method in your main activity class

谢谢
@Manish Dubay
根据我从您那里得到的说明,我更改了 JSONObject 中的代码。我的 Allproducts 活动中仍然不会显示任何内容。 我添加 Log.v("json String","Result => "+json);

时出现 Myt Logcat 错误
03-10 03:49:54.491: W/System.err(1559): org.json.JSONException: No value for products
03-10 03:49:54.491: W/System.err(1559):     at org.json.JSONObject.get(JSONObject.java:354)
03-10 03:49:54.508: I/Choreographer(1559): Skipped 97 frames!  The application may be doing too much work on its main thread.
03-10 03:49:54.528: W/System.err(1559):     at org.json.JSONObject.getJSONArray(JSONObject.java:548)
03-10 03:49:54.558: W/System.err(1559):     at com.example.sampleapp2.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:141)
03-10 03:49:54.618: W/System.err(1559):     at com.example.sampleapp2.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
03-10 03:49:54.668: W/System.err(1559):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-10 03:49:54.698: W/System.err(1559):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-10 03:49:54.718: W/System.err(1559):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-10 03:49:54.748: W/System.err(1559):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-10 03:49:54.788: W/System.err(1559):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-10 03:49:54.898: I/Choreographer(1559): Skipped 84 frames!  The application may be doing too much work on its main thread.
03-10 03:49:54.958: W/System.err(1559):     at java.lang.Thread.run(Thread.java:841)
03-10 03:49:55.038: I/Choreographer(1559): Skipped 83 frames!  The application may be doing too much work on its main thread.
03-10 03:49:55.168: I/Choreographer(1559): Skipped 212 frames!  The application may be doing too much work on its main thread.
03-10 03:49:55.218: I/Choreographer(1559): Skipped 55 frames!  The application may be doing too much work on its main thread.

【问题讨论】:

  • 能不能把你解析的json对象贴出来/
  • @Biraj Zalavadia , 你的意思是 JSON 类代码 /
  • 请将您的 json 响应放在这里...您必须在 json 解析方面遇到问题...
  • 我在我的帖子中发布了 json 响应。请检查一下,任何人都可以帮助我。
  • 你从服务器得到的响应

标签: java php android mysql


【解决方案1】:
Error parsing data org.json.JSONException: Value get_all_products.php of type java.lang.String cannot be converted to JSONObject

表示您的响应中没有来自 Web 服务的有效 json 字符串。因为这个 jObj = isValidJson(json); 不返回任何 json 对象。

在你上面的代码中,在

json = sb.toString();

您正在创建名为 json 的字符串并为其分配字符串构建器对象值。但是你 logcat 说你没有在下面一行得到有效的 json 字符串,

try {
                        jObj = new JSONObject(json);
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    }

所以它会抛出解析 json 字符串的错误。在这种情况下,您必须检查是否从服务器获取有效的 json 字符串作为响应。对上面的代码做一些修改:

public boolean isValidJson(String test)
{
    try {
        new JSONObject(test);
        return true;
    } catch(JSONException ex) { 
        return false;
    }
}

并且,在您的代码中:

try {
       if(isValidJson(json)
    {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
              Log.e("JSON Parser", "Error parsing data " + e.toString());
          }
    } 

【讨论】:

  • @Mainsh Dobey..一个小疑问。我已经在 J​​SONObject 类型中创建了 jObj。所以我无法将布尔值转换为 JSONObject。我该怎么办?
  • @user3367961 这是我的错误,在 if 条件下,我们必须检查它是否是有效的 json,然后将此字符串转换为 json 对象。更新了我的答案。
  • 我在上一节更新了代码jObj = new JSONObject(json);
  • 感谢您的帮助。我根据您的评论更新了我的代码.. 但不幸的是没有工作
  • 用 Log.v("json String","Result => "+json); 更新你的代码并将 logcat 详细信息添加到您的问题中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 2016-04-17
  • 2011-06-10
  • 2012-03-06
相关资源
最近更新 更多