This is my java file where I'm trying to call Json, but I'm not getting any data. Also I'm not getting any error, so I couldn't find where the problem is.
Here is my code and the Json looks like this:
[
{
"title": "Quest",
"description": "Description Quest",
"district": "District Quest";
}
]
AND THE CODE:
public class Quests extends Fragment {
// Log tag
private static final String TAG = Quests.class.getSimpleName();
// Quest Json url
private static final String url = "http://my-ip-adress-of-computer/project/quests.txt";
private ProgressDialog pDialog;
private List<com.dusandimitrijevic.model.Quests> questList = new ArrayList<com.dusandimitrijevic.model.Quests>();
private ListView listView;
private QuestListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quests, container, false);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
listView = (ListView) rootView.findViewById(R.id.list);
adapter = new QuestListAdapter(getActivity(), questList);
listView.setAdapter(adapter);
fetchQuests();
return rootView;
}
private void fetchQuests() {
// Creating volley request obj
JsonArrayRequest questReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
com.dusandimitrijevic.model.Quests q = new com.dusandimitrijevic.model.Quests();
q.setTitle(obj.getString("title"));
q.setDescription(obj.getString("description"));
q.setDistrict(obj.getString("district"));
// adding quests to quest array
questList.add(q);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
// stopping swipe refresh
//swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
// stopping swipe refresh
//swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(questReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Semicolon ; is no a valid field separator. Also you can't use a field separator after the last field at all. Valid JSON should look like this:
[
{
"title": "Quest",
"description": "Description Quest",
"district": "District Quest"
}
]
Related
I've been looking around everywhere in trying to find out why my code was causing an issue. I have a GridView that has an ArrayAdapter which pulls photos down with an AsyncTask. I can see the items being updated but when I try to update the adapter the GridView doesn't seem to update with the new view.
This is the relevant code that does the work...
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
//String id = object.getString("id");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
if(gridViewAdapter != null){
gridViewAdapter.clear();
gridViewAdapter.addAll(list);
gridViewAdapter.notifyDataSetChanged();
gridView.invalidateViews();
} else {
gridViewAdapter = new GridViewAdapter(getActivity(), R.layout.gridview_item, list);
gridView.setAdapter(gridViewAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}
I would really appreciate any help if possible. Trying to get the app out before new years :).
Maybe If you could tell me why this happens so It won't cause an issue again and other will see.
EDIT: Added a bit more code which has it refreshing after I click the button twice.
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
pictureAdapter = new PictureAdapter(getActivity(), list);
gridView.setAdapter(pictureAdapter);
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list);
gridView.invalidate();
progressDialog.dismiss();
}
}
Adapter:
public class PictureAdapter extends BaseAdapter {
private ArrayList<ImageItem> items;
private Context context;
private TextView titleText;
private ImageView itemImage;
public PictureAdapter(Context context, ArrayList<ImageItem> items){
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.gridview_item, parent, false);
titleText = (TextView) v.findViewById(R.id.text);
itemImage = (ImageView)v.findViewById(R.id.image);
titleText.setText(items.get(position).getTitle());
Picasso.with(context).load(items.get(position).getUrl()).fit().into(itemImage);
return v;
}
public void updateItemList(ArrayList<ImageItem> newItemList){
this.items = newItemList;
notifyDataSetChanged();
}
}
Try the below lines in post execute
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list,gridView);
progressDialog.dismiss();
}
Now in your updateItemList
public void updateItemList(ArrayList<ImageItem> newItemList,GridView gridView){
this.items = newItemList;
gridView.setAdapter(null);
gridView.invalidateViews();
gridView.deferNotifyDataSetChanged();
gridView.setAdapter(list);
}
Why you are calling Volley request from AsyncTask as Volley perform request on NetworkThread.
Remove AsyncTask and directly call Volley.
Just try this. Hope it helps.
private ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
progressDialog.show();
fetchJsonResponse(url);
}
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
pictureAdapter.notifyDataSetChanged();
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
I want when i scroll up to my list view load more data using volley, i created PHP webservice and result
{
"error": false,
"status_code": 200,
"total_items": 2,
"last_page": 1,
"current_page": 1,
"per_page": 10,
"result": [
{
"id": 1,
"title": "here title one",
"city": "city",
"zone": "zone",
"type": "type",
"service": "service",
"space": "545",
"date": "2016-08-28 12:24:34",
"image": "http:\/\/localhost\/my_cms\/public\/assets\/media\/ad-pic.png"
}, {
"id": 2,
"title": "here title two",
"city": "city",
"zone": "zone",
"type": "type",
"service": "service",
"space": "545",
"date": "2016-08-28 12:24:34",
"image": "http:\/\/localhost\/my_cms\/public\/assets\/media\/ad-pic.png"
}]
}
My RecentActivity.Java Class
public class RecentActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, AbsListView.OnScrollListener {
private SwipeRefreshLayout swipeRefreshLayout;
// Log tag
private static final String TAG = HomeActivity.class.getSimpleName();
// RealstateDataModel json url
private static final String homeAdsurl = "http://192.168.43.74/my_cms/public/api/realstate/latest?page=";
private ProgressDialog pDialog;
private List<RealstateDataModel> realstateData = new ArrayList<RealstateDataModel>();
private ListView listView;
private HomeListAdapter homaAdapter;
int current_page = 0;
boolean loading;
RecentActivity activity = null;
View loadMoreView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recent);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.Recent_View);
String home= getResources().getString(R.string.recient_offers);
setTitle(home);
activity = this;
//List View
setListAdapter();
listView.setOnScrollListener(this);
}
public void setListAdapter(){
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_recent_layout);
homaAdapter = new HomeListAdapter(this, realstateData);
listView.setAdapter(homaAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchRealStateList();
}
}
);
}
#Override
public void onRefresh() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
fetchRealStateList();
}
private void fetchRealStateList() {
// Creating volley request obj
JsonObjectRequest homeListReq = new JsonObjectRequest(Request.Method.GET,
homeAdsurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
if (response.length() > 0) {
try {
JSONArray ResultArray = response.getJSONArray("result");
if(realstateData!=null) {
realstateData.clear();
}
// Parsing json
for (int i = 0; i < ResultArray.length(); i++) {
try {
JSONObject obj = ResultArray.getJSONObject(i);
RealstateDataModel realstateDataBeans = new RealstateDataModel();
realstateDataBeans.setTitle(obj.getString("title"));
realstateDataBeans.setCity(obj.getString("city"));
realstateDataBeans.setZone(obj.getString("zone"));
realstateDataBeans.setType(obj.getString("type"));
realstateDataBeans.setService(obj.getString("service"));
realstateDataBeans.setSpace(obj.getString("space"));
realstateDataBeans.setCreated_at(obj.getString("date"));
realstateDataBeans.setImage(obj.getString("image"));
// adding movie to movies array
realstateData.add(0,realstateDataBeans);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
homaAdapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(homeListReq);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
}
It tried and searched more but when it try to scroll not effect, i make f
onScrollStateChanged and onScroll empty to fill it your helpful code
For example load 10 item at first. When user reach the bottom load 10 more item. How can you understand it is bottom?
The last item's bottom == scroll position
means end of the list. Load more.
I'm trying to implement a recycler view in fragment using Volley library.
Data is loaded and logged successfully from the server but not displayed at all in the recycler fragment.
The request fetches the data and logs it but nothing renders in the fragment. There are no XML errors.
HitVideoFragment.java
public class HitVideoFragment extends Fragment {
private RecyclerView recyclerView;
private HitVideoAdapter adapter;
private List<HitVideo> hitVideoList = new ArrayList<HitVideo>();
public HitVideoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hit_video, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//Initializing Views
recyclerView = (RecyclerView) this.getActivity().findViewById(R.id.hitvideo_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new HitVideoAdapter(hitVideoList);
recyclerView.setAdapter(adapter);
//Calling method to get data
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this.getActivity(),"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(AppConfig.URL_HIT_VIDEOS,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("Some tag", "onResponse: "+response.toString());
hitVideoList = new ArrayList<HitVideo>();
for(int i = 0; i<response.length(); i++) {
HitVideo hitVideo = new HitVideo();
JSONObject json = null;
try {
json = response.getJSONObject(i);
hitVideo.setTitle(json.getString("name"));
hitVideo.setUrl(json.getString("url"));
hitVideo.setUsername(json.getString("user_id"));
hitVideo.setHits(json.getInt("hits"));
} catch (JSONException e) {
e.printStackTrace();
}
hitVideoList.add(hitVideo);
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Hit Video", "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
Context _context = getActivity().getApplicationContext();
SharedPreferences pref;
String token;
if (_context != null) {
pref = _context.getSharedPreferences(Config.PREF_NAME, Config.PRIVATE_MODE);
if (pref != null) {
token = pref.getString(Config.USER_TOKEN, null);
headers.put("Authorization", "Bearer " + token);
}
}
return headers;
}
};
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this.getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
This is not throwing any exceptions. And the model and adapters are doing their job fine. Thanks in advance.
I am probably too late to this,
But I had the same issue and I fixed it by returning the list.size() on the getItemCout() method in the Adapter class.
I have a listview being populated with data from the server. If I use wifi connection everything works fine.
Is there anything that I could do to improve this code to wait until the data is full loaded from the server with bad connections like 3G or poor wifi connection?
Sometimes listview gets empty.
public class LoadAsync extends AsyncTask<String, Boolean, Boolean>{
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListEvents.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
// Creating volley request obj
JsonArrayRequest eventReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.dismiss();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Event event = new Event();
event.setImovel_id(obj.getString("imovel_id"));
event.setThumbnailUrl(obj.getString("arquivo"));
event.setNegocio(obj.getString("negocio"));
event.setImovel(obj.getString("imovel"));
event.setMobilia(obj.getString("mobilia"));
event.setGaragem(obj.getString("garagem"));
event.setPreco(obj.getString("preco"));
city = obj.getString("city").trim();
statee = obj.getString("state").trim();
checkNegocio = obj.getString("negocio").trim();
checkImovel = obj.getString("imovel").trim();
checkMobilia = obj.getString("mobilia").trim();
checkGaragem = obj.getString("garagem").trim();
checkPreco = obj.getString("preco").trim();
checkPreco = checkPreco.replace("R", "");
checkPreco = checkPreco.replaceAll("[$.,]", "");
int serverprice = Integer.parseInt(checkPreco);
String app_price = checkP.getText().toString();
app_price = app_price.replace("R", "");
app_price = app_price.replaceAll("[$.,]", "");
int i_price = Integer.parseInt(app_price);
if(estado.getText().toString().trim().equalsIgnoreCase(statee) &&
cidade.getText().toString().trim().equalsIgnoreCase(city) &&
checkN.getText().toString().trim().equalsIgnoreCase(checkNegocio)){
if(/*checkI.getText().toString().equalsIgnoreCase(checkImovel) ||
checkM.getText().toString().equalsIgnoreCase(checkMobilia) ||
checkG.getText().toString().equalsIgnoreCase(checkGaragem) ||*/
serverprice <= i_price){
// adding event to events array
eventList.add(event);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} if(eventList.size() > 0){
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
}else{
noEvent.setText("Nothing found.");
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.dismiss();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(eventReq);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String imovelID = ((TextView) view.findViewById(R.id.imovel_id)).getText().toString();
ImageView eFile = ((ImageView) view.findViewById(R.id.thumbnail));
String imgUrl = (String) eFile.getTag();
String negocio = ((TextView) view.findViewById(R.id.negocio)).getText().toString();
String imovel = ((TextView) view.findViewById(R.id.imovel)).getText().toString();
String mobilia = ((TextView) view.findViewById(R.id.mobilia)).getText().toString();
String garagem = ((TextView) view.findViewById(R.id.garagem)).getText().toString();
String preco = ((TextView) view.findViewById(R.id.preco)).getText().toString();
Intent i = new Intent(getApplicationContext(), EventDetails.class);
i.putExtra(TAG_ID, imovelID);
i.putExtra(TAG_ARQUIVO, imgUrl);
i.putExtra(TAG_NEGOCIO, negocio);
i.putExtra(TAG_IMOVEL, imovel);
i.putExtra(TAG_MOBILIA, mobilia);
i.putExtra(TAG_GARAGEM, garagem);
i.putExtra(TAG_PRECO, preco);
startActivity(i);
}
});
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//pDialog.dismiss();
}
}
Show an indeterminate ProgressBar, till your data is loaded. Cancel the progress bar once the loading is complete
Refer:
http://developer.android.com/reference/android/widget/ProgressBar.html
Also see Android indeterminate progress bar
How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);