I want to retreive data from json URL and i am face to a problem. I have this from the url :
{
-infos: (2)[
-{
value: "anderson",
-pictures: (2)[
-{
picone: "text_pic",
url: http://www.example.com
},
-{
picone: "text_pic2",
url: http://www.example.com
}
]
},
-{
value: "bryan",
-pictures: (2)[
-{
picone: "text_pic3",
url: http://www.example.com
},
-{
picone: "text_pic4",
url: http://www.example.com
}
]
},....
I have also my listview row :
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/pic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"/>
And here the volley code i used te retrieve data:
....
private List<News_Item> nNews = new ArrayList<>();
......
CustomRequest lnews = new CustomRequest(Request.Method.POST, URL, param, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray vals= response.getJSONArray("infos");
for (int i = 0; i < vals.length(); i++) {
JSONObject dats= vals.getJSONObject(i);
News_Item item = new News_Item ();
item.setmTitle(dats.getString("value"));
JSONArray overinfo = dats.getJSONArray("pictures");
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo .getJSONObject(j);
item.setmImage(links.getString("picone"));
item.setmUrl(links.getString("url"));
}
nNews.add(item);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
....
This code return only one rows (the last row) for pictures array. something like this
row 1 => anderson / text_pic2 / http://www.example.com
row 2 = bryan / text_pic4 / http://www.example.com
So please help
UPDATE
This News_Item.class
class News_Item {
String mTitle;
public News_Item (){
}
List<Picture> pictureList;
public News_Item (String mTitle, <Picture> pictureList){
this.mTitle= mTitle;
this.pictureList= pictureList;
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
class Picture {
String url;
String picone;
public Picture (String url, String picone) {
this.url= url;
this.picone= picone;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPicone() {
return picone;
}
public void setPicone(String picone) {
this.picone = picone;
}
}
}
How get pictures datas.
Like in News_Item you did
News_Item item = new News_Item ();
item.setmTitle(dats.getString("value"));
And at last added to list: nNews.add(item);
you need to add picture items too,
So inside this loop, you are adding in for loop with same object i.e. item so its overwriting those variables
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo.getJSONObject(j);
item.setmImage(links.getString("picone"));
item.setmUrl(links.getString("url"));
-- Here add in collection of links
}
UPDATE: Here this will guide what you will need to do (I wrote directly on stackoverflow editor so might have error)
News_Item item = new News_Item();
item.setmTitle(dats.getString("value"));
List <Picture> pictures = new ArrayList<>();
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo.getJSONObject(j);
Picture picture = new Picture(links.getString("picone"), links.getString("url"));
pictures.add(picture);
}
item.setmPictureList(pictures); // Create this or use constructor itself
nNews.add(item);
Try to change News_Item to have a list of Picture class.
Your code has a problem. You are overwriting new image in every looping.
JSONArray overinfo = dats.getJSONArray("pictures");
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo .getJSONObject(j);
item.setmImage(links.getString("picone"));
item.setmUrl(links.getString("url"));
}
By creating new Picture class, you can add Picture object for picone and url value from pictures data.
class News_Item {
List<Picture> pictureList;
...
class Picture {
String url;
String picone;
...
}
}
Google has developed Gson, a library which lets you convert a JSON Strings to a Objects in just one line:
Gson on GitHub
Given that these are your classes:
public class InfoResponse {
List<Info> infos;
public InfoResponse(List<Info> infos) {
this.infos = infos;
}
}
public class Info {
String value;
List<Picture> pictures;
public Info(String value, List<Picture> pictures) {
this.value = value;
this.pictures = pictures;
}
}
public class Picture {
String picone;
String url;
public Picture(String picone, String url) {
this.picone = picone;
this.url = url;
}
}
you just have to call
InfoResponse response = new Gson().fromJson(jsonString, InfoResponse.class);
This will do everything for you.
Related
I am a new application developer I try intent or pass data through on click image in (slider Layout) from first activity to the second activity. I try to intent (name) to second activity.
I now have a different set of images now, each one having its own name.if user clicking on the first image will intent or pass data of first image only.Also if user clicking on the five image will intent data of five image only.Like that what I want to do.
Please if anyone knows the answer help me.
import com.smarteist.autoimageslider.SliderLayout;
import com.smarteist.autoimageslider.SliderView;
public class SlidShowMain extends AppCompatActivity {
SliderLayout sliderLayout;
private List<SlidShowListData> list_dataList;
private JsonArrayRequest request;
private RequestQueue requestQueue;
private static final String HI ="http://=========/S.php";
TextView textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_show_new);
sliderLayout = (SliderLayout) findViewById(R.id.imageSlider);
sliderLayout.setIndicatorAnimation(SliderLayout.Animations.WORM);
list_dataList=new ArrayList<>();
sliderLayout.setScrollTimeInSec(1);
textView5 =(TextView)findViewById(R.id.textView5);
SliderView sliderView = new SliderView(this);
setSliderViews();
}
private void setSliderViews() {
request = new JsonArrayRequest(HI, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
SlidShowListData listData = new SlidShowListData listData = new SlidShowListData(jsonObject.getString("imageurl"),jsonObject.getString("name"),jsonObject.getString("id"));
String name = jsonObject.getString("id");
textView5.append(name + ", " +"\n\n");
list_dataList.add(listData);
} catch (JSONException e) {
e.printStackTrace();
}
}
setupdata(list_dataList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void setupdata(List<SlidShowListData> list_dataList) {
for (int i = 0; i <= 4; i++) {
final SlidShowListData ld = list_dataList.get(i);
SliderView view = new SliderView(getBaseContext());
view.setImageUrl(ld.getImageurl());
view.setImageUrl(ld.getname());
view.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
final int finalI = i;
sliderLayout.addSliderView(view);
view.setOnSliderClickListener(new SliderView.OnSliderClickListener() {
#Override
public void onSliderClick(SliderView sliderView) {
Toast.makeText(SlidShowMain.this, "" + (sliderLayout.getCurrentPagePosition() + 1), Toast.LENGTH_SHORT).show();
}
});
}
}
}
public class SlidShowListData {
private String imageurl;
private String name;
private String id;
public SlidShowListData(String imageurl,String name,String id) {
this.imageurl = imageurl;
this.name = name;
this.id = id;
}
public String getImageurl() {
return imageurl;
}
public String getname() {
return name;
}
public String getId() {
return id;
}
}
implementation 'com.github.smarteist:autoimageslider:1.1.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
<?php
$con=mysqli_connect("localhost","=====","=====","show");
$sql="SELECT * FROM slhow";
$result=mysqli_query($con,$sql);
$data=array();
while($row=mysqli_fetch_assoc($result)){
$data[]=$row;
}
header('Content-Type:Application/json');
echo json_encode($data);
?>
I have tried to write it as follows:
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,HomeActivity.class);
intent.putExtra("id",======.=======()); // here problem
context.startActivity(intent);
I don't know what I should write or how on the second line into (====) to send an ID.must send the Id of image that user just clicks, not all ids of images
Anyone know solution , please help me
Use this code for sending data from FirstActivity:
val intent = Intent(this#FirstActivity, SecondActivity::class.java)
intent.putExtra("imagename", imageid)
startActivity(intent)
And this for delivering date in SecondActivity:
var imageid = intent.getStringExtra("imagename")
The title might seem familiar, but the problem isn't. I've referred many posts/articles, and finally posting my question.
I receive data from JSON similar to this, and from "Home" fragment I save data to a getter setter class "StudentDetails", and then access it from another fragment "StudentFees".
PROBLEM: The last object of the inner array gets printed the number of times the outer array runs.
Below is my "Home" Fragment
public class Home extends Fragment {
private ArrayList<StudentDetails> arrayListHome;
private ArrayList<StudentDetails> arrayListTransaction;
private StudentDetails studentDetails;
private StudentDetails studentDetails1;
JSONArray jsonArrayHome = jsonObjectHome.getJSONArray("responseData");
arrayListHome = new ArrayList<StudentDetails>();
// First array
for (int a = 0; a < jsonArrayHome.length(); a++) {
JSONObject jsonObjectStudent = jsonArrayHome.getJSONObject(a);
studentDetails = new StudentDetails();
// Set student ID
if (!jsonObjectStudent.isNull("student_id")) {
studentDetails.setStudentId(jsonObjectStudent.getString("student_id"));
}
JSONArray jsonArrayTransaction = jsonObjectStudent.getJSONArray("transaction");
arrayListTransaction = new ArrayList<StudentDetails>();
// Second array
for (int j = 0; j < jsonArrayTransaction.length(); j++) {
JSONObject jsonObjectTransaction = jsonArrayTransaction.getJSONObject(j);
studentDetails1 = new StudentDetails();
// Set receipt no.
if (!jsonObjectTransaction.isNull("receipt_no")) {
studentDetails1.setReceiptNo(jsonObjectTransaction.getString("receipt_no"));
}
arrayListTransaction.add(studentDetails1);
Log.d("At Home receipt no.", arrayListTransaction.get(j).getReceiptNo()+"");
}
studentDetails1.setArrayListTransaction(arrayListTransaction);
arrayListHome.add(studentDetails);
Log.d("At Home student id", arrayListHome.get(a).getStudentId());
}
studentDetails.setArray(arrayListHome);
}
Below is "StudentDetails" class
public class StudentDetails {
private static ArrayList<StudentDetails> arrayListDetails = null;
private static ArrayList<StudentDetails> arrayListTransaction = null;
private String studentId = null;
private String receiptNo = null;
public void setArray(ArrayList<StudentDetails> arrayList) {
arrayListDetails = arrayList;
}
public ArrayList<StudentDetails> getArray() {
return arrayListDetails;
}
public void setStudentId(String sId) {
studentId = sId;
}
public String getStudentId() {
return studentId;
}
public void setArrayTransaction(ArrayList<StudentDetails> transaction){
arrayListTransaction = transaction;
}
public ArrayList<StudentDetails> getArrayTransaction (){
return arrayListTransaction;
}
public void setReceiptNo(String sReceiptNo) {
receiptNo = sReceiptNo;
}
public String getReceiptNo() {
return receiptNo;
}
Below is "StudentFees" Fragment
public class StudentFees extends Fragment {
StudentDetails studentDetails = new StudentDetails();
final ArrayList<StudentDetails> arrayListFees = studentDetails.getArray();
// First Array
for (int k = 0; k < arrayListFees.size(); k++) {
final TextView textViewId = new TextView(getActivity());
textViewId.setId(View.generateViewId());
Log.d("At Fees student id", arrayListFees.get(k).getStudentId());
textViewId.setText(arrayListFees.get(k).getStudentId());
StudentDetails studentDetails1 = new StudentDetails();
ArrayList<StudentDetails> arrayListTransaction = studentDetails1.getArrayTransaction();
TextView textViewReceiptNo = null;
// Second Array
for (int l = 0; l < arrayListTransaction.size() /*studentDetails.getArrayTransaction().size()*/; l++) {
// StudentDetails studentDetails1 = new StudentDetails();
// ArrayList<StudentDetails> arrayListTransaction = studentDetails1.getArrayTransaction();
textViewReceiptNo = new TextView(getActivity());
textViewReceiptNo.setId(View.generateViewId());
Log.d("At Fees receipt no.", arrayListTransaction.get(l).getReceiptNo());
textViewReceiptNo.setText(arrayListTransaction.get(l).getReceiptNo());
}
}
}
Data insertion log # Home fragment:
D/At Home receipt no.: R/100/2017/04/2449
D/At Home receipt no.: R/100/2017/04/2450
D/At Home student id: 201510353
D/At Home receipt no.: R/100/2017/04/2536
D/At Home receipt no.: R/100/2017/04/2537
D/At Home receipt no.: R/100/2017/11/3024
D/At Home student id: 201610113
Data retrieval # StudentFees fragment
D/At Fees student id: 201510353
D/At Fees receipt no.: R/100/2017/04/2536
D/At Fees receipt no.: R/100/2017/04/2537
D/At Fees receipt no.: R/100/2017/11/3024
D/At Fees student id: 201610113
D/At Fees receipt no.: R/100/2017/04/2536
D/At Fees receipt no.: R/100/2017/04/2537
D/At Fees receipt no.: R/100/2017/11/3024
Desired output is smilar to data inserted.
NOTE: I've referred this, but still used "static" ArrayList variable on purpose, as I need to access this ArrayList from other fragments.
JSON Data:
{
"responseCode": "200",
"status": "true",
"responseData": [{
"student_id": "201510353",
"transaction": [{
"receipt_no": "R\/100\/2017\/04\/2449"
}, {
"receipt_no": "R\/100\/2017\/04\/2450"
}]
}, {
"student_id": "201610113",
"transaction": [{
"receipt_no": "R\/100\/2017\/04\/2536"
}, {
"receipt_no": "R\/100\/2017\/04\/2537"
}, {
"receipt_no": "R\/100\/2017\/11\/3024"
}]
}]
}
Im trying to find an easy way to parse JSON data that are in an array. Ive been able to do this before with pure JSON Objects and OkHttp.
What I plan to do is make a simple recycler view that each row will contain the data from the JSON Array.
Note: there will be keys in each array that may or may not have a "viewers" parameter. If it does not exist I plan to make a default value of 0.
JSON example:
{
status_code: 200,
status_text: "OK",
errors: [ ],
data: {
items: [
{
stream: "channel1",
status: 1,
channel: 527,
provider: "akamai"
},
{
stream: "channel2",
status: 2,
channel: 565,
provider: "akamai",
viewers: 3
},
I have a class that stores the data (not sure if needed in the case of a JSON Array) called CurrentStreams.java
package com.example.concurrent;
public class CurrentStreams {
private String mStream;
private int mStatus;
private int mChannel;
private String mProvider;
private int mViewers;
public String getStream() {
return mStream;
}
public void setStream(String stream) {
mStream = stream;
}
public int getStatus() {
return mStatus;
}
public void setStatus(int status) {
mStatus = status;
}
public int getChannel() {
return mChannel;
}
public void setChannel(int channel) {
mChannel = channel;
}
public String getProvider() {
return mProvider;
}
public void setProvider(String provider) {
mProvider = provider;
}
public int getViewers() {
return mViewers;
}
public void setViewers(int viewers) {
mViewers = viewers;
}
}
In my MainActivity I initiate a new OkHttpClient and create the request and pass a method called getCurrentDetails(jsonData) which contains the following
private CurrentStreams getCurrentDetails(String jsonData) throws JSONException {
//New JSON Array
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++){
JSONObject items = jsonArray.getJSONObject(i);
String streamName = items.getString("stream_name");
int status = items.getInt("status");
int channelId = items.getInt("channel_id");
String cdn = items.getString("cdn");
int viewers = items.getInt("viewers");
}
}
I assume im kinda lost at how to properly handle the JSON Array and save the data to then later populate the view with rows of data. Any help is greatly appreciated in advanced.
I would suggest to use gson.
You maybe want to take a look at this answer or this Tutorial
I know that there are several similar questions already answered, but because the fact that I'm very new to Android development, I couldn't figure out how to solve this on my own. The question is pretty self-explanatory. I'm fetching data from the database over HTTP request and want to adapt that data into a listview. I'm using Volley for my HTTP requests and underneath is my onResponse -method.
Everything else works perfectly, I just haven't found a way to adapt that data into a listview.
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
// If we are getting success from server
try {
JSONObject jObject = new JSONObject(response);
int count = jObject.getInt("count");
if(count == 0) {
noEventsTextView.setText(jObject.getString("msg").toString());
noEventsTextView.setGravity(Gravity.CENTER);
noEventsImageView.setVisibility(View.VISIBLE);
} else {
JSONArray childArray = jObject.getJSONArray("lectures");
for(int i = 0; i < childArray.length(); i++) {
JSONObject finalObject = childArray.getJSONObject(i);
// TODO Adapt data to listView
}
}
} catch(JSONException e) {
e.printStackTrace();
}
}
}
And here's an example of JSON I get back from the server:
{
count: 2,
msg: "",
lectures: [
{
id: "1",
starting_at: "2015-11-30 13:00:00",
ending_at: "2015-11-30 15:00:00",
user_id: "1",
course: "Course #1",
user_name: "John Doe"
},
{
id: "2",
starting_at: "2015-11-30 13:00:00",
ending_at: "2015-11-30 15:00:00",
user_id: "1",
course: "Course #2",
user_name: "John Doe"
}
]
}
Create a class of each key value pairs of Json and the map your json to that class using Jackson and the add generic list of that class to your List Adapter .
Like
Custom Class{
String id;
String starting_at;
String ending_at;
String user_id;
String course ;
String username;
}
Map your response through Jackson to ArrayList
and then
ListAdapter(ArrayList)
https://w2davids.wordpress.com/android-json-parsing-made-easy-using-jackson/
and you are ready to go.......you can use gson also but jackson is a bit faster so you can go for anyone according to ur need......
hope it helps.
create array Variables for each key value pairs of Json.
and pass all those variable to a listview.
new Listadapter(this,id[],starting_at[],ending_at[],user_id[],course[],username[]);
or There is a concept called Gson.
which will allow you to write data to Serializable class without using array.
And after assigning data to these class you can pass the Serializable class to adapter and used it inside adapter getView method.
There is a simple tutorial on this which I wrote to assign data to serializable class, think it will give you an idea.
hope it helps.
You can have a POJO consisting of all the keys a lecture has.
DataPOJO.java
public class DataPOJO {
private int id;
private String starting_at;
private String ending_at;
private String user_id;
private String course;
private String user_name;
}
Inside your onResponse:
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
// If we are getting success from server
try {
JSONObject jObject = new JSONObject(response);
int count = jObject.getInt("count");
if(count == 0) {
noEventsTextView.setText(jObject.getString("msg").toString());
noEventsTextView.setGravity(Gravity.CENTER);
noEventsImageView.setVisibility(View.VISIBLE);
} else {
JSONArray childArray = jObject.getJSONArray("lectures");
ArrayList<DataPOJO> datas = new ArrayList<DataPOJO>();
for(int i = 0; i < childArray.length(); i++) {
JSONObject finalObject = childArray.getJSONObject(i);
DataPOJO data = new DataPOJO;
data.id = finalObject.getInt("id");
data.starting_at = finalObject.getString("starting_at");
//so on
//add data to arraylist......
datas.add(data);
}
//set adapter of your listview here, you have to have an instance of your list view
listView.setAdapter(new MyAdapter(datas, context));
}
} catch(JSONException e) {
e.printStackTrace();
}
}
}
MyAdapter.java
public class MyAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<DataPOJO> listItem;
public MyAdapter(Context mContext, ArrayList<DataPOJO> listItem) {
this.mContext = mContext;
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return listItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_items, null);
((TextView) convertView.findViewById(R.id.name)).setText(listItem.get(position).user_name);
return convertView;
}
}
list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#000"
android:textSize="18sp"/>
</RelativeLayout>
This is kind of weird issue i am having,
I am getting response from web service in this manner
"course": [
{
"id": 1,
"cou_name": "Engineering",
"L1": [
{
"id": 3,
"cou_name": "B.Tech",
},
{
"id": 4,
"cou_name": "M.Tech",
}]
},
{ ...... } ]
I have created POJO class to handle this response in this way
public class FilterCourseDetail {
public static final String ID = "id";
public static final String COU_NAME = "cou_name";
public static final String LEVEL_ONE = "L1";
public int id;
public String courseName;
public ArrayList<FilterCourseDetail> mLevelOneArrayList = new ArrayList<>();
public FilterCourseDetail(JSONObject object) {
setId(object.optInt(ID));
setCourseName(object.optString(COU_NAME));
try {
JSONArray jsonLevelOneArray = object.optJSONArray(LEVEL_ONE);
if(jsonLevelOneArray != null){
for (int i = 0; i < jsonLevelOneArray.length(); i++) {
mLevelOneArrayList.add(new FilterCourseDetail(jsonLevelOneArray.getJSONObject(i)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Normal getter setter
public ArrayList<FilterCourseDetail> getLevelOneArray() {
return this.mLevelOneArrayList;
}
}
And i am storing it in following manner
private ArrayList<FilterCourseDetail> mFilterCourseList = new ArrayList<>();
JSONArray jsonSearchFilterArray = jsonSearchFilterObject.getJSONArray("course");
for (int i = 0; i < jsonSearchFilterArray.length(); i++) {
mFilterCourseList.add(new FilterCourseDetail(jsonSearchFilterArray.getJSONObject(i)));
}
Retrieving it :
private ArrayList<FilterCourseDetail> mFilterLevelOneArray = new ArrayList<>();
mFilterLevelOneArray = mFilterCourseList.get(position).getLevelOneArray();
Problem :
When i check the size of mFilterCourseList for first time, it's fine,
but using it again by
mFilterLevelOneArray = mFilterCourseList.get(position).getLevelOneArray();
and checking the size, it returns 0, means it's automatically been cleared.
I don't understand this. also is this the proper way to handle Inner JSONArray ? please help me out when i am wrong