简体   繁体   中英

How to pass a post value to server and store the result in the listview android

this is my listview where data is coming from the remote server in the JSON format so everything is working fine but now I have to pass a certain value to the server and then make a filter based on that value and then load only the desired result into the listview

public class Reciepe extends AppCompatActivity {

String Barname;
TextView food,price;
private ListView reciepeListView;
private ProgressDialog loading;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reciepe);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setBackgroundColor(Color.parseColor("#FFBC03"));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    new JSONTask().execute("http://thehostels.in/Foody/reciepe_json.php");
    DisplayImageOptions options = new DisplayImageOptions.Builder()

            .cacheInMemory(true)
            .cacheOnDisk(true)

            .build();
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(Reciepe.this)
            .defaultDisplayImageOptions(options)
            .build();
    com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    reciepeListView = (ListView)findViewById(R.id.list_recipe);



    Intent intent=getIntent();
    if(intent!=null){

        Barname=intent.getStringExtra("Type");
        Log.e("Type",Barname);
    }

    if (Barname != null) {

        switch (Barname) {
            case "Punjabi":

                getSupportActionBar().setTitle("Punjabi");
                break;
            case "Chinese":

                getSupportActionBar().setTitle("Chinese");
                break;
            case "South Indian":

                getSupportActionBar().setTitle("South Indian");
                break;
            case "Gujarati":

                getSupportActionBar().setTitle("Gujarati");
                break;
            case "Chicken":

                getSupportActionBar().setTitle("Chicken");
                break;
        }
    }
    }



public class JSONTask extends AsyncTask<String, String, List<Listview_reciepe_conveyer>> {

    ProgressDialog loading;


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loading = ProgressDialog.show(Reciepe.this, "loading,please wait...", null, true, true);
    }

    @Override
    protected List<Listview_reciepe_conveyer> doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {

            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }


            String finalJson = buffer.toString();
            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("list");
            List<Listview_reciepe_conveyer> fixture_conveyerList = new ArrayList<Listview_reciepe_conveyer>();

            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);
                Listview_reciepe_conveyer fixtureList = new Listview_reciepe_conveyer();
                fixtureList.setImage(finalObject.getString("image"));
                fixtureList.setFood(finalObject.getString("food"));
                fixtureList.setPrice(finalObject.getString("price"));

                fixture_conveyerList.add(fixtureList);
            }

            return fixture_conveyerList;




        }catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<Listview_reciepe_conveyer> result) {
        super.onPostExecute(result);

        if (result !=null) {
            loading.dismiss();
            ListAdapter adapter = new ListAdapter(Reciepe.this, R.layout.custom_recipe_list, result);
            reciepeListView.setAdapter(adapter);

        }
        else
        {

            Toast.makeText(Reciepe.this, "No Internet Connection!", Toast.LENGTH_LONG).show();
            loading.dismiss();
        }

    }
}



public class ListAdapter extends ArrayAdapter {

    private List<Listview_reciepe_conveyer> reciepe_conveyerList;
    private int resource;
    private LayoutInflater inflater;

    public ListAdapter(Context context, int resource, List<Listview_reciepe_conveyer> objects) {
        super(context, resource, objects);
        reciepe_conveyerList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {

            convertView = inflater.inflate(resource, null);
        }

        ImageView food_photo;
        final TextView food,price;


        food_photo = (ImageView)convertView.findViewById(R.id.food_photo);
        food = (TextView)convertView.findViewById(R.id.food_name);
        price = (TextView)convertView.findViewById(R.id.food_price);

        ImageLoader.getInstance().displayImage(reciepe_conveyerList.get(position).getImage(), food_photo);

        food.setText(reciepe_conveyerList.get(position).getFood());

        String newprice= ("Rs."+reciepe_conveyerList.get(position).getPrice());
        price.setText(newprice);


        reciepeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                                   @Override
                                                   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                                       Intent i=new Intent(Reciepe.this,Description.class);
                                                       i.putExtra("Dish",reciepe_conveyerList.get(position).getFood());
                                                       i.putExtra("Price",reciepe_conveyerList.get(position).getPrice());
                                                       startActivity(i);
                                                   }
                                               }

        );



        return convertView;
    }
}

  }

this is what my code looks like where i am loading a list from an api,

so i am using AsyncTask to load the listview but i do not know how to make the post request , i have updated the api it os taking the post values but what changes do i need to make on android level.., i have to pass the 'barname' as the post parameter...

On:

protected List<Listview_reciepe_conveyer> doInBackground(String... params) {

Try:

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

params.add(new BasicNameValuePair("firstParam", "paremeterValue")); 
//your param nr.1. 
//This is the value that you want to send. 
//It is represented like 'name=value', or in your case 'firstParam=parameterValue'. 
//You need to edit this field in respect to what you are doing. 

params.add(new BasicNameValuePair("secondParam", "your2parameter")); 
//your param nr.2 
//This is the value that you want to send. 
//It is represented like 'name=value', or in your case 'secondParam=your2parameter'. 
//You need to edit this field in respect to what you are doing. 


params.add(new BasicNameValuePair("thirdParam", "anotherParameter")); 
//your param nr.3
//This is the value that you want to send. 
//It is represented like 'name=value', or in your case 'thirdParam=anotherParameter'. 
//You need to edit this field in respect to what you are doing. 


// Write(add) parameters to your request

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

Before your..:

InputStream stream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); ...


EDITED

private String getQuery(List<BasicNameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (String pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

This function turn's the List params, in a String with the format, 'name=value' which is needed to send via request.

For more info see Query String .

Please do NOT copy and paste the solution, you also need to understand what you are doing and replace variables/methods accordingly, for this code to work.

Best

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