简体   繁体   中英

How can i post data to php using json just to receive data depending on posted data?

i'm trying to post data to my php-file using json. In my php-file, I want to use the posted data for a mySQL-Select-Statement and return the selection to my code and displaying it as a list.

What is the simpliest way to do it?

This is my 'postData()':

   public void postData() {
    //trying 
    List<Map<String, String>> buyCategories = new ArrayList<Map<String, String>>();
    //trying

    try{
        // url where the data will be posted
        String postReceiverUrl = "http://www.url.de/getArticles.php";

        // HttpClient
        HttpClient httpClient = new DefaultHttpClient();

        // post header
        HttpPost httpPost = new HttpPost(postReceiverUrl);

        int cat = UsingSharedPrefs.getChosenCategorie();
        if(cat == 0) {
            cat = 100;
        }
        String cats = Integer.toString(cat);

        // add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("categorieId", cats));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // execute HTTP post request
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.getJSONArray("testproducts");
            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.getString("testproduct_name");
                String price = jsonChildNode.getString("testproduct_price");
                String path = jsonChildNode.getString("testproduct_buffer");

                HashMap<String, String> hmBuyCategories = new HashMap<String,String>();
                hmBuyCategories.put("txt", "Categorie : " + name);
                hmBuyCategories.put("pri", "Price : " + price);
                hmBuyCategories.put("bes","Currency : " + path);

                int imageId = getResources().getIdentifier("jollocks.logle:drawable/" + path, null, null);

                hmBuyCategories.put("pic", Integer.toString(imageId) );

                buyCategories.add(hmBuyCategories);
                }
            String responseStr = EntityUtils.toString(resEntity).trim();
            Log.v(TAG, "Response: " +  responseStr);
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Errortest" + e.toString(),
        Toast.LENGTH_SHORT).show();
    }

    String[] from = { "pic","txt","pri", "bes" };

    int[] to = { R.id.buffer,R.id.name, R.id.price, R.id.beschreibung};

    ListView listView = ( ListView ) findViewById(R.id.sampleListView);

    SimpleAdapter simpleAdapter = new SimpleAdapter(this, buyCategories,
    R.layout.list_item_product,
    from, to);
    listView.setAdapter(simpleAdapter);
}

You can use volley library. Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don't have to worry about using asynctask anymore.

http://developer.android.com/training/volley/simple.html

First of all you should move the code in a separate thread to avoid ANR. You could use an AsyncTask but be aware of memory lekeage. Otherwise you can use volley as suggested or OkHttp. They are libraries that help you to manage HTTP connection and handle requests in a separate thread.

For example if you want to use OkHttp:

  OkHttpClient client = new OkHttpClient();
  Request request = new Request.Builder().url(url).build();
  client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request request, IOException e) {
           // Notify error
        }

        @Override
        public void onResponse(Response response) throws IOException {

               // Here you parse the response
               // when ready update the View
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Here you update the listview
                    }
                });

        }
    });

Hope it will help you!!

First of all, you should know that running this code on the main UI would give you errors, you try implementing this in a AsyncTask.

Secondly, "JSONObject jsonResponse = new JSONObject(jsonResult);" where did you declare the "jsonResult" variable, according to your codes i don't see where you declared. Also you should know that DefaultHttpClient is now deprecated, its better to use UrlConnect for your http calls.

Lastly i agree with Patil, you should get your hands on some android networking libraries eg Retrofit or Volley and play around with since you are a beginner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM