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.
Related
I have a query to a mysql database, it asks for all the favorite courses, but first I need to pass the user to it. How could I do that?
file java:
public class FavoritosFragment extends Fragment {
RecyclerView recyclerView;
MyFavoritosRecyclerViewAdapter AdapterFavoritos;
List<Cursos>cursosList;
RequestQueue requestQueue;
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
public FavoritosFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favoritos_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
cursosList=new ArrayList<>();
ejecutarServicio();
obtenerCursos();
//asociamos el adaptador al recyclerview
AdapterFavoritos=new MyFavoritosRecyclerViewAdapter(cursosList, mListener);
recyclerView.setAdapter(AdapterFavoritos);
}
return view;
}
private void ejecutarServicio() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.URL_favo) , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error de registro!"+error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
final String usuario = "avo";
params.put("usu_usuario",usuario);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
public void obtenerCursos() {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.URL_favo),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("Curso");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
boolean add = cursosList.add(
new Cursos(
jsonObject1.getString("id_curso"),
jsonObject1.getString("titulo"),
jsonObject1.getString("descripcion"),
jsonObject1.getString("categoria"),
jsonObject1.getString("imagen")
)
);
}
AdapterFavoritos=new MyFavoritosRecyclerViewAdapter(cursosList, mListener);
recyclerView.setAdapter(AdapterFavoritos);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
);
requestQueue.add(stringRequest);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(Cursos item);
}
}
this is my php file.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include 'conexion.php';
$usu_usuario=$_POST['usu_usuario'];
$miDato='';
$consultado="SELECT id_usuario FROM usuario WHERE usu_usuario='".$usu_usuario."'";
$result=mysqli_query($conexion,$consultado);
while($mostrar=mysqli_fetch_array($result)){
$miDato= $mostrar['id_usuario'];
}
// echo $miDato;
$consulta = " SELECT * FROM curso RIGHT JOIN favoritos ON curso.id_curso=favoritos.id_curso WHERE favoritos.id_usuario='".$miDato."'";
$resultado=$conexion->query($consulta);
$datos = array();
while($resultados = $resultado->fetch_assoc()) {
$datos[] = $resultados;
}
//echo json_encode($datos);
echo json_encode(array("Curso" => $datos));
mysqli_query($conexion,$consulta) or die (mysqli_error());
mysqli_close($conexion);
?>
here my two files java and php to the database query ..
I'm desperate you know how angry when the code does not understand me hahaha;)
here my two files java and php to the database query ..
I'm desperate you know how angry when the code does not understand me hahaha;)
what I want is to send the user to the query and volley returns the result, I know how to do it separately but I do not understand how to do that in a single request
Here in my UI, i have used two buttons to load different data to a RecyclerView. First time the data is displaying properly on click of each button. But if i click the button for the second time the data is adding to the adapter twice. I mean the the adapter is not cleared. it is keep on adding the data on click of button. I Think i have to do something with the adapter on click of a button. Can anyone pls let me know how to clear the adapter or where i am going wrong..
Here is the code.
public class GstVendorLocRetrieve extends AppCompatActivity {
private String vault;
private TextView txt;
public static final String DATA_URL = "http://oursite.com/getgstvendorlocation.php?vault_no=";
public static final String DATA_URL1 = "http://oursite.com/getgstcustomerlocation.php?vault_no=";
//Tags for my JSONRes
public static final String TAG_VendorID = "VendorID";
public static final String TAG_CustomerID = "Customer_ID";
public static final String TAG_ADDRESS = "Address";
private Button vendor;
private Button customer;
//Creating a List of superheroes
private List<GstVendLoc> listSuperHeroes;
private List<GstCustLoc> listSuperHeroes1;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationretrieve);
SharedPreferences sharedPreferences = getSharedPreferences(GstLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(GstLogin.EMAIL_SHARED_PREF,"Not Available");
vendor = (Button) findViewById(R.id.login);
customer = (Button) findViewById(R.id.login1);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
listSuperHeroes1 = new ArrayList<>();
vendor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setAdapter(null);
getData();
}
});
customer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setAdapter(null);
getData1();
}
});
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GstVendLoc gst1 = new GstVendLoc();
JSONObject json = null;
try {
json = array.getJSONObject(i);
gst1.setVendorID(json.getString(TAG_VendorID));
gst1.setAddress(json.getString(TAG_ADDRESS));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(gst1);
}
//Finally initializing our adapter
adapter = new CardAdapter17(listSuperHeroes, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private void getData1(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL1+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData1(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData1(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GstCustLoc gst1 = new GstCustLoc();
JSONObject json = null;
try {
json = array.getJSONObject(i);
gst1.setCustomer_ID(json.getString(TAG_CustomerID));
gst1.setAddress(json.getString(TAG_ADDRESS));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes1.add(gst1);
}
//Finally initializing our adapter
adapter = new CardAdapter18(listSuperHeroes1, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Use this code for clear RecycleView items
public void clear() {
int size = listSuperHeroes.size();
listSuperHeroes.clear();
notifyItemRangeRemoved(0, size);
}
You need to clear your Array List before you get data second time.
Do this inside parseData1 method before for loop.
listSuperHeroes.clear();
listSuperHeroes1.clear();
What you have to do is Update RecyclerView on button Click , Put below method in your adapter
public void updateData(ArrayList<ViewModel> viewModels) {
items.clear();
items.addAll(viewModels);
notifyDataSetChanged();
}
Than call this method with new data
ArrayList<ViewModel> viewModelsWithNewData = new ArrayList<ViewModel>();
adapter.updateData(viewModelsWithNewData );
you dont need to set adapter after geting data from the online
//Finally initializing our adapter
adapter = new CardAdapter18(listSuperHeroes1, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
you can initialize of set the adapter in the on create and add data in the 'listSuperHeroes1' and after parse data you can do adapter.notifyDataSetChanged();
this will change the list data.
and the solution for the getting the previous data you have to remove the all data from the listsuperHeroes1 this will help you if you getting any problem please comment .
I am just improving #Rony's answer.
If you should always check if the ArrayList is not null before attempting to call .size(), otherwise, you might end up with a null pointer exception
if (listSuperHeroes != null && !listSuperHeroes.isEmpty()) {
int size = listSuperHeroes.size();
listSuperHeroes.clear();
notifyItemRangeRemoved(0, size);
}
I want to get the JSON response onto a RecyclerView. Though I am getting the correct response through the REST API I have used , but the response is not coming on the RecyclerView after parsing. Below is the code. Please help !!
RepoActivity.java
public class RepoActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<RepoList> repoList = new ArrayList<>();
String data = "";
private RecyclerView recyclerView;
private static String url;
private RepoAdapter adapter;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repo);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
adapter = new RepoAdapter(repoList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
url = "https://api.github.com/users/" + message + "/repos";
parsingMethod();
}
private void parsingMethod() {
Log.d("hello1", url);
pDialog = new ProgressDialog(this);
// Showing progress dialog
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest cityReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
// Parsing json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
RepoList repoList = new RepoList();
try {
repoList.setRepoName(obj.getString("name"));
Log.d("zxcv",obj.getString("name") );
repoList.setRepoDesc(obj.getString("description"));
Log.d("zxcv",obj.getString("description") );
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setAdapter(adapter);
}
},new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(cityReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
RepoAdapter.java
public class RepoAdapter extends RecyclerView.Adapter<RepoAdapter.MyViewHolder> {
private List<RepoList> repoLists;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.repo_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
RepoList repoList = repoLists.get(position);
holder.repoName.setText(repoList.getRepoName());
holder.repoDesc.setText(repoList.getRepoDesc());
}
#Override
public int getItemCount() {
return repoLists.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView repoName, repoDesc;
public MyViewHolder(View view) {
super(view);
repoName = (TextView) view.findViewById(R.id.repoName);
repoDesc = (TextView) view.findViewById(R.id.repoDesc);
}
}
public RepoAdapter( List<RepoList> repoList) {
this.repoLists = repoList;
}
}
RepoList.java
package com.example.lenovo.boxme;
/**
* Created by lenovo on 16-12-2016.
*/
public class RepoList {
private String repoName,repoDesc;
public RepoList(String repoDesc, String repoName) {
this.repoDesc = repoDesc;
this.repoName = repoName;
}
public RepoList(){};
public String getRepoDesc() {
return repoDesc;
}
public void setRepoDesc(String repoDesc) {
this.repoDesc = repoDesc;
}
public String getRepoName() {
return repoName;
}
public void setRepoName(String repoName) {
this.repoName = repoName;
}
}
adapter = new RepoAdapter(repoList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
//notify data set after list item changed
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
RepoList repo= new RepoList();
try {
repo.setRepoName(obj.getString("name"));
Log.d("zxcv",obj.getString("name") );
repo.setRepoDesc(obj.getString("description"));
Log.d("zxcv",obj.getString("description") );
repoList.add(repo);//you missed
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChange();
you're passing in repoList when creating adapter
adapter = new RepoAdapter(repoList);
but are then creating/populating new list before calling setAdapter
RepoList repoList = new RepoList();
...
recyclerView.setAdapter(adapter);
Remove this line :
RepoList repoList = new RepoList();
Put this line in onCreate
recyclerView.setAdapter(adapter);
And after fetching the data call :
adapter.notifyDataSetChange()
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"
}
]
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);