怎么算不。数据库表的行并在TextView上显示它?

时间:2016-10-13 07:04:55

标签: php android mysql json

我想要数不。数据库表中的行数并将该数字显示在TextView

这里我试过但没有得到所需的输出。

这是我的完整代码

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());
        }
    }
}

这里是APi文件

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);
    }


?>

这里是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.

我试过但它根本不起作用。 请帮帮我..

1 个答案:

答案 0 :(得分:0)

您需要在此代码上使用调试器,并逐步执行DownloadJSON()方法的每一行。在这里的某个地方你有一个错误,你使用了错误的方法导致检索一个你期望JSON对象的整数。

我怀疑它可能是这两行之一,可能是使用错误的jParser方法,也可能是使用错误的getJSONArray()参数。

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

我找到了another question,它显示了从API获取JSON对象的略有不同的方法。

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

免责声明:我实际上并不了解Java,这解释了缺乏细节。在任何情况下,将调试器应用于您的代码,找到问题。

编辑:看到你的PHP代码也有问题......

首先,你 需要停止使用旧的mysql_*()功能,并且必须阅读网络安全性。特别是XSS,SQL注入,输入验证和相关主题。你的代码非常不安全。

我对您的代码进行了一些更改,并添加了评论以突出显示我已完成的工作以及原因。

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);

对于下一个问题,我建议您确切地解释错误,错误原因以及您希望从中获得的错误。因此,我们不必浪费时间回答错误的问题......