从数据库中获取不工作的Android数据(php + json + mysql)

时间:2021-10-25 07:28:54

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.

虽然我知道这个问题已经在stack overflow上贴了很多次了,但是我已经尝试了所有的解决方案,但是没有一个对我有用。

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.

我尝试在列表视图中显示数据。数据以json格式存储,在获取数据时,android似乎没有读取json数组,因此数据不会出现在列表视图中,并且它仍然是空的。

Java file:

Java文件:

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文件:

<?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.

我已经通过页面中的sign传递了cid、rno和密码,下面是运行read data页面生成的json输出。

json output :

json输出:

{"products":[{"Semester":"0","Score":"0"}],"success":1}

2 个解决方案

#1


0  

I got a comment on your code that might help. The following line is useless

我得到一个关于你的代码的评论,可能会有帮助。下面这行没用

JSONObject object = new JSONObject(json.toString());

as you can just use json as your JSONObject instead of creating a new one.

正如您可以使用json作为您的JSONObject,而不是创建一个新的JSONObject。

#2


0  

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.

作为对Sarthak Garg评论的回应,我在这里发布了一个使用Gson将字符串响应转换为Java对象的示例。

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.

我个人认为调用web服务的方法与您不同,但这超出了我们的讨论范围,因此我只说一下,对于您现有的代码示例,我要做什么。

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

下面代码示例中的一行给出了一个json对象,可以很容易地转换为字符串。

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.

Gson为您做的是解析json并从中提取所需的各个部分的所有繁琐工作。要理解Gson的全部功能,您需要进行一些google搜索,我在这里提供的示例只是您可以使用它做的一件事。

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实例,然后使用该实例将json字符串转换为POJO(普通的旧Java对象)。可以将YourPojo类视为模板,并将其提供给Gson,以便告诉它倾斜的json是什么样子,以及您希望得到的对象是什么样子。

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

在这里,您需要做的惟一额外工作是创建YourPojo类,幸运的是,有一些工具可以帮助您创建这个类,例如这个

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.

这些工具将获取您提供的json示例,并为您生成Pojo类或类。您所需要做的就是提供类名。

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

如果您成功实现了这个功能,那么您将能够在pojo对象上调用pojo. getproducts()和pojo. getsuccess()等方法。

#1


0  

I got a comment on your code that might help. The following line is useless

我得到一个关于你的代码的评论,可能会有帮助。下面这行没用

JSONObject object = new JSONObject(json.toString());

as you can just use json as your JSONObject instead of creating a new one.

正如您可以使用json作为您的JSONObject,而不是创建一个新的JSONObject。

#2


0  

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.

作为对Sarthak Garg评论的回应,我在这里发布了一个使用Gson将字符串响应转换为Java对象的示例。

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.

我个人认为调用web服务的方法与您不同,但这超出了我们的讨论范围,因此我只说一下,对于您现有的代码示例,我要做什么。

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

下面代码示例中的一行给出了一个json对象,可以很容易地转换为字符串。

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.

Gson为您做的是解析json并从中提取所需的各个部分的所有繁琐工作。要理解Gson的全部功能,您需要进行一些google搜索,我在这里提供的示例只是您可以使用它做的一件事。

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实例,然后使用该实例将json字符串转换为POJO(普通的旧Java对象)。可以将YourPojo类视为模板,并将其提供给Gson,以便告诉它倾斜的json是什么样子,以及您希望得到的对象是什么样子。

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

在这里,您需要做的惟一额外工作是创建YourPojo类,幸运的是,有一些工具可以帮助您创建这个类,例如这个

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.

这些工具将获取您提供的json示例,并为您生成Pojo类或类。您所需要做的就是提供类名。

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

如果您成功实现了这个功能,那么您将能够在pojo对象上调用pojo. getproducts()和pojo. getsuccess()等方法。