0

i need help.

just want to know how to pass value to my php using JSON?

in my CategoryFragment code i set value to my cid

cid = catid;

now i want to pass this value to my php using JSON in this code

DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");

this is my CategoryFragment.java

package com.example.administrator.mosbeau;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
/**
 * Created by Administrator on 9/18/2015.
 */
public class CategoryFragment extends Fragment {

    public static CategoryFragment newInstance(String id,String name) {
        CategoryFragment fragment = new CategoryFragment();

        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putString("name", name);
        fragment.setArguments(bundle);

        return fragment;
    }

    public CategoryFragment () {
    }

    EditText tpid, tpname;
    String cid;
    String cname;

    String myJSON;
    JSONArray jsonarray;
    GridView productgridview;
    GridViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    public static String products_id = "products_id";
    public static String products_name = "products_name";
    public static String products_price = "products_price";
    public static String products_image = "products_image";

    Boolean InternetAvailable = false;
    Seocnd detectconnection;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.categorylayout, container, false);

        getActivity().invalidateOptionsMenu();

        tpid = (EditText) rootView.findViewById(R.id.tpid);
        tpname = (EditText) rootView.findViewById(R.id.tpname);

        if(getArguments() != null) {
            String catid = getArguments().getString("id");
            String catname = getArguments().getString("name");

            tpid.setText(catid);
            tpname.setText(catname);
            cid = catid;
            cname = catname;
        }

        productgridview = (GridView) rootView.findViewById(R.id.productgridview);

        //new DownloadJSON().execute();

        detectconnection = new Seocnd(getActivity());
        InternetAvailable = detectconnection.InternetConnecting();
        if (InternetAvailable) {
            getProduct();
        } else {
            NointernetFragment fragment = new NointernetFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();
        }

        return rootView;
    }

    public void getProduct(){
        class DownloadJSON extends AsyncTask<String, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(getActivity());
                // Set progressdialog title
                mProgressDialog.setTitle(cname);
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;

                try {
                    // Locate the array name in JSON
                    JSONObject jsonObj = new JSONObject(myJSON);
                    jsonarray = jsonObj.getJSONArray("products");

                    arraylist = new ArrayList<HashMap<String, String>>();

                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject p = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("products_id", p.getString("products_id"));
                        map.put("products_name", p.getString("products_name"));
                        map.put("products_price", p.getString("products_price"));
                        map.put("products_image", p.getString("products_image"));
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }

                adapter = new GridViewAdapter(getActivity(), arraylist);
                // Set the adapter to the GridView
                productgridview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
        DownloadJSON g = new DownloadJSON();
        g.execute();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(2);
    }
}

after i pass the value i want to use it in this part of my php code

$cid = "CID value here from java";

here is the complete php code..

products.php

<?php
    include('dbconnection.php');

    $cid = "CID value here from java";

    $statement = mysqli_query($con, "SELECT p.products_id, pd.products_name, p.products_price, p.products_image FROM products p INNER JOIN products_description pd ON p.products_id=pd.products_id WHERE p.products_status='1' ORDER BY p.products_sort_order ASC");

    $products = array();

    while($row = mysqli_fetch_array($statement)){
      array_push($products,
        array(
        'products_id'=>$row[0],
        'products_name'=>$row[1],
        'products_price'=>$row[2],
        'products_image'=>"http://joehamirbalabadan.com/android/images/".$row[3]
        ));
    }

    echo json_encode(array("products"=>$products));
    mysqli_close($con);
?>

help me to construct my code.. thanks..

1
  • Please only post relevant code. We don't need your entire codebase ;) Commented Oct 1, 2015 at 12:26

1 Answer 1

1

use following code for add parameters into http post request.I hope it will help you..!

    //Post Data
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("cid", "testid"));
    nameValuePair.add(new BasicNameValuePair("test", "testvalue"));

    //Encoding POST data
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    // finally make POST request.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.