通过发送一些数据来获取Jsonarray作为Android Volley的响应

时间:2018-09-29 03:14:57

标签: android mysql json android-volley

有人可以告诉我....如何通过android凌空库获取jsonarray作为响应...我使用了称为 jsonArrayRequest 的方法,但是有一件事......我想获取通过向php脚本发送一些数据来实现jsonArray响应.....我的php脚本包含三个变量...并且我将从Android应用程序传递这三个变量....然后我的php脚本生成基于这三个变量的jsonarray响应值....我使用getParams方法将数据发送到php脚本...但是当我需要jsonArray响应时,Android永远不会达到getParams方法.....但是当我使用stringRequest时...它会正常工作……但是我想要jsonArray响应而不是stringRequest。...

有人可以帮我怎么做吗? 预先感谢

    package com.example.shreeram.dreamapp;

    import android.content.Intent;
    import android.graphics.Typeface;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;
    import android.widget.TextView;

    import com.android.volley.AuthFailureError;
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonArrayRequest;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;

    public class QuestionActivity extends AppCompatActivity {


        // declare all views...
        TextView tv1,tv2,tv3,tv4,tv5;
        Spinner spinner;


        //php script url.....
        String server_url = "http://192.168.212.2/question.php";


        ArrayList<String> question;
        ArrayList<String> option1;
        ArrayList<String> option2;
        ArrayList<String> option3;
        ArrayList<String> option4;
        ArrayList<Integer> correct;
        ArrayList<Integer> q_id;
        ArrayList<Integer> id;



        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_question);


            //receive data from previous activity....data is .....value of click and listclick..
            Intent in = getIntent();
            Bundle b = in.getExtras();
          final Integer click =  b.getInt("click");
           final Integer listclick =  b.getInt("listclick");


            //initilize all views...
            tv1 = (TextView) findViewById(R.id.textView_question);
            tv2 = (TextView) findViewById(R.id.textViewop1);
            tv3 = (TextView) findViewById(R.id.textViewop2);
            tv4 = (TextView) findViewById(R.id.textViewop3);
            tv5 = (TextView) findViewById(R.id.textViewop4);
            spinner = (Spinner) findViewById(R.id.spinner);


            //Initialize all array list....here data will come from mysql database or jsonarray...
            question = new ArrayList<String>();
            option1 = new ArrayList<String>();
            option2 = new ArrayList<String>();
            option3 = new ArrayList<String>();
            option4 = new ArrayList<String>();
            correct = new ArrayList<Integer>();
            q_id = new ArrayList<Integer>();
            id = new ArrayList<Integer>();


           //Set the different fonts....
            final Typeface myfont1 = Typeface.createFromAsset(getAssets(),"fonts/Vollkorn-

    Regular.ttf");
            final Typeface myfont2 = Typeface.createFromAsset(getAssets(),"fonts/PT_Serif-

    Web-Regular.ttf");






            //This is the request from server....for jsonarray.....

            //This is starting of jsonArrayrequest.......
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest

    (Request.Method.POST, server_url,null,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {

                            //response will come here....

                            int i = 0;
                            int j = response.length();

                            //retrieve all json object from json array...and fill that data to the 

    corresponding arraylist...

                            while (i<j)
                            {
                                try {
                                    JSONObject jsonObject = response.getJSONObject(i);
                                    id.add(jsonObject.getInt("id"));
                                    q_id.add(jsonObject.getInt("q_id"));
                                    question.add(jsonObject.getString("question"));
                                    option1.add(jsonObject.getString("op_1"));
                                    option2.add(jsonObject.getString("op_2"));
                                    option3.add(jsonObject.getString("op_3"));
                                    option4.add(jsonObject.getString("op_4"));
                                    correct.add(jsonObject.getInt("correct"));


                                    i++;




                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            //set fonts to all the views....

                            tv1.setTypeface(myfont1);
                            tv2.setTypeface(myfont1);
                            tv3.setTypeface(myfont1);
                            tv4.setTypeface(myfont1);
                            tv5.setTypeface(myfont1);


                            //set values to the views from arraylist....

                            tv1.setText(question.get(0));
                            tv2.setText(option1.get(0));
                            tv3.setText(option2.get(0));
                            tv4.setText(option3.get(0));
                            tv5.setText(option4.get(0));




                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {


                    //Error will appear here.....
                    tv1.setText("error happened...");

                }
            }){

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String , String> params = new HashMap<String, String>();

                    //put values in the params....
                    params.put("category",""+click);
                    params.put("quizno",""+listclick);

                    //return params....and values to the php script...
                    return params;
                }
            };

            //This is end of jsonArrayrequest.....


            //Create a new request queue.....
        RequestQueue requestQueue = Volley.newRequestQueue(this);


            //Add jsonarray request to the request queue....
       requestQueue.add(jsonArrayRequest);





            //End of oncreate method....
        }




        //End of activity class......
    }   


and this is the php script..... 


<?php

//get values from android app......

$click = $_POST['category'];
$listclick = $_POST['quizno'];


//This is fix....
$language = 1;







$user = "root";
$password = "";
$host = "localhost";


//All database names....

$db_name1 = "history_english";
$db_name2= "history_hindi";
$db_name3= "world_english";
$db_name4= "world_hindi";
$db_name5= "science_english";
$db_name6= "science_hindi";
$db_name7= "sports_english";
$db_name8= "sports_hindi";
$db_name9= "india_english";
$db_name10= "india_hindi";
$db_name11= "computer_english";
$db_name12= "computer_hindi";
$db_name13= "politics_english";
$db_name14= "politics_hindi";
$db_name15= "business_english";
$db_name16= "business_hindi";



//Conditions for fetch jsonarray.....

if($click==1)
{

    //means history database....

    if($language==1)
    {
        //means english database...history_english
        $con1 = mysqli_connect($host,$user,$password,$db_name1);




        //Make sql query......
        $q1 = "select * from t_".$listclick;

        $result1 = mysqli_query($con1,$q1);
        $response = array( );
        $num1 = mysqli_num_rows($result1);


        //Encode data as jsonarray.....

        while($row1 = mysqli_fetch_array($result1))
        {

            array_push($response,array("id"=>$row1["id"],"q_id"=>$row1["q_id"],"question"=>$row1["question"],"op_1"=>$row1["op_1"],
            "op_2"=>$row1["op_2"],"op_3"=>$row1["op_3"],"op_4"=>$row1["op_4"],"correct"=>$row1["correct"]));
        }


        echo json_encode($response);





    }
    else
    {
        //means hindi database.....history_hindi

        $con2 = mysqli_connect($host,$user,$password,$db_name2);


        //Write code later.....

    }










?>

1 个答案:

答案 0 :(得分:0)

根据您提供的信息,使用Volley StringRequest方法不会出现问题-下载功能正常且getParams()方法被正确调用。 知道服务器请求将返回一个字符串!如果您在PHP代码中使用json_encode(),则该字符串将是JSON编码的String。您没有提供PHP代码...因此,我只需要假设PHP方面的所有内容都已正确设置。

您可以简单地使用JSONArray使用该JSON编码的字符串来创建JSONArray array = new JSONArray(response);,其中“响应”是StringRequest的返回值。 因此,只需在下面创建类似downLoadDataVolley()方法的方法,然后根据需要传递网址即可。

private void downLoadDataVolley(String url){
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        //INFO:: The response is of String type, but it is a JSON encoded String..
        // !! as long as the PHP code is indeed returning JSON!!
        // IF the JSON encoded string is structured as a JSONArray then do this...

        JSONArray array = new JSONArray(response);

        for(int i = 0; i < array.length(); i++){
            JSONObject o = array.getJSONObject(i);
            Iterator<String> it = o.keys();
            while(it.hasNext()){
                String key = it.next();
                String value = o.optString(key, "NA");
                Log.e("Try to Parse", "key = " + key + " value = " + value);
            }
            //String s = o.optString("key", "NA");
        }
    }
    }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError e) {
            e.printStackTrace();
         }
    }){
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String , String> params = new HashMap<String, String>();
        //put values in the params....
        params.put("category",""+click);
        params.put("quizno",""+listclick);

        //return params....and values to the php script...
        return params;
    }};
    requestQueue.add(stringRequest);
}

对于您而言,您可以调用downLoadDataVolley(server_url),并且一切正常(就像以前一样),只是这次将字符串转换为JSONArray

您将需要添加代码,而不仅仅是String s = o.optString("key", "NA");,但我强烈建议使用optString()optInt(),因为这些方法使您能够使用可选的后备值。 / p>

如果还有其他问题,请告诉我。


免责声明

我在标准文本编辑器中键入此代码...因此我的代码没有自动更正的优势-可能会有一两个错字。