Android的数据提取从数据库无法正常工作

Android的数据提取从数据库无法正常工作

本文介绍了Android的数据提取从数据库无法正常工作(PHP + JSON + MYSQL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我知道这个问题已经张贴在堆栈溢出很多次,但我已经尝试了所有的解决方案并没有什么工作适合我。

我想显示列表视图数据。数据存储在JSON格式,并同时获取数据好像Android是不读书的JSON阵列,因此数据在列表视图来了,它仍然是空的。

Java的文件:

 公共类ReadResult扩展ListActivity {
私人ProgressDialog pDialog;
JSONParser jParser =新JSONParser();ArrayList的<&HashMap的LT;字符串,字符串>> ResultFetch;
私人静态字符串url_readResult =htt​​p://10.0.2.2/Result-Viewer/php/ReadData.php;私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_SCORE =得分;
私有静态最后弦乐TAG_SEMESTER =学期;
私有静态最后弦乐TAG_PRODUCTS =产品;
JSONArray产品= NULL;
ListView控件列表;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.read_result);
    名单=(ListView控件)getListView();
    ResultFetch =新的ArrayList<&HashMap的LT;字符串,字符串>>();
    新LoadResult()执行();
}类LoadResult扩展的AsyncTask<字符串,字符串,字符串> {
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(ReadResult.this);
        pDialog.setMessage(加载结果,请稍候...);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(假);
        pDialog.show();
    }    @覆盖
    保护字符串doInBackground(字符串... PARAMS){
        // TODO自动生成方法存根        清单<&的NameValuePair GT;参数=新的ArrayList<&的NameValuePair GT;();        JSONObject的JSON = jParser.makeHtt prequest(url_readResult,GET,
                参数);
        Log.d(结果:,json.toString());
        尝试{
            INT成功= json.getInt(TAG_SUCCESS);
            如果(成功== 1){
                的JSONObject对象=新的JSONObject(json.toString());
                产品= object.getJSONArray(TAG_PRODUCTS);                的for(int i = 0; I< products.length();我++){
                    JSONObject的C = products.getJSONObject(I)
                    字符串学期= c.getString(TAG_SEMESTER);
                    字符串分数= c.getString(TAG_SCORE);
                    HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                    map.put(TAG_SEMESTER,学期);
                    map.put(TAG_SCORE,分数);
                    ResultFetch.add(地图);
                }
            }其他{
                 吐司面包= Toast.makeText(getApplicationContext()
                 未找到任何结果,Toast.LENGTH_SHORT);
                 toast.show();
            }
        }赶上(JSONException E){
            e.printStackTrace();
        }        返回null;
    }    保护无效onPostExecute(字符串FILE_URL){
        pDialog.dismiss();
        runOnUiThread(新的Runnable(){
            公共无效的run(){                ListAdapter适配器=新SimpleAdapter(ReadResult.this,
                        ResultFetch,R.layout.list_item,新的String [] {
                                TAG_SEMESTER,TAG_SCORE},新的INT [] {
                                R.id.semester,R.id.score});                list.setAdapter(适配器);            }
        });    }}

}

php文件:

 < PHP
在session_start();
$ CID = $ _SESSION [CID];
$ RNO = $ _SESSION [RNO];
$响应=阵列();康涅狄格州$ =新PDO('MySQL的:主机=本地主机,数据库名=结果','根','');
$结果= $ conn->查询(SELECT * FROM $ CID,其中RegistrationNumber ='$ RNO');如果($ result->行数()大于0)
{
$响应[产品] =阵列();
的foreach($结果作为$行)
{
$产品[学期] = $行[学期];
$产品[分数] = $行[得分];
$响应[成功] = 1;
array_push($响应[产品],$产品);
回声json_en code($响应);
}
}
其他
{
$响应[成功] = 0;
$响应[消息] =没有找到记录;
回声json_en code($响应);
}?>

我已经通过在登录页面通过CID,RNO和密码,以下是运行数据读取页面生成的JSON输出。

JSON输出:

  {产品:[{学期:0,分数:0}],成功:1}


解决方案

在回答Sarthak加尔格评论我在这里转换为使用GSON一个Java对象的String响应张贴的例子。

我个人采取不同的方式来拨打电话到您的Web服务,而不是你,但是这是本次讨论的范围之内,所以我只想说我会做什么给您现有的code样品。

从code样品下面一行将赋予您可以很容易地转换为String的JSON对象。

  JSONObject的JSON = jParser.makeHtt prequest(url_readResult,GET,参数);
字符串的myString = json.toString();

什么GSON确实为大家解析JSON和提取你需要它的各部分的繁琐的工作是。要了解GSON的全部功能,你需要做一些谷歌搜索,我给你这里的样本只有一件事,你可以用它做。

这是什么样的作用是创建一个新的GSON实例,然后使用该实例的JSON字符串到一个POJO(普通Java对象)进行转换。想想YourPojo类,你给GSON才能使用告诉它incloming JSON将是什么样子,你想要什么样的结果对象看起来像一个模板。

  GSON GSON =新GSON();
YourPojo POJO = gson.fromJson(MyString的,YourPojo.class);

您要在这里做的唯一的额外工作是创建YourPojo类,幸好有工具,有可以提供帮助的,例如

这些工具将带你为它提供一个JSON样本并生成一个POJO类或类为您服务。所有你需要做的是提供类名。

如果你已经实现这个成功,你就可以调用像 pojo.getProducts方法() pojo.getSuccess()您的POJO对象。

Although I know that this question has already been posted on stack overflow many times, but I have tried all solutions and nothing worked for me.

I am trying to display data in List View. Data is stored in the json format and while fetching data it seems like android is not reading the JSON Array and hence data is not coming up in List View and it remains empty.

Java file:

public class ReadResult extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> ResultFetch;
private static String url_readResult = "http://10.0.2.2/Result-Viewer/php/ReadData.php";

private static final String TAG_SUCCESS = "success";
private static final String TAG_SCORE = "Score";
private static final String TAG_SEMESTER = "Semester";
private static final String TAG_PRODUCTS = "products";
JSONArray products = null;
ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.read_result);
    list = (ListView) getListView();
    ResultFetch = new ArrayList<HashMap<String, String>>();
    new LoadResult().execute();
}

class LoadResult extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ReadResult.this);
        pDialog.setMessage("Loading Result. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        List<NameValuePair> param = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url_readResult, "GET",
                param);


        Log.d("Result: ", json.toString());
        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                JSONObject object = new JSONObject(json.toString());
                products = object.getJSONArray(TAG_PRODUCTS);

                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);
                    String Semester = c.getString(TAG_SEMESTER);
                    String Score = c.getString(TAG_SCORE);
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_SEMESTER, Semester);
                    map.put(TAG_SCORE, Score);
                    ResultFetch.add(map);
                }
            } else {
                 Toast toast = Toast.makeText(getApplicationContext(),
                 "No Result Found", Toast.LENGTH_SHORT);
                 toast.show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {

                ListAdapter adapter = new SimpleAdapter(ReadResult.this,
                        ResultFetch, R.layout.list_item, new String[] {
                                TAG_SEMESTER, TAG_SCORE }, new int[] {
                                R.id.semester, R.id.score });

                list.setAdapter(adapter);

            }
        });

    }

}

}

php file :

<?php
session_start();
$cid = $_SESSION["cid"];
$rno = $_SESSION["rno"];
$response = array();

$conn=new PDO('mysql:host=localhost;dbname=result','root' ,'');
$result=$conn->query("Select * from $cid where RegistrationNumber =     '$rno'");

if($result->rowcount()>0)
{
$response["products"] = array();
foreach($result as $row)
{
$product["Semester"] = $row["Semester"];
$product["Score"] = $row["Score"];
$response["success"] = 1;
array_push($response["products"], $product);
echo json_encode($response);
}
}
else
{
$response["success"] = 0;
$response["message"] = "No record found.";
echo json_encode($response);
}

?>

I have passed the cid,rno and password through sign in page and the following is the json output generated by running read data page.

json output :

{"products":[{"Semester":"0","Score":"0"}],"success":1}
解决方案

In reply to a comment from Sarthak Garg I'm posting an example here of converting a String response to a Java object using Gson.

I'd personally take a different approach to making a call to your web service than you are but that's outside the scope of this discussion so I'll just say what I would do given your existing code sample.

The following line from your code sample gives you a json object which can easily be converted to a String.

JSONObject json = jParser.makeHttpRequest(url_readResult, "GET",param);
String myString = json.toString();

What Gson does for you is all of the tedious work of parsing the json and extracting the various parts you need from it. To understand the full capabilities of Gson you'll need to do some Googling, the sample I give you here is just one thing you can do with it.

What this sample does is creates a new Gson instance and then uses that instance to convert your json String to a POJO (Plain Old Java Object). Think of the YourPojo class as a template which you give to Gson to use in order to tell it what the incloming json will look like and what you'd like the resulting object to look like.

Gson gson = new Gson();
YourPojo pojo = gson.fromJson(myString, YourPojo.class);

The only extra work you have to do here is create the YourPojo class and thankfully there are tools out there which can help with that, e.g. this one

These tools will take a json sample you provide it with and generate a Pojo class or classes for you. All you need do is supply the class name.

If you've implemented this successfully you'll be able to call methods like pojo.getProducts() and pojo.getSuccess() on your pojo object.

这篇关于Android的数据提取从数据库无法正常工作(PHP + JSON + MYSQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 22:06