Put 2 columns of recycler view every row - android

I would like to put 2 columns of recyclerview every row.
Right now my design is like this:
and i would like to put 2 so the scroll is not to long.
I have this view inside a fragment and I use a recyclerview adapter but I have no clue how to tell it to use its parent with, so it can fill the width of the screen. In the fragment I recive a JSON from an online database using an AsyncTask and fill in the recyclerview on the onPostExecute of the AsyncTask.
If anyone has any Idea how i can do it, I can't seem to find this anywhere
Thx!
My recyclerview Adapter:
package com.example.juanfri.seguridadmainactivity;
/**
* Created by jlira on 30/05/2017.
*/
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.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Juanfri on 29/05/2017.
*/
public class RecyclerAdapterSerie extends RecyclerView.Adapter<RecyclerAdapterSerie.SerieHolder> {
private ArrayList<Serie> mSerie;
#Override
public RecyclerAdapterSerie.SerieHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View inflatedView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recyclerview_card, viewGroup, false);
return new SerieHolder(inflatedView);
}
#Override
public void onBindViewHolder(RecyclerAdapterSerie.SerieHolder holder, int i) {
Serie itemPhoto = mSerie.get(i);
holder.bindPhoto(itemPhoto);
}
#Override
public int getItemCount() {
return mSerie.size();
}
public RecyclerAdapterSerie(ArrayList<Serie> serie) {
mSerie = serie;
}
public static class SerieHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//2
private ImageView mItemImage;
private TextView mItemDate;
private TextView mItemDescription;
private Serie serie;
//3
private static final String PHOTO_KEY = "PHOTO";
//4
public SerieHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.item_image);
mItemDate = (TextView) v.findViewById(R.id.item_date);
mItemDescription = (TextView) v.findViewById(R.id.item_description);
v.setOnClickListener(this);
}
//5
#Override
public void onClick(View v) {
/*Context context = itemView.getContext();
Intent showPhotoIntent = new Intent(context, Pelicula.class);
showPhotoIntent.putExtra(PHOTO_KEY, peli);
context.startActivity(showPhotoIntent);*/
}
public void bindPhoto(Serie mserie) {
serie = mserie;
String Nombre = mserie.getNombreSerie();
if(Nombre.length() >= 25)
{
Nombre = Nombre.substring(0,22);
Nombre = Nombre + "...";
}
Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
mItemDate.setText(Nombre);
mItemDescription.setText(Integer.toString(mserie.getIdTMDB()));
}
}
}
My fragment (where i create the recyclerview)
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
/**
* Created by jlira on 06/06/2017.
*/
public class FragmentoSeriesPelis extends Fragment {
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original/";
private ProgressDialog pDialog;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<Serie> series;
private ArrayList<Pelicula> Pelis;
private RecyclerAdapterSerie mAdapterSerie;
private RecyclerAdapterPelicula mAdapterPeli;
private int pagina;
private String url;
private Button CargarMas;
private String tipo;
private int MaxPag;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.series_pelis_layout, container, false);
view.setTag(TAG);
Bundle args = getArguments();
series = new ArrayList<>();
Pelis = new ArrayList<>();
MaxPag = 2;
pagina = args.getInt("Page");
url = args.getString("url");
tipo = args.getString("Tipo");
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewSerieshoy);
//mLinearLayoutManagerSerie = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
//recyclerViewSerie.setLayoutManager(mLinearLayoutManagerSerie);
//mAdapterSerie = new RecyclerAdapterSerie(seriesHoy);
//recyclerViewSerie.setAdapter(mAdapterSerie);
new GetSeriesHoy().execute();
CargarMas = (Button) view.findViewById(R.id.buttonCargarMas);
CargarMas.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(pagina+1<=MaxPag)
{
pagina++;
new GetSeriesHoy().execute();
}
else
{
Toast.makeText(getActivity(), "No hay mas resultados", Toast.LENGTH_LONG).show();
}
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Series de Hoy");
}
private class GetSeriesHoy extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
String aux = url+pagina;
String jsonStr = sh.makeServiceCall(aux);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
MaxPag = jsonObj.getInt("total_pages");
JSONArray contacts = jsonObj.getJSONArray("results");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
int IdSerie = i;
int idTMDB = c.getInt("id");
String nombreSerie;
String poster =URLFOTO + c.getString("poster_path");
if(tipo.equalsIgnoreCase("Series"))
{
nombreSerie = c.getString("name");
Serie nuevo = new Serie();
nuevo.setIdSerie(IdSerie);
nuevo.setNombreSerie(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
series.add(nuevo);
}
else
{
nombreSerie = c.getString("title");
Pelicula nuevo = new Pelicula();
nuevo.setIdPelicula(IdSerie);
nuevo.setNombrePelicula(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
Pelis.add(nuevo);
}
}
} catch (final JSONException e) {
Toast.makeText(getActivity(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
//Aqui Realizar la RecycleView BuildUp
if(tipo.equalsIgnoreCase("Series"))
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterSerie = new RecyclerAdapterSerie(series);
recyclerView.setAdapter(mAdapterSerie);
}else
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterPeli = new RecyclerAdapterPelicula(Pelis);
recyclerView.setAdapter(mAdapterPeli);
}
}
}
}

Replace your LinearLayoutManager for a GridLayoutManager like this:
private GridLayoutManager mGridLayoutManager;
// ...
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
Then you can use it the same way as the LinearLayoutManager.

Related

I found Error " E/RecyclerView: No adapter attached; skipping layout "

Everything works, but after I check the log it shows:
"E/RecyclerView: No adapter attached; skipping layout ".
My home fragment code:
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
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.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
I saw another question similar to this, that said to attach the adapter before running other threads but I don't believe I have any other threads running in this activity.
You start a new thread in this line:
new LoadLatestNews().execute(Constant.URL_LATEST);
and it is executed before control reaches:
recyclerView.setAdapter(adapterRecent);
This however should not be the problem you have since AsyncTask publishes to the UIThread.
Instead you should set an empty adapter in onCreateView and update it with adapterRecent.notifyDataSetChanged(); once you have loaded your data.

Can't open fragment from RecyclerView item Click

Hi I have a simple app that features a recyclerView with list items (each representing a "Movie" object. The content for the movie list items is generated from an API call (themoviedb.org). I'm trying to open a "detail fragment" by clicking on a recyclerView list item. I want all of the content from the Movie item clicked to appear in the next fragment as well. Right now when I click the list item, nothing happens. No crash, even. I thought I had set up the listener interface correctly, but maybe that's the problem. Can anyone see where I'm going wrong? Thanks in advance.
Here is the Fragment where the RecyclerView (movie list) first appears:
public class ResultsFragment extends Fragment {
private RecyclerView mRecyclerView;
Movie_Results_Adapter results_adapter;
ArrayList<Movie> movieList;
onMovieSelectedListener listener;
public ResultsFragment(){
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout_1, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);
mRecyclerView.setVisibility(View.VISIBLE);
results_adapter = new Movie_Results_Adapter(movieList, listener);
listener = new onMovieSelectedListener() {
#Override
public void onMovieSelected(Movie selectedMovie) {
Intent launchIntent = new Intent(getContext(), MovieDetailActivity.class);
launchIntent.putExtra(MovieDetailActivity.EXTRA_MOVIE, "movie");
Log.d("PaulsApp", selectedMovie + "");
launchIntent.putExtra(MovieDetailActivity.NEW_EXTRA, (Serializable) selectedMovie);
startActivity(launchIntent);
}
};
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(results_adapter);
Log.d("TAGG", "AAAH" + movieList.toString());
return rootView;
}
public void parseJson(String jsonToParse) throws JSONException {
JSONObject responseObject= new JSONObject(jsonToParse);
JSONArray resultsArray = responseObject.getJSONArray("results");
for(int i = 0; i < resultsArray.length(); i++){
JSONObject movie = resultsArray.getJSONObject(i);
String movieName = movie.getString("title");
String movieReleaseDate = movie.getString("release_date");
String movieScore = movie.getString("vote_average");
String moviePopularity = movie.getString("vote_count");
String movieImage = movie.getString("poster_path");
String movieDescription = movie.getString("overview");
Movie movie1 = new Movie(movieName, movieReleaseDate, movieScore, moviePopularity, movieImage, movieDescription);
movieList.add(movie1);
}
}
#Override
public void setArguments(Bundle args) {
movieList = new ArrayList<>();
String arguments = args.getString("JSON_STRING");
try {
parseJson(arguments);
} catch (JSONException e) {
e.printStackTrace();
}
super.setArguments(args);
}
public interface onMovieSelectedListener{
public void onMovieSelected(Movie selectedMovie);
}
}
Here is the RecyclerView Adapter for the "results" fragment:
public class Movie_Results_Adapter extends RecyclerView.Adapter<Movie_Results_Adapter.ResultViewHolder>{
ArrayList<Movie> MovieListArray;
ResultsFragment.onMovieSelectedListener listener;
private Activity mActivity;
public class ResultViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView titleText;
TextView dateText;
TextView scoreText;
TextView popularityText;
ImageView movieImage;
public Movie movie;
public ResultViewHolder(View itemView){
super(itemView);
titleText = (TextView) itemView.findViewById(R.id.movie_title_text);
dateText = (TextView) itemView.findViewById(R.id.movie_date_text);
scoreText = (TextView) itemView.findViewById(R.id.movie_score_text);
popularityText = (TextView) itemView.findViewById(R.id.movie_popularity_text);
movieImage = (ImageView) itemView.findViewById(R.id.movie_image);
}
#Override
public void onClick(View view) {
if (listener != null) {
listener.onMovieSelected(MovieListArray.get(getAdapterPosition()));
Toast.makeText(view.getContext(), "clicked: " + MovieListArray.get(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
}
public Movie_Results_Adapter(ArrayList<Movie> movieList, ResultsFragment.onMovieSelectedListener listener){
MovieListArray = movieList;
this.listener = listener;
}
#Override
public ResultViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_result_list_item, parent, false);
ResultViewHolder vh = new ResultViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ResultViewHolder holder, int position) {
holder.titleText.setText(MovieListArray.get(position).getmTitle());
Log.d("TAGG", MovieListArray.toString());
holder.dateText.setText("Released "+MovieListArray.get(position).getmReleaseYear());
holder.scoreText.setText("TMDB Score: "+MovieListArray.get(position).getmScore());
holder.popularityText.setText(MovieListArray.get(position).getmPopularity()+" votes");
Context context = holder.movieImage.getContext();
Picasso.with(context).load(Constants.TMDB_POSTER+MovieListArray.get(position).getmImage()).into(holder.movieImage);
}
#Override
public int getItemCount() {
return MovieListArray.size();
}
}
Here is the detail fragment (and accompanying activity):
package jetsetpaul.movienerd;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
/**
* Created by pauljoiner on 8/17/16.
*/
public class MovieDetailFragment extends Fragment {
public String movieTitle;
public String movieImage;
public String movieDate;
public String movieDescription;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail_fragment, container, false);
TextView mTitleText = (TextView) rootView.findViewById(R.id.movie_detail_title);
ImageView mMovieImage = (ImageView) rootView.findViewById(R.id.movie_detail_image);
TextView mDateText = (TextView) rootView.findViewById(R.id.movie_detail_release_date);
TextView mDescriptionText = (TextView) rootView.findViewById(R.id.movie_detail_description);
mTitleText.setText(movieTitle);
mDateText.setText(movieDate);
mDescriptionText.setText(movieDescription);
Context context = mMovieImage.getContext();
Picasso.with(context).load(Constants.TMDB_POSTER+movieImage);
return rootView;
}
public void setMovieTitle(String title){
this.movieTitle = title;
}
public void setMovieImage(String image){
this.movieImage = image;
}
public void setMovieDate(String date){
this.movieDate = date;
}
public void setMovieDescription(String description){
this.movieDescription = description;
}
}
Activity:
package jetsetpaul.movienerd;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
/**
* Created by pauljoiner on 8/17/16.
*/
public class MovieDetailActivity extends AppCompatActivity {
public static final String EXTRA_MOVIE = "movie";
public static final String NEW_EXTRA = "movie2";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
Intent i = getIntent();
if(i.hasExtra(NEW_EXTRA)) {
Log.d("PaulsApp", "Had Extra!");
//set the text in my fragment
Movie movie = (Movie) i.getSerializableExtra(NEW_EXTRA);
Fragment newFragment = new MovieDetailFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_fragment, newFragment);
transaction.commit();
((MovieDetailFragment) newFragment).setMovieTitle(movie.getmTitle());
((MovieDetailFragment) newFragment).setMovieImage(movie.getmImage());
((MovieDetailFragment) newFragment).setMovieDate(movie.getmReleaseYear());
((MovieDetailFragment) newFragment).setMovieDescription(movie.getmDescription());
}
}
}
I can post more code if necessary. Thanks again!
Your listener needs to be created before your results_adapter
listener = new onMovieSelectedListener() {
#Override
public void onMovieSelected(Movie selectedMovie) {
Intent launchIntent = new Intent(getContext(), MovieDetailActivity.class);
launchIntent.putExtra(MovieDetailActivity.EXTRA_MOVIE, "movie");
Log.d("PaulsApp", selectedMovie + "");
launchIntent.putExtra(MovieDetailActivity.NEW_EXTRA, (Serializable) selectedMovie);
startActivity(launchIntent);
}
};
results_adapter = new Movie_Results_Adapter(movieList, listener);
To be honest though, it would be best for your fragment to implement the listener (interface) instead of having to create it by using new onMovieSelectedListener().

Android: List not pass to RecyclerView

I'm passing a value from MainActivity.class to this fragment ResultFrag.class. In this class, it's supposed to display the places that is within the requested value from the user's current location.
The json return is correct.
I also tried to debug and display the item in the myList through Logcat and it is fine. So meaning that the json is parsed correctly and it's being added to the myList.
myAdapter = new MyAdapter(getActivity(), getTheList());
This particular line that pass the list to the custom adapter; I don't think it's getting the list from the getTheList() method. Because I tried debugging using below codes by putting it in onCreateView but it's not logging anything:
for (int b = 0; b < getTheList().size(); b++) {
Log.d("list: ", Integer.toString(b) + " : " + getTheList().get(b).getPlace());
}
Can anyone help? I've been working on this since yesterday.
import android.location.Location;
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.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResultFrag extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
double latitude, longitude;
String lat, lng;
private Bundle bundle;
private String data;
private static final String TAG_URL_DISTANCE = "///remove link///";
private static final String LOG_DISTANCE = ResultFrag.class.getSimpleName();
private MyAdapter myAdapter;
private RecyclerView recyclerView;
List<GetterSetter> myList = new ArrayList<>();
private static final String TAG = ResultFrag.class.getSimpleName();
private static final int REQUEST_CODE = 1000;
Location location;
GoogleApiClient googleClient;
public ResultFrag() {
}
public void searchPlace(final String dist, final String latitude, final String longitude) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, TAG_URL_DISTANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(LOG_DISTANCE, response.toString());
try {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setId(obj.getString("id"));
getterSetter.setPlace(obj.getString("name"));
getterSetter.setDistance(obj.getInt("distance"));
myList.add(getterSetter);
}
for (int b = 0; b < getTheList().size(); b++) {
Log.d("list: ", Integer.toString(b) + " : " + getTheList().get(b).getPlace());
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "JSONException: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(LOG_DISTANCE, "Volley Error: " + error.getMessage());
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("dist", dist);
params.put("latitude", latitude);
params.put("longitude", longitude);
return params;
}
};
Volley.newRequestQueue(getContext()).add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.result_frag, container, false);
bundle = this.getArguments();
data = bundle.getString(MainActivity.option);
if (checkGooglePlayServices()) {
buildGoogleClient();
}
lat = getLatitude();
lng = getLongitude();
Log.d("radius", data);
Log.d("latitude", lat);
Log.d("longitude", lng);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
myAdapter = new MyAdapter(getActivity(), getTheList());
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
/* recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
}
})
);*/
return rootView;
}
private boolean checkGooglePlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
// Show error
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), REQUEST_CODE).show();
} else {
Toast.makeText(getContext(),
"No GPS",
Toast.LENGTH_LONG).show();
}
return false;
}
return true;
}
protected synchronized void buildGoogleClient() {
googleClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onStart() {
super.onStart();
if (googleClient != null) {
googleClient.connect();
}
}
#Override
public void onResume() {
super.onResume();
checkGooglePlayServices();
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(googleClient);
searchPlace(data, getLatitude(), getLongitude());
Toast.makeText(getContext(), getLatitude() + ", " + getLongitude(), Toast.LENGTH_LONG).show();
}
public List<GetterSetter> getTheList() {
return myList;
}
public String getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return String.valueOf(latitude);
}
public String getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return String.valueOf(longitude);
}
#Override
public void onConnectionSuspended(int i) {
googleClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
}
MyAdapter.class
import android.content.Context;
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.Collections;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
List<GetterSetter> data = Collections.emptyList();
private LayoutInflater layoutInflater;
private Context context;
public MyAdapter (Context context, List<GetterSetter> data) {
this.context = context;
this.data = data;
layoutInflater = layoutInflater.from(context);
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.mylist, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
// Get event data
GetterSetter current = data.get(position);
holder.id.setText(current.getId());
holder.place.setText(current.getPlace());
holder.distance.setText("Distance: " + String.valueOf(current.getDistance()) + " km");
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView place;
TextView distance;
public MyViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.placeId);
place = (TextView) itemView.findViewById(R.id.name);
distance = (TextView) itemView.findViewById(R.id.distance);
}
}
}
Did you fix it in the meantime? What I see is that you actually share the list between the adapter and the Fragment. And you make changes (add items) to the list after the adapter was constructed. But you do not call notfyDatasetChanged() on the adapter. Add that call once you are done with applyting changes to the list.
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setId(obj.getString("id"));
getterSetter.setPlace(obj.getString("name"));
getterSetter.setDistance(obj.getInt("distance"));
myList.add(getterSetter);
}
myAdapter.notfyDatasetChanged()

Blank ListView in Android

I'm making a parse json app and i've got an issue !
I've got these codes :
Temps.java :
package model;
public class Temps {
private String direction;
private String ligne;
private String temps;
public Temps() {
}
public Temps(String direction, String ligne, String temps) {
this.direction = direction;
this.ligne = ligne;
this.temps = temps;
}
public String getDirection() {
return direction;
}
public void setDirection(String thumbnailUrl) {
this.direction = thumbnailUrl;
}
public String getTemps() {
return temps;
}
public void setTemps(String temps) {
this.temps = temps;
}
public String getLigne() {
return ligne;
}
public void setLigne(String ligne) {
this.ligne = ligne;
}
}
TempsActivity.java :
package activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.pierre.tan.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import adapter.CustomListAdapterTemps;
import app.AppController;
import model.Temps;
public class TempsActivity extends ActionBarActivity {
private Toolbar mToolbar;
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private List<Temps> directionList = new ArrayList<Temps>();
private ListView listView2;
private CustomListAdapterTemps adapter;
private SwipeRefreshLayout swipeLayout;
private Menu menu;
private MenuInflater inflater;
HashMap<String, String> lieumap = new HashMap<String, String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_temps, container, false);
// Inflate the layout for this fragment
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
System.out.println(intent.getExtras().getString("text") + " Test Test ");
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(getParent(), directionList);
listView2.setAdapter(adapter);
// Showing progress dialog before making http request
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Toast.makeText(getApplication(), "Rechargement...", Toast.LENGTH_SHORT).show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// 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());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
swipeLayout.setRefreshing(false);
}
});
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_search) {
String title = getString(R.string.app_name);
Fragment fragment = null;
fragment = new ArretsFragment();
title = "Rechercher";
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temps);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(this, directionList);
listView2.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// 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());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
}
And CustomListViewAdapterTemps.java :
package adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.example.pierre.tan.R;
import java.util.List;
import app.AppController;
import model.Temps;
public class CustomListAdapterTemps extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Temps> directionItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterTemps(Activity activity, List<Temps> directionItems) {
this.activity = activity;
this.directionItems = directionItems;
}
#Override
public int getCount() {
return directionItems.size();
}
#Override
public Object getItem(int location) {
return directionItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rowtemps, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView direction = (TextView) convertView.findViewById(R.id.direction);
TextView ligne = (TextView) convertView.findViewById(R.id.ligne);
TextView temps = (TextView) convertView.findViewById(R.id.temps);
// getting movie data for the row
Temps m = directionItems.get(position);
// title
direction.setText(m.getDirection());
ligne.setText(m.getLigne());
temps.setText(m.getTemps());
return convertView;
}
}
I don't understand why I get a Blank ListView because the url json work and in the console we can see just the json Request with the data. If someone can help me it would be very nice!
That's because your directionList is empty. In your loops, where you parse JSON, you're creating your Temps object:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
but you're not adding them to your directionsList. Add this line just after the above:
directionList.add(temps);
Hi i think that you are not adding your response to the list, please try this:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
directionList.add(temps);

AsyncTask is not functioning on my second fragment connected to Mysql database on swipe

I have an app with three fragments which I need to Asynctask every swipe. But it seems that the Asynctask runs only on the opening of the app. But when it's already created, only the first and third fragment functions well when it comes to AsyncTask the second doesn't change when I update the database.
This is my MainActivity.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
/**
* Created by Lemueloodle on 2/12/14.
*/
public class MainActivity extends FragmentActivity{
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.viewPager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("FirstFragment").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("SecondFragment").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("ThirdFragment").setTabListener(tabListener));
}
}
This is my TabPagerAdapter
package com.example.RadarOperationMonitoringSystem;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Lemueloodle on 2/12/14.
*/
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch(i) {
case 0:
return new FirstFragment();
case 1:
return new SecondFragment();
case 2:
return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3; //No of Tabs
}
}
This is my FirstFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View first = inflater.inflate(R.layout.first_frag, container, false);
// get the listview
((TextView)first.findViewById(R.id.textView)).setText("SecondFragment");
return first;
}
}
SecondFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SecondFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/networkstatus.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_NETSTAT1 = "netlink_stats1";
private static final String TAG_FORECAST1 = "forcasting_stats1";
private static final String TAG_MDSI1 = "pagasa_mdsi_stats1";
private static final String TAG_PNOAH1 = "projectnoah_stats1";
....so on
String site1 = "";
String netstat1 = "";
String forecast1 = "";
String mdsi1 = "";
String pnoah1 = "";
.....so on
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View second = inflater.inflate(R.layout.second_frag, container, false);
((TextView)second.findViewById(R.id.textView)).setText("SecondFragment");
return second;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// We set clear listener
new GetContactsb().execute();
}
public class GetContactsb extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler2.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
netstat1 = c.getString(TAG_NETSTAT1);
forecast1 = c.getString(TAG_FORECAST1);
mdsi1 = c.getString(TAG_MDSI1);
pnoah1 = c.getString(TAG_PNOAH1);
..so on
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_NETSTAT1, netstat1);
contact.put(TAG_FORECAST1, forecast1);
contact.put(TAG_MDSI1, mdsi1);
contact.put(TAG_PNOAH1, pnoah1);
...so on
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item2, new String[] { TAG_SITENAME1,TAG_SITENAME2,TAG_SITENAME3,TAG_SITENAME4,
TAG_SITENAME5,TAG_SITENAME6,TAG_SITENAME7},
new int[] { R.id.sitename1, R.id.sitename2, R.id.sitename3, R.id.sitename4,R.id.sitename5,
R.id.sitename6, R.id.sitename7}){
//This will change the color of the value depending on the limit given
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView netstata = (TextView) view.findViewById(R.id.netstat1);
TextView forecasta = (TextView) view.findViewById(R.id.forecast1);
TextView mdsia = (TextView) view.findViewById(R.id.pmdsi1);
TextView pnoaha = (TextView) view.findViewById(R.id.pnoah1);
....so on
//1 - Red = No link
//2 - Yellow = Delay
//3 - Green = Good
//Radar 1
//Network Link Status
if (netstat1.equals("1")){
netstata.setText("No-Link");
netstata.setTextColor(getResources().getColor(R.color.red));
}
else if(netstat1.equals("2")){
netstata.setText("Delay");
netstata.setTextColor(getResources().getColor(R.color.yellow));
}
else if(netstat1.equals("3")){
netstata.setText("Good");
netstata.setTextColor(getResources().getColor(R.color.green));
}
...so on to Radar 7
return view;
};
};
// updating listviews
setListAdapter(adapter);
}
}
}
ThirdFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ThirdFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/energyreadings.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_FREQUENCY1 = "Frequency1";
private static final String TAG_ACCURRENT1 = "AC_Voltage1";
private static final String TAG_ACVOLTAGE1 = "AC_Current1";
private static final String TAG_FSTAT1 = "Flimitstat1";
private static final String TAG_VSTAT1 = "Vlimitstat1";
private static final String TAG_CSTAT1 = "Climitstat1";
...so on
// contacts JSONArray
JSONObject c = null;
String site1 = "";
String freq1 = "";
String curr1 = "";
String volts1 = "";
String fstat1 = "";
String vstat1 = "";
String cstat1 = "";
.. so on
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View third = inflater.inflate(R.layout.third_frag, container, false);
((TextView)third.findViewById(R.id.textView)).setText("ThirdFragment");
return third;
}
public void StartProgress() {
new GetContactsc().execute();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// We set clear listener
new GetContactsc().execute();
}
public class GetContactsc extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler3 sh = new ServiceHandler3();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler3.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
freq1 = c.getString(TAG_FREQUENCY1);
curr1 = c.getString(TAG_ACCURRENT1);
volts1 = c.getString(TAG_ACVOLTAGE1);
fstat1 = c.getString(TAG_FSTAT1);
vstat1 = c.getString(TAG_VSTAT1);
cstat1 = c.getString(TAG_CSTAT1);
...so on
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_FREQUENCY1, freq1);
contact.put(TAG_ACCURRENT1, curr1);
contact.put(TAG_ACVOLTAGE1, volts1);
contact.put(TAG_FSTAT1, fstat1);
contact.put(TAG_VSTAT1, vstat1);
contact.put(TAG_CSTAT1, cstat1);
...so on
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_SITENAME1, TAG_FREQUENCY1, TAG_ACCURRENT1,
TAG_ACVOLTAGE1,TAG_SITENAME2, TAG_FREQUENCY2, TAG_ACCURRENT2,
TAG_ACVOLTAGE2,TAG_SITENAME3, TAG_FREQUENCY3, TAG_ACCURRENT3,
TAG_ACVOLTAGE3, TAG_SITENAME4, TAG_FREQUENCY4, TAG_ACCURRENT4,
TAG_ACVOLTAGE4, TAG_SITENAME5, TAG_FREQUENCY5, TAG_ACCURRENT5,
TAG_ACVOLTAGE5, TAG_SITENAME6, TAG_FREQUENCY6, TAG_ACCURRENT6,
TAG_ACVOLTAGE6, TAG_SITENAME7, TAG_FREQUENCY7, TAG_ACCURRENT7,
TAG_ACVOLTAGE7},
new int[] { R.id.sitename1, R.id.frequency1,
R.id.accurrent1, R.id.acvoltage1, R.id.sitename2, R.id.frequency2,
R.id.accurrent2, R.id.acvoltage2, R.id.sitename3, R.id.frequency3,
R.id.accurrent3, R.id.acvoltage3, R.id.sitename4, R.id.frequency4,
R.id.accurrent4, R.id.acvoltage4, R.id.sitename5, R.id.frequency5,
R.id.accurrent5, R.id.acvoltage5, R.id.sitename6, R.id.frequency6,
R.id.accurrent6, R.id.acvoltage6, R.id.sitename7, R.id.frequency7,
R.id.accurrent7, R.id.acvoltage7}){
//This will change the color of the value depending on the limit given
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView freqa = (TextView) view.findViewById(R.id.frequency1);
TextView voltsa = (TextView) view.findViewById(R.id.acvoltage1);
TextView curra = (TextView) view.findViewById(R.id.accurrent1);
... so on
//Radar 1
if (fstat1.equals("1")){
freqa.setTextColor(getResources().getColor(R.color.green));
}
else if(fstat1.equals("2")){
freqa.setTextColor(getResources().getColor(R.color.red));
}
if(vstat1.equals("1")){
voltsa.setTextColor(getResources().getColor(R.color.green));
}
else if(vstat1.equals("2")){
voltsa.setTextColor(getResources().getColor(R.color.red));
}
if(cstat1.equals("1")){
curra.setTextColor(getResources().getColor(R.color.green));
}
else if(cstat1.equals("2")){
curra.setTextColor(getResources().getColor(R.color.red));
}
... so on to Radar 7
return view;
};
};
// updating listviews
setListAdapter(adapter);
}
}
}
I had the same problem like u. I think that problem is because ViewPager saves states of last and next pager, and building them before they come. Try setting tab.setOffscreenPageLimit(0). By doing that u may encounter problem that when ever u swipe pages, pages will be rebuild.

Categories

Resources