I have a web service for search in some videos by name.
It pass me the names and images of the videos.
how should I say which image is for which video?
and how shoud i say it to play
package com.video;
import java.util.List;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import com.uvideo.adapter.VideoSearchAdapter;
import com.uvideo.controller.MasterVideoController;
import com.uvideo.model.VideoSearch;
public class ActivityVideoSearch extends Activity implements OnClickListener {
private VideoSearchAdapter videoSearchAdapter;
private GridView grdVideoList;
private List<VideoSearch> listVideo;
private EditText edtKeySearch;
private Button btnSearch;
// -------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_video_search);
ini();
}
// -------------------------
private void ini() {
grdVideoList = (GridView) findViewById(R.id.grdVideoList);
edtKeySearch = (EditText) findViewById(R.id.edtKeySearch);
btnSearch = (Button) findViewById(R.id.btnSearchVideo);
btnSearch.setOnClickListener(this);
}
// -------------------------
private class SearchVideo extends AsyncTask<String, Void, List<VideoSearch>>{
#Override
protected List<VideoSearch> doInBackground(String... params) {
MasterVideoController masterVideoController = new MasterVideoController();
return masterVideoController.searchVideo(params[0]);
}
#Override
protected void onPostExecute(List<VideoSearch> result) {
super.onPostExecute(result);
listVideo = result;
videoSearchAdapter = new VideoSearchAdapter(getBaseContext(),result);
grdVideoList.setAdapter(videoSearchAdapter);
}
}
// -------------------------
#Override
public void onClick(View v) {
new SearchVideo().execute(edtKeySearch.getText().toString());
}
}
package com.video.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.uvideo.R;
import com.uvideo.model.VideoSearch;
public class VideoSearchAdapter extends ArrayAdapter {
private List<VideoSearch> listVideo;
private Context context;
// ---------------------
public VideoSearchAdapter(Context context,List<VideoSearch> listVideo) {
super(context, R.layout.row_video_item, listVideo);
this .listVideo = listVideo;
this.context = context;
}
// ---------------------
#Override
public int getCount() {
return super.getCount();
}
// ---------------------
#Override
public VideoSearch getItem(int position) {
return ((listVideo!=null ? listVideo.get(position):null));
}
// ---------------------
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view==null){
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_video_item, parent,false);
}
final VideoSearch video=listVideo.get(position);
if(video!=null){
TextView txtMusicName = (TextView) view.findViewById(R.id.txtVideoName);
txtMusicName.setTextSize(16);
txtMusicName.setText(video.getVideoTitle());
// ---------------------
}
return view;
}
// ---------------------
#Override
public long getItemId(int position) {
return position;
}
}
package com.video.controller;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import com.uvideo.model.VideoDetail;
import com.uvideo.model.VideoSearch;
import com.uvideo.tools.parser.XmlParser;
import com.uvideo.tools.webservice.WebServiceConnection;
import com.uvideo.tools.webservice.WebServiceConnection2;
public class MasterVideoController extends WebServiceConnection {
private String result;
private JSONObject jsonObject;
private JSONArray jsonObjectArray;
private final static String SEARCHKEY="SearchKey";
// -------------------------
public MasterVideoController() {
}
// -------------------------
public List<VideoDetail> getVideoList(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
result = super.sendRequest("MasterVideo", params);
return getVideoListJson(result);
}
// -------------------------
private List<VideoDetail> getVideoListJson(String json){
List<VideoDetail> listVideo = new ArrayList<VideoDetail>();
json = new XmlParser().getxml(json);
try{
jsonObject = new JSONObject(json);
listVideo.add(new VideoDetail(jsonObject.optString(VideoDetail.VIDEOTITLE)
, jsonObject.optString(VideoDetail.VIDEOPATH)
, jsonObject.optString(VideoDetail.VIDEOIMAGE)
, jsonObject.optInt(VideoDetail.VIDEOVISIT)
, jsonObject.optString(VideoDetail.CHANNELNAME)
, jsonObject.optString(VideoDetail.USERNAME)
, jsonObject.optString(VideoDetail.USERIMAGE)
, jsonObject.optInt(VideoDetail.USERVIDEOCOUNT)
, jsonObject.optInt(VideoDetail.USERFOLLOWER)));
//}
return listVideo;
}
catch(Exception exp){
}
return null;
}
// -------------------------
public List<VideoSearch> searchVideo(String requestSearchKey){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(SEARCHKEY,requestSearchKey));
result = super.sendRequest("SearchByVideoTitle", params);
return getVideoListSearchJson(result);
}
// -------------------------
private List<VideoSearch> getVideoListSearchJson(String json){
List<VideoSearch> listVideo = new ArrayList<VideoSearch>();
json = new XmlParser().getxml(json);
try{
jsonObjectArray = new JSONArray(json);
for (int i = 0; i < jsonObjectArray.length(); i++) {
jsonObject = (JSONObject) jsonObjectArray.get(i);
listVideo.add(new VideoSearch(jsonObject.optString(VideoSearch.VIDEOTITLE)
, jsonObject.optString(VideoSearch.VIDEOPATH)
, jsonObject.optString(VideoSearch.VIDEOIMAGE)
, jsonObject.optInt(VideoSearch.VIDEOVISIT)
, jsonObject.optString(VideoSearch.USERNAME)));
}
return listVideo;
}
catch(Exception exp){
String a = "";
}
return null;
}
// -------------------------
}
package com.video.model;
public class VideoSearch {
// -------------------------
public final static String VIDEOTITLE="VideoTitle";
public final static String VIDEOPATH="VideoPath";
public final static String VIDEOIMAGE="VideoImage";
public final static String VIDEOVISIT="VideoVisit";
public final static String USERNAME="UserName";
// -------------------------
private String videoTitle ;
private String videoPath ;
private String videoImage ;
private int videoVisit ;
private String username ;
// -------------------------
public VideoSearch(String videoTitle , String videoPath ,String videoImage ,int
videoVisit , String username) {
this.videoTitle = videoTitle;
this.videoPath = videoPath;
this.videoImage = videoImage;
this.videoVisit = videoVisit;
this.username = username;
}
// -------------------------
public VideoSearch() {
}
// -------------------------
public String getVideoTitle(){
return videoTitle;
}
public String getvideoPath(){
return videoPath;
}
public String getVideoImage(){
return videoImage;
}
public int getVideoVisit(){
return videoVisit;
}
public String getUsername(){
return username;
}
// -------------------------
public void setVideoTitle(String videoTitle){
this.videoTitle = videoTitle;
}
public void setvideoPath(String videoPath){
this.videoPath = videoPath;
}
public void setVideoImage(String videoImage){
this.videoImage = videoImage;
}
public void setVideoVisit(int videoVisit){
this.videoVisit = videoVisit;
}
public void setUsername(String username){
this.username = username;
}
// -------------------------
}
Firstly, your not clearly stated.
If you are using web service, then you should send the items by coupling them in web service.
Like in JSON
{
video[{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}
]
}
here you see you receiving in couple
Related
// I have a Custom ListView in android and have set a adapter . My problem is //that the list view does not show anything, regardless of the adapter, note I'm //retrieving information from a Backendless services . please help
// adapter Code
package za.ac.cut.afinal;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by User on 2017/09/12.
*/
public class StudentAdapter extends ArrayAdapter<Student_Class> {
private final Context context;
private final List<Student_Class> values;
TextView tvName, tvSurname,tvGender,tvRace;
public StudentAdapter(Context context, List<Student_Class> list)
{
super(context,R.layout.custom_student_row_layout);
this.context = context;
this.values = list;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Nullable
#Override
public Student_Class getItem(int position) {
return values.get(position);
}
#Override
public int getCount() {
return values == null ? 0 : values.size();
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.custom_student_row_layout,parent,false);
tvName = (TextView) rowView.findViewById(R.id.customSNmae);
tvSurname = (TextView) rowView.findViewById(R.id.tv_customSSurname);
tvGender = (TextView) rowView.findViewById(R.id.customSGender);
tvRace = (TextView) rowView.findViewById(R.id.customSRace);
Toast.makeText(context, "help" + values.get(position).getL_fname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help2" + values.get(position).getL_lname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help3" + values.get(position).getL_gender(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help4" + values.get(position).getL_race(), Toast.LENGTH_SHORT).show();
tvName.setText(values.get(position).getL_fname());
tvSurname.setText(values.get(position).getL_lname());
tvGender.setText(values.get(position).getL_gender());
tvRace.setText(values.get(position).getL_race());
return rowView ;
}
}
// class Listview
package za.ac.cut.afinal;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.persistence.BackendlessDataQuery;
import com.backendless.persistence.DataQueryBuilder;
import com.backendless.persistence.QueryOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import weborb.client.ant.wdm.View;
public class Student_List extends AppCompatActivity {
ListView lv;
List<Student_Class> StudentsList;
Student_Class student ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
lv = (ListView)findViewById(R.id.lvStudentDetails1);
retrieveStudent();
}
#Override
protected void onResume() {
super.onResume();
retrieveStudent();
}
private void retrieveStudent()
{
// progressBar.setVisibility(android.view.View.VISIBLE);
if(StudentsList != null)
{
StudentsList.clear();
}
String whereClause = "u_Name = '12'";
DataQueryBuilder queryBuilder = DataQueryBuilder.create();
queryBuilder.setWhereClause(whereClause);
queryBuilder.setPageSize(100);
queryBuilder.setSortBy("l_fname");
Backendless.Persistence.of(Student_Class.class).find(queryBuilder, new AsyncCallback<List<Student_Class>>() {
#Override
public void handleResponse(List<Student_Class> response) {
for (int x = 0; x < response.size(); x++) {
student = new Student_Class(response.get(x).getL_IDNo(), response.get(x).getL_fname(), response.get(x).getL_lname(),
response.get(x).getL_className(), response.get(x).getL_gender(),
response.get(x).getL_race(), response.get(x).getL_DOB(),
response.get(x).getL_classLang(), response.get(x).getL_fullOrhalfday(),
response.get(x).getL_DOE(), response.get(x).getL_address(),
response.get(x).getL_mGardian(), response.get(x).getL_fGardian(),
response.get(x).getL_mGardianEmail(), response.get(x).getL_fGardianEmail(),
response.get(x).getL_mGardianCell(), response.get(x).getL_fGardianCell(),
response.get(x).getL_doc(),
response.get(x).getL_doctCell(), response.get(x).getL_medicalAid(),
response.get(x).getL_medicalAidPlan(), response.get(x).getL_medicalAidPlanNo(),
response.get(x).getL_allergies(), response.get(x).getL_tuckshopBalance()
, response.get(x).getCreated(), response.get(x).getUpdated(),
response.get(x).getObjectID());
}
StudentsList.add(student);
if (StudentsList != null) {
StudentAdapter adapter = new StudentAdapter(Student_List.this,StudentsList);
lv.setAdapter(adapter);
Helper_Class.ShowToast(Student_List.this,"WTF");
}else {
// tv_emptyList.setVisibility(View.VISIBLE);
Helper_Class.ShowToast(Student_List.this,"No Learners enrolled for this class");
}
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
}
}
// Student Class
package za.ac.cut.afinal;
import java.util.Date;
/**
* Created by User on 2017/09/10.
*/
public class Student_Class {
private Date created;
private Date updated;
private String objectID;
private String l_IDNo;
private String l_fname;
private String l_lname;
private String l_className;
private String l_gender;
private String l_race;
private String l_DOB;
private String l_classLang;
private String l_fullOrhalfday;
private String l_DOE;
private String l_address;
private String l_mGardian;
private String l_fGardian;
private String l_mGardianEmail;
private String l_fGardianEmail;
private String l_mGardianCell;
private String l_fGardianCell;
private String l_doc;
private String l_doctCell;
private String l_medicalAid;
private String l_medicalAidPlan;
private String l_medicalAidPlanNo;
private String l_allergies;
private String l_tuckshopBalance;
public Student_Class(String l_fname, String l_lname, String l_gender, String l_race) {
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_gender = l_gender;
this.l_race = l_race;
}
public Student_Class() {
l_IDNo = null;
l_fname = null;
l_lname = null;
l_className = null;
l_gender = null;
l_race = null;
l_DOB = null;
l_classLang = null;
l_fullOrhalfday = null;
l_DOE = null;
l_address = null;
l_mGardian = null;
l_fGardian = null;
l_mGardianEmail = null;
l_fGardianEmail = null;
l_mGardianCell = null;
l_fGardianCell = null;
l_doc = null;
l_doctCell = null;
l_medicalAid = null;
l_medicalAidPlan = null;
l_medicalAidPlanNo = null;
l_allergies = null;
l_tuckshopBalance = null;
created = null;
updated = null;
objectID = null;
}
public Student_Class(String l_IDNo, String l_fname, String l_lname, String l_className, String l_gender, String l_race, String l_DOB, String l_classLang, String l_fullOrhalfday, String l_DOE, String l_address, String l_mGardian, String l_fGardian, String l_mGardianEmail, String l_fGardianEmail, String l_mGardianCell, String l_fGardianCell, String l_doc, String l_doctCell, String l_medicalAid, String l_medicalAidPlan, String l_medicalAidPlanNo, String l_allergies, String l_tuckshopBalance,Date created, Date updated, String objectID) {
this.created = created;
this.updated = updated;
this.objectID = objectID;
this.l_IDNo = l_IDNo;
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_className = l_className;
this.l_gender = l_gender;
this.l_race = l_race;
this.l_DOB = l_DOB;
this.l_classLang = l_classLang;
this.l_fullOrhalfday = l_fullOrhalfday;
this.l_DOE = l_DOE;
this.l_address = l_address;
this.l_mGardian = l_mGardian;
this.l_fGardian = l_fGardian;
this.l_mGardianEmail = l_mGardianEmail;
this.l_fGardianEmail = l_fGardianEmail;
this.l_mGardianCell = l_mGardianCell;
this.l_fGardianCell = l_fGardianCell;
this.l_doc = l_doc;
this.l_doctCell = l_doctCell;
this.l_medicalAid = l_medicalAid;
this.l_medicalAidPlan = l_medicalAidPlan;
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
this.l_allergies = l_allergies;
this.l_tuckshopBalance = l_tuckshopBalance;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getObjectID() {
return objectID;
}
public void setObjectID(String objectID) {
this.objectID = objectID;
}
public String getL_IDNo() {
return l_IDNo;
}
public void setL_IDNo(String l_IDNo) {
this.l_IDNo = l_IDNo;
}
public String getL_fname() {
return l_fname;
}
public void setL_fname(String l_fname) {
this.l_fname = l_fname;
}
public String getL_lname() {
return l_lname;
}
public void setL_lname(String l_lname) {
this.l_lname = l_lname;
}
public String getL_className() {
return l_className;
}
public void setL_className(String l_className) {
this.l_className = l_className;
}
public String getL_gender() {
return l_gender;
}
public void setL_gender(String l_gender) {
this.l_gender = l_gender;
}
public String getL_race() {
return l_race;
}
public void setL_race(String l_race) {
this.l_race = l_race;
}
public String getL_DOB() {
return l_DOB;
}
public void setL_DOB(String l_DOB) {
this.l_DOB = l_DOB;
}
public String getL_classLang() {
return l_classLang;
}
public void setL_classLang(String l_classLang) {
this.l_classLang = l_classLang;
}
public String getL_fullOrhalfday() {
return l_fullOrhalfday;
}
public void setL_fullOrhalfday(String l_fullOrhalfday) {
this.l_fullOrhalfday = l_fullOrhalfday;
}
public String getL_DOE() {
return l_DOE;
}
public void setL_DOE(String l_DOE) {
this.l_DOE = l_DOE;
}
public String getL_address() {
return l_address;
}
public void setL_address(String l_address) {
this.l_address = l_address;
}
public String getL_mGardian() {
return l_mGardian;
}
public void setL_mGardian(String l_mGardian) {
this.l_mGardian = l_mGardian;
}
public String getL_fGardian() {
return l_fGardian;
}
public void setL_fGardian(String l_fGardian) {
this.l_fGardian = l_fGardian;
}
public String getL_mGardianEmail() {
return l_mGardianEmail;
}
public void setL_mGardianEmail(String l_mGardianEmail) {
this.l_mGardianEmail = l_mGardianEmail;
}
public String getL_fGardianEmail() {
return l_fGardianEmail;
}
public void setL_fGardianEmail(String l_fGardianEmail) {
this.l_fGardianEmail = l_fGardianEmail;
}
public String getL_mGardianCell() {
return l_mGardianCell;
}
public void setL_mGardianCell(String l_mGardianCell) {
this.l_mGardianCell = l_mGardianCell;
}
public String getL_fGardianCell() {
return l_fGardianCell;
}
public void setL_fGardianCell(String l_fGardianCell) {
this.l_fGardianCell = l_fGardianCell;
}
public String getL_doc() {
return l_doc;
}
public void setL_doc(String l_doc) {
this.l_doc = l_doc;
}
public String getL_doctCell() {
return l_doctCell;
}
public void setL_doctCell(String l_doctCell) {
this.l_doctCell = l_doctCell;
}
public String getL_medicalAid() {
return l_medicalAid;
}
public void setL_medicalAid(String l_medicalAid) {
this.l_medicalAid = l_medicalAid;
}
public String getL_medicalAidPlan() {
return l_medicalAidPlan;
}
public void setL_medicalAidPlan(String l_medicalAidPlan) {
this.l_medicalAidPlan = l_medicalAidPlan;
}
public String getL_medicalAidPlanNo() {
return l_medicalAidPlanNo;
}
public void setL_medicalAidPlanNo(String l_medicalAidPlanNo) {
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
}
public String getL_allergies() {
return l_allergies;
}
public void setL_allergies(String l_allergies) {
this.l_allergies = l_allergies;
}
public String getL_tuckshopBalance() {
return l_tuckshopBalance;
}
public void setL_tuckshopBalance(String l_tuckshopBalance) {
this.l_tuckshopBalance = l_tuckshopBalance;
}
}
set adapter.notifyDataSetChanged(); after retrieving data from backend.
Info data variable must be same reference adress, I mean do not malloc again etc. after retrieving data.
there are some errors:
1) StudentsList is never istanciated (always null)
2) StudentsList.add(student); cannot work because SutendList is null
3) StudentsList.add(student); should be called inside for loop, why are you calling it outside?
Everything was working fine, i mistakenly typed in the wrong string here "String whereClause = "u_Name = '12'";"
36 hours when the problem was a string!
I tried to display jsonObject in Recyclerview use retrofit library, but it only accept in the Array format. I tried to change the jsonObject to jsonArray, but the problem is the server don't recognize the json type. So now my question is, how to display jsonObject to recyclerview widget. Give me tips or idea..Thank in advance
This is my Jsonobject Data..
{
"success": true,
"data": {
"id": 1,
"parent_id": null,
"name": "Ionnex Sdn Bhd",
"description": "Test Value",
"image": "http://www.ionnex.com/images/logo_ionnex.png",
"phone_no": "12345678",
"fax": "123456",
"address": "Kl Sentral",
"latitude": 0,
"longitude": 0,
"created_at": "2017-08-15 02:26:00",
"donors_count": "4",
"donors_amount": "601.00"
}
}
This is my Fragment connect to the recyclerview widget.
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.baracode.eilsan.data.ApiRequest;
import com.baracode.eilsan.donate.DonateMenuActivity;
import com.baracode.eilsan.donate.parentOrganisation.ParentOrganisationActivity;
import com.baracode.eilsan.donate.parentOrganisation.adapter.DonateParentOrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationModel;
import com.baracode.eilsan.R;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import static android.R.id.message;
public class OrganisationFragment extends Fragment {
private ViewPager viewPager;
private ImageView mosqueImage;
private RecyclerView recyclerView;
// private ArrayList<OrganisationModel> organisationModelArrayList = new ArrayList<>();
private ArrayList<Organisation> organisationList = new ArrayList<>();
// Organisation organisationList = new Organisation();
private OrganisationAdapter organisationAdapter;
private OrganisationFragment.MainPagerAdapter adapter;
private Organisation organisation;
private Context context;
private ApiRequest apiRequest;
public Organisation selectedOrganization = null;
public OrganisationFragment() {
// Required empty public constructor
}
public View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_organisation, container, false);
recyclerView = rootView.findViewById(R.id.organisation_recyclerview);
mosqueImage = rootView.findViewById(R.id.donate_fragment_mosque_image);
// organisationModelArrayList.clear();
prepareOrganisationData();
// Organisation org = ParentOrganisationActivity.selectedOrganization;
// recyclerView.setAdapter();
return rootView;
}
//here create parse
public static OrganisationFragment newInstance(Organisation organisation) {
OrganisationFragment fragment = new OrganisationFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
fragment.selectedOrganization = organisation;
return fragment;
}
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private FragmentManager fragmentManager;
private final ArrayList<Fragment> fragmentList = new ArrayList<>();
private final ArrayList<String> fragmentTitleList = new ArrayList<>();
MainPagerAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
}
//Organisation data change here
private void prepareOrganisationData() {
// OrganisationModel organisationModel = new OrganisationModel("Masjid Sultan Abu Bakar", "Kuala Lumpur", R.drawable.mosque_1);
// this.organisationModelArrayList.add(organisationModel);
//
// organisationModel = new OrganisationModel("Masjid Zahir", "Kuala Lumpur", R.drawable.mosque_2);
// this.organisationModelArrayList.add(organisationModel);
Bundle extras = getActivity().getIntent().getExtras();
if (extras == null) {
selectedOrganization = null;
} else {
Gson gson = new Gson();
// Gson gson = new GsonBuilder().serializeNulls().create();
selectedOrganization = gson.fromJson(extras.getString("org"), Organisation.class);
Organisation org = selectedOrganization;
Picasso.with(context).load(org.getImage()).into(mosqueImage);
}
ApiRequest.getInstance().getOrganisationIdDetails(getActivity(), selectedOrganization.id, new ApiRequest.GetAllOrgIdDetailsCallback() {
#Override
public void getAllOrgIdDetailsSuccess(ArrayList<Organisation> result) {
organisationList = result;
organisationAdapter = new OrganisationAdapter(organisationList, context);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(organisationAdapter);
}
#Override
public void getAllOrgDetailsFail(String message) {
}
});
}
/* TODO
add onClick listener to each object
*/
}
This is my Fragment Adapter..
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baracode.eilsan.R;
import com.baracode.eilsan.donate.organisation.OrganisationActivity;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class OrganisationAdapter extends RecyclerView.Adapter<OrganisationAdapter.MyViewHolder> {
private Context context;
// private final ArrayList<OrganisationModel> organisationModelList;
ArrayList<Organisation> organisationModelList;
public OrganisationAdapter(ArrayList<Organisation> organisationModelList , Context context) {
this.organisationModelList = organisationModelList;
this.context = context;
}
#Override
public OrganisationAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_organisation_recyclerview, parent, false);
return new OrganisationAdapter.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(OrganisationAdapter.MyViewHolder holder, int position) {
// OrganisationModel organisationModel = organisationModelList.get(position);
final Organisation organisationModel = organisationModelList.get(position);
holder.organisationName.setText(organisationModel.getName());
holder.cityName.setText(organisationModel.getAddress());
// holder.mosqueImage.setImageResource(organisationModel.getOrganisationImage());
Picasso.with(context)
.load(organisationModel.getImage())
.into(holder.mosqueImage);
holder.headlineLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.organisation_linearlayout:
intent = new Intent(view.getContext(), OrganisationActivity.class);
view.getContext().startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return organisationModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView organisationName, cityName;
public ImageView mosqueImage;
public LinearLayout headlineLinearLayout;
public MyViewHolder(View view) {
super(view);
organisationName = view.findViewById(R.id.donate_parent_organisation_name);
cityName = view.findViewById(R.id.donate_parent_organisation_city_name);
mosqueImage = view.findViewById(R.id.donate_parent_organisation_image);
headlineLinearLayout = view.findViewById(R.id.organisation_linearlayout);
}
}
/* TODO
* Implement on click listener on the recyclerview
* */
}
This is my Fragment Model(Setter n Getter)
public class OrganisationModel {
private String organisationName = "";
private String cityName = "";
private int organisationImage;
public int getOrganisationImage() {
return organisationImage;
}
public void setOrganisationImage(int organisationImage) {
this.organisationImage = organisationImage;
}
public String getOrganisationName() {
return organisationName;
}
public void setOrganisationName(String organisationName) {
this.organisationName = organisationName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public OrganisationModel(String organisationName, String cityName, int organisationImage) {
this.organisationName = organisationName;
this.cityName = cityName;
this.organisationImage = organisationImage;
}
}
This is MyApirequest class to get the Json Object
public void getOrganisationIdDetails(final Context context, String organizationIdDetails, final GetAllOrgIdDetailsCallback apiCallback) {
String accessToken = LocalData.getInstance().loadStringData(LocalData.KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOrgIdDetails("Bearer " + accessToken, organizationIdDetails);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("eihsan", "getOrgIdDetails: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
//JsonArray jsonArray = jsonData.getAsJsonArray("data");
Organisation org = new Organisation();
// ArrayList<Organisation> organisationList = new ArrayList<>();
org.setId(jsonData.get("id").getAsString());
org.setParentId(jsonData.get("parent_id").toString());
org.setName(jsonData.get("name").getAsString());
org.setDescription(jsonData.get("description").getAsString());
org.setImage(jsonData.get("image").getAsString());
org.setPhone_no(jsonData.get("phone_no").getAsString());
org.setFax(jsonData.get("fax").getAsString());
org.setAddress(jsonData.get("address").getAsString());
org.setLatitude(jsonData.get("latitude").getAsString());
org.setLongitude(jsonData.get("longitude").getAsString());
org.setDonorCount(jsonData.get("donors_count").getAsString());
apiCallback.getAllOrgIdDetailsSuccess(org);
} else {
apiCallback.getAllOrgDetailsFail("Data Error occurred");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
}
});
}
AFTER FEW MONTH, I SOLVED THE PROBLEM..
Use retrofit library and call the api before display. So here how to call the data for future reference....
public void getOneOrg(String orgId, final GetOneOrgCallback apiCallback) {
String auth = "Bearer " + LocalData.getInstance().loadStringData(LocalData.SP_KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOneOrg(auth, orgId);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
StaticFunction.showLogD("getOneOrg: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
Organization org = gson.fromJson(jsonData, Organization.class);
apiCallback.getOneOrgSuccess(org);
} else {
apiCallback.getOneOrgFail("Data error");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
apiCallback.getOneOrgFail("Data error");
}
});
}
Here how i called the json object in API "Organization" is the java file for each variables in api.
I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}
My Fragment is not showing custom listview data. Asynctask is working properly but after sometime application is crashing with null pointer exception.
My fragment class code :
package com.example.y34h1a.androidlime.Fragment;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.adapter.FeedListAdapter;
import com.example.y34h1a.androidlime.data.FeedItem;
import com.example.y34h1a.androidlime.network.VolleySigleton;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class FragmentBoxOffice extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VolleySigleton volleySigleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private OnFragmentInteractionListener mListener;
private static final String TAG = FragmentBoxOffice.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private ArrayList<FeedItem> feedItems;
private String URL_FEED = "http://androidlime.com/wp-json/posts";
private FeedItem feedItem = new FeedItem();
// TODO: Rename and change types and number of parameters
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentBoxOffice() {
// Required empty public constructor
feedItems = new ArrayList<FeedItem>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_box_office, container, false);
listView = (ListView) view.findViewById(R.id.fragmentList);
new JSONAsyncTask().execute(URL_FEED);
return view;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
for(String url : urls){
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject titleObj = jsonArray.getJSONObject(i);
String title = titleObj.getString("title");
feedItem.setStatus(title);
Log.i("arif", title);
//DATE
String date = titleObj.getString("date");
feedItem.setTimeStamp(date);
Log.i("arif", date);
//Author Name
JSONObject author = titleObj.getJSONObject("author");
String name = author.getString("name");
feedItem.setName(name);
Log.i("arif", name);
//Author Profile Pic
String profilePic = author.getString("avatar");
feedItem.setProfilePic(profilePic);
Log.i("arif", profilePic);
//Post thumbnail
JSONObject thumnailObj = titleObj.getJSONObject("featured_image");
String thumbnail = thumnailObj.getString("guid");
feedItem.setThumnail(thumbnail);
Log.i("arif", thumbnail);
feedItems.add(feedItem);
}
return true;
//------------------>>
} catch (IOException e) {
Log.e("arif", "Parse Exception");
} catch (JSONException e) {
Log.e("arif", "Parse Exception");
}
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
if(result == false)
Log.i("arif","unable to featch data");
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
My Custom Adapter Class:
package com.example.y34h1a.androidlime.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.data.FeedItem;
import java.util.ArrayList;
import java.util.List;
public class FeedListAdapter extends ArrayAdapter<FeedItem> {
private LayoutInflater vi;
private List<FeedItem> feedItems;
int Resource;
ViewHolder holder;
public FeedListAdapter(Context context, int resource, ArrayList<FeedItem> feedItems) {
super(context, resource, feedItems);
this.feedItems = feedItems;
Resource = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
holder.name = (TextView) v.findViewById(R.id.name);
holder.status = (TextView) v.findViewById(R.id.txtStatusMsg);
holder.time = (TextView) v.findViewById(R.id.timestamp);
holder.url = (TextView) v.findViewById(R.id.txtUrl);
holder.profilePic = (ImageView) v.findViewById(R.id.profilePic);
holder.thumbnail = (ImageView) v.findViewById(R.id.thumbernail);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
v.setTag(holder);
holder.name.setText(feedItems.get(position).getName());
holder.status.setText(feedItems.get(position).getStatus());
holder.time.setText(feedItems.get(position).getTimeStamp());
holder.url.setText(feedItems.get(position).getUrl());
holder.profilePic.setImageResource(R.drawable.ic_launcher);
holder.profilePic.setImageResource(R.drawable.sample);
return v;
}
static class ViewHolder {
public TextView name;
public TextView status;
public TextView url;
public TextView time;
public ImageView profilePic;
public ImageView thumbnail;
}
}
The line where error showing is :
View v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);'
From your code, I think your error is more like ClassCastException, don't know why it's NPE, because
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
You pass a ApplicationContext then cast it to a Activity
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
Try this may works:
in onPostExecute:
if (getActivity() != null) {
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
}
in getView:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item, parent, false);
Try:
v = (LayoutInflater.from(getContext()).inflate(R.layout.feed_item, parent, false);
Inside my tab bar i want to show my data in Recycler view by using json parsing using volley library. I parsed the data and it showing in toast perfectly.But in Recycler view its not showing Here is my codes.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
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.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.transform.ErrorListener;
import info.tatwa.adupter.AdupterBoxOffice;
import info.tatwa.extras.Keys;
import info.tatwa.extras.UrlEndPoint;
import info.tatwa.login.L;
import info.tatwa.model.Movies;
import info.tatwa.network.MyApplication;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
import info.tatwa.extras.UrlEndPoint.*;
import info.tatwa.extras.Keys.EndpointBoxOffice.*;
public class FragmentBoxOffice extends Fragment {
private VolleySingleton volleySingleton;
private RequestQueue requestQueue;
private AdupterBoxOffice adupterBoxOffice;
private ArrayList<Movies>listMovie = new ArrayList<>();
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final String ROTET_TOMATO_URL_BOX_OFFICE="My url is here"
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView listMovieHits;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentBoxOffice.
*/
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static String getRequestUrl(int limit){
//ROTET_TOMATO_URL_BOX_OFFICE+"?apikey="+ MyApplication.ROTET_TOMATO_API_KEY+"&limit="+limit;
return UrlEndPoint.URL_BOX_OFFICE +
UrlEndPoint.URL_CHAR_QUASTIAN+
UrlEndPoint.URL_CHAR_PAREM_APIKEY +
MyApplication.ROTET_TOMATO_API_KEY +
UrlEndPoint.URL_CHAR_APPEND+
UrlEndPoint.URL_CHAR_PAREM_LIMIT + limit;
}
public FragmentBoxOffice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getmRequestQueue();
senJsonRequest();
}
public void senJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10), (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
paresJSONResponse(response);
listMovie =paresJSONResponse(response);
adupterBoxOffice.setMovieList(listMovie);
L.t(getActivity(), response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Error"+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(request);
}
public ArrayList<Movies> paresJSONResponse(JSONObject response){
ArrayList<Movies> listMovie = new ArrayList<>();
if(response ==null|| response.length()==0 ){
return null;
}
try {
StringBuilder data = new StringBuilder();
JSONArray arrayMovie = response.getJSONArray(Keys.EndpointBoxOffice.KEY_MOVIES);
Log.v("BIKASH", "JSON Object id" + arrayMovie);
for(int i = 0; i<arrayMovie.length();i++){
JSONObject currentMovies= arrayMovie.getJSONObject(i);
Long id =currentMovies.getLong(Keys.EndpointBoxOffice.KEY_ID);
String title=currentMovies.getString(Keys.EndpointBoxOffice.KEY_TITLE);
JSONObject objectReleaseDates=currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RELEASE_DATES);
String releaseDate=null;
if(objectReleaseDates.has(Keys.EndpointBoxOffice.KEY_THEATER)){
releaseDate = objectReleaseDates.getString(Keys.EndpointBoxOffice.KEY_THEATER);
}
else {
releaseDate="NA";
}
int audianceRatting=-1;
JSONObject objectRatting = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RATINGS);
{
if(objectRatting.has(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE)){
audianceRatting=objectRatting.getInt(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE);
}
}
String synuypsis = currentMovies.getString(Keys.EndpointBoxOffice.KEY_SYNOPSIS);
String urlThumbnel = null;
JSONObject objPoster = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
if(objPoster.has(Keys.EndpointBoxOffice.KEY_THUMBNAIL)){
urlThumbnel = objPoster.getString(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
}
Movies movie =new Movies();
movie.setId(id);
movie.setTitle(title);
Date date = dateFormat.parse(releaseDate);
movie.setReleaseDateTheater(date);
movie.setAudienceScore(audianceRatting);
movie.setSynopsis(synuypsis);
movie.setUrlThumbnail(urlThumbnel);
listMovie.add(movie);
// data.append(id + "\n");
}
L.t(getActivity(),listMovie.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return listMovie;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_fragment_box_office, container, false);
listMovieHits =(RecyclerView)view.findViewById(R.id.listMovieHits);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
adupterBoxOffice = new AdupterBoxOffice(getActivity());
listMovieHits.setAdapter(adupterBoxOffice);
senJsonRequest();
return view;
}
}
My Adupter
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import java.util.ArrayList;
import info.tatwa.model.Movies;
import info.tatwa.myfragment.FragmentBoxOffice;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
public class AdupterBoxOffice extends RecyclerView.Adapter<AdupterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
FragmentBoxOffice activity;
private ArrayList<Movies> listMovie = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
public AdupterBoxOffice(Context context){
layoutInflater=LayoutInflater.from(context);
volleySingleton=VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movies>listMovie){
this.listMovie = listMovie;
notifyItemRangeChanged(0,listMovie.size());
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.movie_list_itom,parent,false);
ViewHolderBoxOffice viewHolder =new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movies currentMovie =listMovie.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
holder.movieReleaseDate.setText(currentMovie.getReleaseDateTheater().toString());
holder.movieRatting.setRating(currentMovie.getAudienceScore()/20.0f);
String urlThumbnel = currentMovie.getUrlThumbnail();
if(urlThumbnel!=null){
imageLoader.get(urlThumbnel, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.imagePoster.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return listMovie.size();
}
static class ViewHolderBoxOffice extends RecyclerView.ViewHolder {
private ImageView imagePoster;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieRatting;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
imagePoster=(ImageView)itemView.findViewById(R.id.movieThumbnail);
movieTitle =(TextView)itemView.findViewById(R.id.movieTitle);
movieReleaseDate=(TextView)itemView.findViewById(R.id.movieReleaseDate);
movieRatting=(RatingBar)itemView.findViewById(R.id.movieAudienceScore);
}
}
}
And My Model class
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
public class Movies{
private long id;
private String title;
private Date releaseDateTheater;
private int audienceScore;
private String synopsis;
private String urlThumbnail;
private String urlSelf;
private String urlCast;
private String urlReviews;
private String urlSimilar;
public Movies() {
}
public Movies(long id,
String title,
Date releaseDateTheater,
int audienceScore,
String synopsis,
String urlThumbnail,
String urlSelf,
String urlCast,
String urlReviews,
String urlSimilar) {
this.id = id;
this.title = title;
this.releaseDateTheater = releaseDateTheater;
this.audienceScore = audienceScore;
this.synopsis = synopsis;
this.urlThumbnail = urlThumbnail;
this.urlSelf = urlSelf;
this.urlCast = urlCast;
this.urlReviews = urlReviews;
this.urlSimilar = urlSimilar;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReleaseDateTheater() {
return releaseDateTheater;
}
public void setReleaseDateTheater(Date releaseDateTheater) {
this.releaseDateTheater = releaseDateTheater;
}
public int getAudienceScore() {
return audienceScore;
}
public void setAudienceScore(int audienceScore) {
this.audienceScore = audienceScore;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getUrlThumbnail() {
return urlThumbnail;
}
public void setUrlThumbnail(String urlThumbnail) {
this.urlThumbnail = urlThumbnail;
}
public String getUrlSelf() {
return urlSelf;
}
public void setUrlSelf(String urlSelf) {
this.urlSelf = urlSelf;
}
public String getUrlCast() {
return urlCast;
}
public void setUrlCast(String urlCast) {
this.urlCast = urlCast;
}
public String getUrlReviews() {
return urlReviews;
}
public void setUrlReviews(String urlReviews) {
this.urlReviews = urlReviews;
}
public String getUrlSimilar() {
return urlSimilar;
}
public void setUrlSimilar(String urlSimilar) {
this.urlSimilar = urlSimilar;
}
#Override
public String toString() {
return "\nID: " + id +
"\nTitle " + title +
"\nDate " + releaseDateTheater +
"\nSynopsis " + synopsis +
"\nScore " + audienceScore +
"\nurlThumbnail " + urlThumbnail +
"\nurlSelf " + urlSelf +
"\nurlCast " + urlCast +
"\nurlReviews " + urlReviews +
"\nurlSimilar " + urlSimilar +
"\n";
}
}
Please help me out .. Thanks in advance ..
After adupterBoxOffice.setMovieList(listMovie);
try add adupterBoxOffice.notifyDataSetChanged();
I found my solution.I put some wrong key during pars the Json. That's why my ArrayList returning zero.
Many many thanks to all for helping me out.