0

I want to count no. of rows from the database table and display that number into the TextView

Here i tried but not getting the required output.

Here my complete code

Mainactivity.java

        package com.example.sachin.splashlogin;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Home extends Fragment {
    Activity activity;

    public Home() {};

    TextView visit;
    SessionManager session;
    CardView cardviewvisit, cardvieworder, cardviewpayment, cardviewdelivery;
    JSONObject jsonobject;
    private static String url_visitor = "http://10.0.2.2/portal/fetchvisit.php";
    JSONParser jParser = new JSONParser();
    JSONArray ownerObj, jsonarray;

    ArrayList<HashMap<String, String>> arraylist;
    ArrayList<String> v_username = new ArrayList<String>();
    ArrayList<String> v_parties1 = new ArrayList<String>();
    ArrayList<String> v_date = new ArrayList<String>();
    String suid, uid, wt_wod_code1, wt_party1;
    View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_home, container, false);
        getActivity().setTitle("Home");
        cardviewvisit = (CardView) view.findViewById(R.id.cardviewvisit);
        cardvieworder = (CardView) view.findViewById(R.id.cardvieworder);
        cardviewpayment = (CardView) view.findViewById(R.id.cardviewpayment);
        cardviewdelivery = (CardView) view.findViewById(R.id.cardviewdelivery);
        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);
        visit = (TextView) view.findViewById(R.id.visit1);
        cardviewvisit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Fragment fragment = new DeliveryTab();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.framelayout, fragment).commit();

            }
        });

        new DownloadJSON().execute();
        return view;
    }


    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... args) {

            // Create an array
            try {
                arraylist = new ArrayList<HashMap<String, String>>();

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("v_username", uid));

                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);

                    ownerObj = json.getJSONArray("visit");
                    for (int i = 0; i < ownerObj.length(); i++) {
                      wt_party1= json.getJSONArray("v_parties1").getJSONObject(0).getString("count");
                        jsonobject = ownerObj.getJSONObject(i);
                     // v_parties1.add(jsonobject.getString("v_parties"));
                    }
            } catch (Exception e) {
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void args) {
            visit.setText(v_parties1.toString());
        }
    }
}

Here APi file

fetchvisit.php

 <?php
    include("connection.php");

    $response = array();
    $User = $_REQUEST["v_username"];




    // get all products from products table
    date_default_timezone_set('Asia/Kolkata');
    $dt = date("m/d/Y");
    $result=mysql_query("select DISTINCT v_parties,v_date from abc WHERE v_date='$dt' AND v_username='$User' ")or die(mysql_error());
    $count = mysql_num_rows($result);


    if ($count > 0) {
        // looping through all results
        // products node

        $response["visit"] = array();
            while ($row = mysql_fetch_array($result))
        {
            echo $count;
            $visit = array();

            $visit["v_parties"] = $row["v_parties"];

            $response["success"]=1;




           // push single product into final response array
            array_push($response["visit"], $count);


        }

    $response["success"] = 1;
    echo json_encode($response);
    }
    else 
    {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No Visit found";

        // echo no users JSON
        echo json_encode($response);
    }


?>

Here the logcat

     10-13 13:05:05.200 486-512/com.example.sachin.splashlogin D/Parameters: http://10.0.2.2/portal/fetchvisit.php?v_username=JAYESHBHAI
10-13 13:05:07.039 486-492/com.example.sachin.splashlogin W/art: Suspending all threads took: 9.021ms
10-13 13:05:07.140 486-486/com.example.sachin.splashlogin I/Choreographer: Skipped 116 frames!  The application may be doing too much work on its main thread.
10-13 13:05:08.476 486-512/com.example.sachin.splashlogin D/reader: org.apache.http.conn.EofSensorInputStream@e5a22fd
10-13 13:05:08.476 486-512/com.example.sachin.splashlogin D/P: [v_username=JAYESHBHAI]
10-13 13:05:08.476 486-512/com.example.sachin.splashlogin E/Json Object:: {"visit":[1],"success":1}
10-13 13:05:08.969 486-486/com.example.sachin.splashlogin I/Choreographer: Skipped 109 frames!  The application may be doing too much work on its main thread.

i tried but it is not working at all. Please help me out from this..

1 Answers1

0

You need to use a debugger on this code, and step through each line of the DownloadJSON() method. Somewhere in here you have an error, where you've used the wrong method resulting in retrieving an integer where you expect a JSON object.

I suspect it might be one of these two lines, either by using the wrong jParser method, or by using a/the wrong parameter to getJSONArray().

JSONObject json = jParser.makeHttpRequest(url_visitor, "POST", params);
ownerObj = json.getJSONArray("visit");

I've found another question, which shows a slightly different approach of obtaining a JSON object from an API.

JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ArtikelURL);

Disclaimer: I don't actually know Java all that much, which explains the lack of details. In any case, apply a debugger to your code and you will find the problem.

Edit: Seeing as you had problems with the PHP code as well...

First off you really need to stop using the old mysql_*() functions, and you must read up on web security. Especially XSS, SQL injections, input validation, and related subjects. Your code is woefully insecure.

I've made some changes to your code, and added comments to highlight what I've done and why.

include ("connection.php");

$response = array ();

// You really need to validate the input here, to prevent against both mistyping and malicious users.
$User = $_REQUEST["v_username"];

// get all products from products table
date_default_timezone_set ('Asia/Kolkata');
$dt = date ("m/d/Y");

// First of use PDO as the old(!) mysql_*() functions are deprecated, insecure and removed in PHP7.
$db = new PDO (.....);

// Next we use prepared statements to prevent SQL injections.
$stmt = $db->prepare ("select DISTINCT v_parties,v_date from abc WHERE v_date=:date AND v_username=:user ");
$res = $stmt->execute (array (
        ':date' => $dt,
        ':user' => $User));

// 0 is a "falsey" value, so this will handle if we get no rows returned from the query.
if (!$count = $stmt->num_rows) {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No Visit found";

    // Echo no users JSON, and exit early. 
    echo json_encode ($response);
    die ();
}

// Since you only want to know the number of rows, no need to loop. 
$response["visit"] = $count;
$response["success"] = 1;

// However, if you do want to have a list of all rows returned...
foreach ($stmt->fetchAll () as $row) {
    // No need to use array_push(), when you can use the following (normal) convention.
    $response['rows'][] = $row;
}

echo json_encode ($response);

For the next question I recommend explaining exactly what's wrong, why it's wrong, and what you expect to get from it. So that we don't have to waste time answering the wrong questions...

Community
  • 1
  • 1
ChristianF
  • 2,068
  • 9
  • 14
  • if i want to fetch a data from the database then this code is working perfectly but the thing which i want to do is to count the no. of rows datewise. –  Oct 13 '16 at 07:36
  • array_push($response["visit"], $count); –  Oct 13 '16 at 07:36
  • if i write $visit instead of $count then it will displaying the database data. but i want to count the no. of rows. –  Oct 13 '16 at 07:38
  • yup i'll surely do this and sry for my wrong quest.. thank you –  Oct 13 '16 at 08:01
  • You're welcome. Please remember to upvote and accept the answer. – ChristianF Oct 13 '16 at 08:03
  • Please update your question with the code you're currently using, including the response you are getting from the PHP script, and how this is different from what you require. – ChristianF Oct 13 '16 at 08:40
  • I updated my question and i want to use same api... so please suggest me the correction on the same code thank you –  Oct 13 '16 at 10:46