How to Parse nested JSON using Volley? - android

MainClass.java
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
private Toolbar mToolbar;
private List<Onwardflights> onwardflights;
private static final String url = "http://tripofareapi.herokuapp.com/flightapi/src=DEL&dest=BOM&depdate=20180420&arrdate=20180422"; // https: url will insert here
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flight_suggestion);
mToolbar = (Toolbar) findViewById(R.id.flight_suggestion_appbar);
Bundle bundle = getIntent().getExtras();
String from = bundle.getString("from");
String to = bundle.getString("to");
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(from + "-" + to);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setTitleTextColor(Color.WHITE);
recyclerView = (RecyclerView) findViewById(R.id.flight_suggestion_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
onwardflights = new ArrayList<>();
getdata();
}
This is what i have done
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait, while we load the data");
progressDialog.show();
//*Could not understand how to parse FARE objects*
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}

Try this.
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait, while we load the data");
progressDialog.show();
//*Could not understand how to parse FARE objects*
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray returnflights = data.getJSONArray("returnflights");
JSONArray onwardflights = data.getJSONArray("onwardflights");
for (int i = 0; i < returnflights.length(); i++) {
JSONObject returnFlightChild = returnflights.getJSONObject(i);
//returnFlights objects
}
for (int i = 0; i < onwardflights.length(); i++) {
JSONObject onwardFlightsChild = onwardflights.getJSONObject(i);
//onwardFlight objects
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}

First check your response format in Json formatter and validator.
Your json response has 2 json object
data
data_length
to get JSONObject form a Json user getJSONObject("key") and to get JSONArray from Json use getJSONArray("key").
As node data is a JSONObject use getJSONObject("key")` to get that.
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray jsArray1 = data.getJSONArray("returnflights");
JSONArray jsArray2 = data.getJSONArray("onwardflights");
for (int i = 0; i < jsArray1.length(); i++) {
JSONObject jo = jsArray1.getJSONObject(i);
}
..................
Check this tutorial to learn how to parse Json

Related

android studio - json to settext

<?php
$con = mysqli_connect("localhost", "database ", "data pass", "database name");
$userID = $_POST["userID"];
$result = mysqli_query($con, "SELECT * FROM USER WHERE userID like '$userID';");
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("userPoint" => $row[4]));
}
echo json_encode(array("response" => $response));
mysqli_close($con);
?>
I'm trying to use this php to send userID data to my database and receive the point of the user and set the data to settext in android studio.
I used two class to obtain data from my database
public class GameRequest extends StringRequest {
final static private String URL = "http://smg6135.cafe24.com/ogi.php";
private Map<String, String> parameters;
public GameRequest(String userID, Response.Listener<String> listener){
super(Method.POST, URL, listener, null);
parameters = new HashMap<>();
parameters.put("userID", userID);
}
#Override
public Map<String, String> getParams(){
return parameters;
}
}
to send request to my php and
public class MainActivity extends AppCompatActivity {
private String userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView idtext = (TextView) findViewById(R.id.userID);
final TextView point = (TextView) findViewById(R.id.point);
Intent intent = getIntent();
userid = intent.getStringExtra("userID");
idtext.setText(userid);
Response.Listener<String> responseLister = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String result = jsonObject.getString("userPoint");
JSONArray arr = new JSONArray(result);
point.setText(arr.toString());
}catch(Exception e){
e.printStackTrace();
}
}
};
GameRequest gameRequest = new GameRequest(userid, responseLister);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(gameRequest);
}
}
to receive the data in Json array and display it by textview. Somehow it doesn't work... can anyone help me with this problem?
You are receiving response in Array Object so use JSONArray instead of JSONObject as follows -
Response.Listener<String> responseLister = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String result = jsonobject.getString("userPoint");
point.setText(result);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
I hope its work for you. Thanks

how can i display google nearbyplace api images response in listview?

I am using json volley to for getting information from google api.I know how to display text in listview but dont know how to display images because they are in string form i really dont know how to convert that string into image and display in listview . here is my code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView lst_1;
Button btn_one;
String url;
ArrayList<CostumAdapter> contactList;
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
contactList = new ArrayList<>();
lst_1 = (ListView) findViewById(R.id.lst_1);
btn_one = (Button) findViewById(R.id.btn_1);
btn_one.setOnClickListener(this);
}
public void Progress() {
progress = new ProgressDialog(this);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setMessage("Loading");
progress.show();
}
private void jsonfunction() {
Progress();
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" +
"location=-33.8670522,151.1957362&" +
"radius=500&" +
"type=restaurant&" +
"key=AIzaSyAG5Fndg4wPzs81FNv5-Ycl7GDlAdqeIaI" +
"&sensor=true";
Log.e("url", url);
final StringRequest stringrequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
try {
JSONObject jsonobj = new JSONObject(response);
JSONArray jsonArray = jsonobj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONArray jsonArray2 = object.getJSONArray("photos");
for (int a = 0; a < jsonArray2.length(); a++) {
JSONObject object2 = jsonArray2.getJSONObject(a);
contactList.add(new CostumAdapter(
jsonArray.getJSONObject(i).getString("name"),
object2.getString("photo_reference")
));
}
}
Log.e("response in a", String.valueOf(contactList));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "error in jason", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
function();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "error in ErrorListener", Toast.LENGTH_LONG).show();
}
});
singalton.getinstance(MainActivity.this).addtorequestque(stringrequest);
}
public void function() {
CustomListAdapter adapter = new CustomListAdapter(getApplicationContext(), R.layout.custumlistview, contactList);
lst_1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
jsonfunction();
}
}

cannot find symbol method getJSONArray(String) Volley

hi everyone i am working on a android project where i have to retrive the data form JSON. here is my link
I am trying to get the data using the below code
public class DisplayUser extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_user);
textViewResult = (TextView) findViewById(R.id.check_data_id); // in this text view i will display the text
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = statics_demo.USER_URL+"7";// this is fixed url where i am getting the data
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayUser.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
JSONObject result;
private void showJSON(String response) {
try {
JSONArray obj = response.getJSONArray("responseMs");
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
String name = jsonObject.getString("name");
System.out.println("luckyyyyyy"+name);
// String type = jsonObject.getString("type");
// retrieve the values like this so on..
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
When i run the code i am getting a erorr saying
"Error:(60, 37) error: cannot find symbol method getJSONArray(String)"
String s = "[]"; JsonParser parser = new JsonParser(); JsonElement tradeElement = parser.parse(s); JsonArray trade = tradeElement.getAsJsonArray();
you need to convert string to jsonarray first

How to create ExpandableListview with json data in Android

can anyone suggest that how to create expandable list-view with Json data, i want to parse json data in my expandable list view, plss suggest how can i create
This is exactly what you looking for,you can parse and display data to ExpandableListview
See this : http://www.tutorialsbuzz.com/2015/02/android-expandable-listview-json-http.html
public class MainActivity extends Activity {
String url = "http://api.tutorialsbuzz.com/cricketworldcup2015/cricket.json";
ProgressDialog PD;
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExpandList = (ExpandableListView) findViewById(R.id.exp_list);
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
makejsonobjreq();
}
private void makejsonobjreq() {
PD.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Group> list = new ArrayList<Group>();
ArrayList<Child> ch_list;
try {
Iterator<String> key = response.keys();
while (key.hasNext()) {
String k = key.next();
Group gru = new Group();
gru.setName(k);
ch_list = new ArrayList<Child>();
JSONArray ja = response.getJSONArray(k);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
Child ch = new Child();
ch.setName(jo.getString("name"));
ch.setImage(jo.getString("flag"));
ch_list.add(ch);
} // for loop end
gru.setItems(ch_list);
list.add(gru);
} // while loop end
ExpAdapter = new ExpandListAdapter(
MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
PD.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD.dismiss();
}
});
MyApplication.getInstance().addToReqQueue(jsonObjReq, "jreq");
}
}

how to parse json object and json array in listview android

I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray

Categories

Resources