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
Спасибо
@ Маниш Дубай
Согласно инструкции, которую я получил от вас, я изменил код в JSONObject. Пока ничего не будет отображаться в моей активности Allproducts. Ошибка Myt Logcat при добавлении Log.v ("json String", "Result =>" + json);
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.