Vincent Tang
Vincent Tang

Reputation: 280

How to retrieve the json array after post parameter to PHP through Android

This is my JAVA class, I have SendPHP() AsyncTask to post my chosen date to PHP and another RequestTask() AsyncTask to retrieve my JSON Array

    public class CustomerPage extends Fragment {
    private FragmentActivity activity;
    private RecyclerView rv;
    private LinearLayoutManager layoutManager;
    private AlertDialog alertDialog;
    private List<Customer> customers;
    private RequestTask task;
    private CustomerAdapter adapter;
    private String url ="http://eac.asia/eacsales/Newstar/get_customer.php";
    private String TAG_STATUS = "status";
    private String TAG_CUSTOMER = "customers";
    private Calendar calendar;
    private int year,month,day;
    private TextView tvDate;
    private ImageView imgSearch;
    private String output;
    String strDay , strMonth,strYear;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = (FragmentActivity) getActivity();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.customer_page,container,false);
    rv = (RecyclerView) v.findViewById(R.id.rvCustomer);
    tvDate = (TextView)v.findViewById(R.id.dateView);
    imgSearch = (ImageView)v.findViewById(R.id.img_search);
    layoutManager = new LinearLayoutManager(getActivity());
    calendar = Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);

    rv.setLayoutManager(layoutManager);
    rv.setItemAnimator(new DefaultItemAnimator());

    tvDate.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {
            DialogFragment dialogFragment = new DateFragment();
            dialogFragment.show(getActivity().getSupportFragmentManager(), "DatePicker");
        }
    });

    return v;
}

@Override
public void onResume() {
    super.onResume();
}

private void sendRequest() {
    if (enableNetwork()) {
        task = new RequestTask();
        task.execute(url);
    } else {
        showAlertDialog("No Internet Connection");
    }
}
public void showAlertDialog(String message) {
    alertDialog = new AlertDialog.Builder(getActivity()).create();
    alertDialog.setMessage(message);
    alertDialog.setCancelable(false);

    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    alertDialog.show();
}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

private class RequestTask extends AsyncTask<String, Void, List<Customer>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<Customer> doInBackground(String... urls) {
        try {
            JSONObject jsonObject = getJsonObject(urls[0]);
            Log.d("All data: ", jsonObject.toString());

            if (jsonObject != null) {
                boolean status = jsonObject.getBoolean(TAG_STATUS);
                Log.d("Status: ", String.valueOf(status));

                if (status) {
                    customers = CustomerJsonReader.getHome(jsonObject.getJSONArray(TAG_CUSTOMER));
                } else {

                }

            }else {
                showAlertDialog("Connection Problem");
            }
            URL url = new URL("http://eac.asia/eacsales/Newstar/get_customer.php");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                // Append server response in string
                sb.append(line + "\n");
            }
            Log.d("Return Post",sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return customers;
    }
    /**
     * It returns jsonObject for the specified url.
     *
     * @param url
     * @return JSONObject
     */
    public JSONObject getJsonObject(String url) {
        JSONObject jsonObject = null;
        try {
            jsonObject = GetJSONObject.getJSONObject(url);
        } catch (Exception e) {
        }
        return jsonObject;
    }

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

        customers = result;
            if (customers != null && customers.size() != 0) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new CustomerAdapter(getActivity(), customers);
                        rv.setAdapter(adapter);
                    }
                });
            }else{
                Toast.makeText(getActivity(), "No Product found", Toast.LENGTH_SHORT).show();
            }
    }
}
public boolean enableNetwork() {

    ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()
                && netInfo.isConnectedOrConnecting()
                && netInfo.isAvailable()) {
            return true;
        }
    }
    return false;
}
class DateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dp = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this,yy,mm,dd);
            return dp;

    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        populateSetDate(year,monthOfYear+1,dayOfMonth);
    }

    public void populateSetDate(int year, int month, int day) {
        tvDate.setText(month + "/" + day + "/" + year);
        strDay = String.valueOf(day);
        strMonth = String.valueOf(month);
        strYear = String.valueOf(year);
        new SendPHPRequest(getActivity()).execute(strDay,strMonth,strYear);
    }
}

class SendPHPRequest extends AsyncTask<String, Void, String> {
    private Context context;

    public SendPHPRequest(Context context){
        this.context = context;
    }
    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(String... params) {

        String day = params[0];
        String month = params[1];
        String year = params[2];
        StringBuilder sb = null;

        System.out.println("*** doInBackground ** day " + day + " month :" + month +"year :"+year);
        try {
            String data = URLEncoder.encode("day", "UTF-8")
                    + "=" + URLEncoder.encode(day, "UTF-8");
            data += "&" + URLEncoder.encode("month", "UTF-8") + "="
                    + URLEncoder.encode(month, "UTF-8");
            data += "&" + URLEncoder.encode("year", "UTF-8") + "="
                    + URLEncoder.encode(year, "UTF-8");

            URL url = new URL("http://eac.asia/eacsales/Newstar/get_customer.php");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);

            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
            wr.write(String.valueOf(data));
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            {
            // Append server response in string
                sb.append(line + "\n");
            }
            //noinspection ResourceType


        } catch (UnsupportedEncodingException uee) {
            System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
            uee.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        sendRequest();
    }
}

}

This is my PHP Code to get the date from Android and select the result from database according to the date, then display the result into JSON Object

    <?php
$con = mysql_connect("localhost","eac_sale_database","a123456Z","eac_sale_database");
$db = mysql_select_db("eac_sale_database");

$response = array();

$day = urldecode($_POST['day']);
$month = urldecode($_POST['month']);
$year = urldecode($_POST['year']);

$result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

if(mysql_num_rows($result)> 0){
    $response["customers"] = array();
        while($row = mysql_fetch_array($result)){
            $product = array();
            $product["custNo"] = $row["no"];
            $product["custName"] = $row["name"];
            $product["netSales"] = $row["net_sales"];
            $product["dayVisit"] = $row["day_visit"];
            $product["monthVisit"] = $row["month_visit"];
            $product["yearVisit"] = $row["year_visit"];
            $product["dateVisit"] = $row["date_visit"];
            array_push($response["customers"], $product);
    }
    $response["status"] = "true";
    header('Content-Type: application/json');
    header('Vary: User-Agent');

    echo json_encode($response);

}
  else{
      $response["status"] = "false";
     echo json_encode($response);
  }

?>

However, my output in the android log is showing that "status" = "false". I am very sure that my date parameter has been post to the PHP, but it just cannot do the query and output. Is there solution to this? Please kindly help.

This is the date in my database

DATA Sent get the JSONobject but it should be displayed in RequestTask()

Upvotes: 2

Views: 1161

Answers (2)

Rushi M Thakker
Rushi M Thakker

Reputation: 679

Problem is on your php side:

  1. $con = mysql_connect("localhost","eac_sale_database","a123456Z");

only 3 parameters required here because you have already written

$db = mysql_select_db("eac_sale_database");
  1. Do this:

    $day = urldecode($_GET['day']);
    $month = urldecode($_GET['month']);
    $year = urldecode($_GET['year']);

Use postman to verify your code and be sure your username and password are correct because your username and database name are same which should not be.

I tried your code creating a database and php file on my side and I am getting a json object like this:

{"customers":[{"custNo":"1","custName":"Rushi","netSales":"30000","dayVisit":"5","monthVisit":"7","yearVisit":"2016","dateVisit":"2016-10-05 10:24:33"}],"status":"true"}

Why do you have same file for inserting into db and fetching from db? You have to create different files for both.Also, why are you not returning in doInBackground? I think your requestTask will work properly if you request the same way you request in sendPHP because it is what your php query is doing. Your request in RequestTask doesn't contain any parameter to search through. You need to learn bit more on php.

MY PHP. It returns the row corresponding to particular date if requested url is like: :http://localhost/stacktest/get_customer.php?day=5&month=7&year=2016 and returns all details if requested URL is like:http://localhost/stacktest/get_customer.php Hope you get what I am saying. You need to change your sql queries on php side and your requests on android side.

<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("stacktest");

$response = array();
print_r($_GET);
if(isset($_GET['day']))
{
$day = urldecode($_GET['day']);
$month = urldecode($_GET['month']);
$year = urldecode($_GET['year']);

$result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

if(mysql_num_rows($result)> 0){
    $response["customers"] = array();
        while($row = mysql_fetch_array($result)){
            $product = array();
            $product["custNo"] = $row["no"];
            $product["custName"] = $row["name"];
            $product["netSales"] = $row["net_sales"];
            $product["dayVisit"] = $row["day_visit"];
            $product["monthVisit"] = $row["month_visit"];
            $product["yearVisit"] = $row["year_visit"];
            $product["dateVisit"] = $row["date_visit"];
            array_push($response["customers"], $product);
    }
    $response["status"] = "true";
    header('Content-Type: application/json');
    header('Vary: User-Agent');

    echo json_encode($response);

}
  else{
      $response["status"] = "false";
     echo json_encode($response);
  }
}
else{
    $result = mysql_query("SELECT * FROM customer ")or die(mysql_error());

if(mysql_num_rows($result)> 0){
    $response["customers"] = array();
        while($row = mysql_fetch_array($result)){
            $product = array();
            $product["custNo"] = $row["no"];
            $product["custName"] = $row["name"];
            $product["netSales"] = $row["net_sales"];
            $product["dayVisit"] = $row["day_visit"];
            $product["monthVisit"] = $row["month_visit"];
            $product["yearVisit"] = $row["year_visit"];
            $product["dateVisit"] = $row["date_visit"];
            array_push($response["customers"], $product);
    }
    $response["status"] = "true";
    header('Content-Type: application/json');
    header('Vary: User-Agent');

    echo json_encode($response);
}
}
?>

If you want to display only the data corresponding to a given date do this:

class SendPHPRequest extends AsyncTask<String, Void, String> {
               ...
               ...
               ...
                protected String doInBackground(String... params) {
                 ...
                 ...
                 return sb.toString();
                 }
                    protected void onPostExecute(String result) {
                    RequestTask(result);
                }

Only do json parsing in RequestTask. Otherwise there is no need of RequestTask.

Keep your php as:

<?php
    $con = mysql_connect("localhost","root","");
    $db = mysql_select_db("stacktest");

    $response = array();

    $day = urldecode($_GET['day']);
    $month = urldecode($_GET['month']);
    $year = urldecode($_GET['year']);

    $result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

    if(mysql_num_rows($result)> 0){
        $response["customers"] = array();
            while($row = mysql_fetch_array($result)){
                $product = array();
                $product["custNo"] = $row["no"];
                $product["custName"] = $row["name"];
                $product["netSales"] = $row["net_sales"];
                $product["dayVisit"] = $row["day_visit"];
                $product["monthVisit"] = $row["month_visit"];
                $product["yearVisit"] = $row["year_visit"];
                $product["dateVisit"] = $row["date_visit"];
                array_push($response["customers"], $product);
        }
        $response["status"] = "true";
        header('Content-Type: application/json');
        header('Vary: User-Agent');

        echo json_encode($response);

    }
      else{
          $response["status"] = "false";
         echo json_encode($response);
      }

    ?>

Upvotes: 1

Aung Myo Linn
Aung Myo Linn

Reputation: 2890

1). try changing your URLConnection to HttpURLConnection and set a POST request method.

From:

URLConnection con = url.openConnection();
con.setDoOutput(true);

To:

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");

2). dump and check your $_POST in php, var_dump($_POST);die(); the result should look like this:

array(3) {
  ["day"]=>
  string(1) "6"
  ["month"]=>
  string(7) "10"
  ["year"]=>
  string(4) "2016"
}

3). if you want to send the request as JSON, you might want to try

con.setRequestProperty("Content-Type","application/json");

4). if your request body is JSON, then try:

$json = file_get_contents('php://input');
$date = json_decode($json);

you will get $date["day"], $date["month"] and $date["year"].

5). try adding response headers in php as something like below:

header('Content-Type: application/json');
header('Vary: User-Agent');

echo json_encode($response);

Note: use a tool like Postman to verify if your request and API work or not.

Upvotes: 1

Related Questions