通过 android volley 通过发送一些数据来获取 Jsonarray 作为响应
get Jsonarray as response by android volley by sending some data
有人能告诉我....如何通过 android volley 库获取 jsonarray 作为响应...我使用了名为 jsonArrayRequest 的方法,但有一个方法事情....我想通过向 php 脚本发送一些数据来获得 jsonArray 响应.....我的 php 脚本包含三个变量...我将从 android app....然后我的 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.....
}
?>
根据您提供的信息,您使用 Volley StringRequest
方法没有问题 -- 下载功能正常并且 getParams()
方法被正确调用。
要知道服务器请求会return一个字符串!如果您在 PHP 代码中使用 json_encode()
,那么该字符串将是 JSON 编码的 String
。您没有提供 PHP 代码...所以我只需要假设 PHP 端的所有内容都已正确设置。
您可以使用 JSON 编码的字符串创建 JSONArray
,只需使用 JSONArray array = new JSONArray(response);
,其中 "response" 是 returned 的值 [=11] =].
因此,只需创建一个方法,如下面的 downLoadDataVolley()
方法,并根据需要传递 url。
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()
,因为这些方法使您能够使用可选的后备值.
如果您还有任何问题,请告诉我。
免责声明
我是在标准文本编辑器中输入的...所以我的代码没有自动更正的优势 -- 可能有一两个错字。
有人能告诉我....如何通过 android volley 库获取 jsonarray 作为响应...我使用了名为 jsonArrayRequest 的方法,但有一个方法事情....我想通过向 php 脚本发送一些数据来获得 jsonArray 响应.....我的 php 脚本包含三个变量...我将从 android app....然后我的 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.....
}
?>
根据您提供的信息,您使用 Volley StringRequest
方法没有问题 -- 下载功能正常并且 getParams()
方法被正确调用。
要知道服务器请求会return一个字符串!如果您在 PHP 代码中使用 json_encode()
,那么该字符串将是 JSON 编码的 String
。您没有提供 PHP 代码...所以我只需要假设 PHP 端的所有内容都已正确设置。
您可以使用 JSON 编码的字符串创建 JSONArray
,只需使用 JSONArray array = new JSONArray(response);
,其中 "response" 是 returned 的值 [=11] =].
因此,只需创建一个方法,如下面的 downLoadDataVolley()
方法,并根据需要传递 url。
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()
,因为这些方法使您能够使用可选的后备值.
如果您还有任何问题,请告诉我。
免责声明
我是在标准文本编辑器中输入的...所以我的代码没有自动更正的优势 -- 可能有一两个错字。