I have movie android app which contain recycleview with it's adapter and network it with api json data so when I run the app it installed and open but I get a white empty contain there is no data (images) in recycleview and don't now why
this is my code:
Main Activity:
public class MainActivity extends AppCompatActivity {
RecyclerViewAdapter mAdapter;
RecyclerView mMoviesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMoviesList = (RecyclerView) findViewById(R.id.rv_movies);
GridLayoutManager LayoutManager = new GridLayoutManager(this, 2);
mMoviesList.setLayoutManager(LayoutManager);
mMoviesList.setHasFixedSize(true);
mAdapter = new RecyclerViewAdapter(this);
mMoviesList.setAdapter(mAdapter);
loadMoviesData();
}
private void loadMoviesData() {
showMovieDataView();
new FetchMoviesTask().execute();
}
private void showMovieDataView() {
mMoviesList.setVisibility(View.VISIBLE);
}
public class FetchMoviesTask extends AsyncTask<String, Void, ArrayList<MovieItem>> {
#Override
protected ArrayList<MovieItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String movie = params[0];
URL moviesRequestUrl = NetworkUtils.buildUrl(movie);
try {
String jsonMovieResponse = NetworkUtils.getResponseFromHttpUrl(moviesRequestUrl);
ArrayList<MovieItem> simpleJsonMovieData = OpenMovieJsonUtils.getSimpleMovieStringsFromJson(MainActivity.this, jsonMovieResponse);
return simpleJsonMovieData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(ArrayList<MovieItem> movieData) {
if (movieData != null) {
showMovieDataView();
mAdapter.setMovieData(movieData);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sort, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.most_popular) {
loadMoviesData();
return true;
}
if (id == R.id.top_rated) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter of RecycleView:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
ArrayList<MovieItem> mMoviesItems;
private Context context;
public RecyclerViewAdapter(MainActivity mainActivity) {
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
context = viewGroup.getContext();
int layoutIdForListItem = R.layout.movie_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.MoviePopularity.setText(String.valueOf(mMoviesItems.get(position).getPopularity()));
Picasso.with(this.context).load(mMoviesItems.get(position).getPhoto()).into(holder.MoviePoster);
holder.MovieName.setText(mMoviesItems.get(position).getName());
}
#Override
public int getItemCount() {
if (null == mMoviesItems) return 0;
return mMoviesItems.size();
}
public void setMovieData(ArrayList<MovieItem> movieData) {
mMoviesItems = movieData;
notifyDataSetChanged();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView MoviePopularity;
ImageView MoviePoster;
TextView MovieName;
public RecyclerViewHolder(View itemView) {
super(itemView);
MoviePopularity = (TextView)itemView.findViewById(R.id.movie_popularity);
MoviePoster = (ImageView)itemView.findViewById(R.id.iv_item_movie);
MovieName = (TextView)itemView.findViewById(R.id.movie_name);
}
}
}
Network:
public final class NetworkUtils {
private static final String TAG = NetworkUtils.class.getSimpleName();
private static final String MOVIES_BASE_URL = "https://api.themoviedb.org/3/movie/";
private static final String MOVIES_URL = MOVIES_BASE_URL;
private static final String apiKey = "36666cbb5d7e20041e705d1b2c4e7a79";
final static String SORT_Order = "popular";
final static String API_PARAM = "api_key";
public static URL buildUrl(String MoviesQuery) {
Uri builtUri = Uri.parse(MOVIES_URL).buildUpon()
.appendPath(SORT_Order)
.appendQueryParameter(API_PARAM, apiKey)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Log.v(TAG, "Built URI " + url);
return url;
}
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
}
JSON:
public final class OpenMovieJsonUtils {
public static ArrayList<MovieItem> getSimpleMovieStringsFromJson(Context context, String moviesJsonString)
throws JSONException {
final String RESULTS = "results";
final String POPULARITY = "popularity";
final String POSTER_PATH = "poster_path";
final String ORIGINAL_TITLE = "original_title";
ArrayList<MovieItem> parsedMovieData = new ArrayList<MovieItem>();
JSONObject moviesObject = new JSONObject(moviesJsonString);
JSONArray moviesArray = moviesObject.getJSONArray(RESULTS);
for (int i = 0; i < moviesArray.length(); i++) {
double popularity;
String poster_path;
String original_title;
moviesObject = moviesArray.getJSONObject(i);
popularity = moviesObject.getDouble(POPULARITY);
poster_path = moviesObject.getString(POSTER_PATH);
original_title = moviesObject.getString(ORIGINAL_TITLE);
parsedMovieData.add(new MovieItem(popularity, poster_path, original_title));
}
return parsedMovieData;
}
}
custom class:
public class MovieItem {
private double popularity;
private String photo;
private String name;
public MovieItem(double popularity, String poster_path, String original_title) {
this.popularity = popularity;
this.photo = photo;
this.name = name;
}
public double getPopularity() { return popularity; }
public String getPhoto() { return photo; }
public String getName() { return name; }
}
where is the problem ?
Related
This is Fist time i'm asking question!! so bear with me.
The application is project(popular movie stage 2) from udacity where i need to fetch info of movies like tilte or poster_path or backdrop_path.
so when i fetch data from json it works perfectly fine but when i add another argument String backdrop in my Movies.java class.then getmBackdrop() shows empty and i couldn't get the data of backdrop overview and vote.but if i delete backdrop from constructor than it works fine. i dont know what is happening please help me.
this is Movies.javaclass
public class Movies implements Parcelable {
//Movies Data
public long mID;
private String mPosterPath;
private String mReleaseDate;
private String mTitle;
private String mVote;
private String mOverview;
private String mBackdrop;
private ArrayList<Trailers> trailers;
private ArrayList<Reviews> reviews;
public Movies() {
}
public Movies(String title, String releaseDate, String posterPath,
String backdrop,String vote, String overview) {
// this.mID=id;
this.mTitle = title;
this.mReleaseDate = releaseDate;
this.mPosterPath = posterPath;
this.mBackdrop = backdrop;
this.mVote = vote;
this.mOverview = overview;
this.trailers = new ArrayList<>();
this.reviews = new ArrayList<>();
}
public long getID(){ return mID ;}
public String getmBackdrop() { return mBackdrop; }
public String getPosterPath() {
return mPosterPath;
}
public String getTitle() {
return mTitle;
}
public String getReleaseDate() {
return mReleaseDate;
}
public String getOverview() {
return mOverview;
}
public String getVote() {
return mVote +"/10";
}
public void setTrailers(ArrayList<Trailers> trailers) {
this.trailers = trailers;
}
public void setReviews(ArrayList<Reviews> reviews) {
this.reviews = reviews;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(mID);
dest.writeString(mTitle);
dest.writeString(mReleaseDate);
dest.writeString(mPosterPath);
dest.writeValue(mBackdrop);
dest.writeString(mVote);
dest.writeString(mOverview);
}
protected Movies(Parcel in) {
mID = in.readLong();
mTitle = in.readString();
mReleaseDate = in.readString();
mPosterPath = in.readString();
mBackdrop = in.readString();
mVote = in.readString();
mOverview = in.readString();
}
public static final Creator<Movies> CREATOR = new Creator<Movies>() {
public Movies createFromParcel(Parcel source) {
return new Movies(source);
}
public Movies[] newArray(int size) {
return new Movies[size];
}
};
}
MoviepediaJsonUtils.java where i'm parsing data
public class MoviepediaJsonUtils {
public static ArrayList<Movies> getParseMovieJson(String jsonMovies) throws JSONException {
final String IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";
final String BACKDROP_URL= "https://image.tmdb.org/t/p/w1280/";
JSONObject movieJson = new JSONObject(jsonMovies);
JSONArray movieArray = movieJson.getJSONArray("results");
ArrayList<Movies> movieArrayList = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movieObject = movieArray.getJSONObject(i);
long id = movieObject.getLong("id");
String title = movieObject.getString("title");
String release_date = movieObject.getString("release_date");
String poster_path = movieObject.getString("poster_path");
String backdrop = movieObject.getString("backdrop_path");
String vote_average = movieObject.getString("vote_average");
String overview = movieObject.getString("overview");
Movies movies = new Movies(title, release_date,
IMAGE_BASE_URL + poster_path, BACKDROP_URL+backdrop,vote_average, overview);
movieArrayList.add(movies);
}
return movieArrayList;
}
public static String getResponseFromHttpUrl(InputStream stream) throws IOException {
Scanner scanner = new Scanner(stream);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
}
}
MainActivityFragments.java
public class MainActivityFragments extends Fragment {
private static final int COLUMN = 2;
private RecyclerView mRecyclerView;
SharedPreferences mSettings;
GridLayoutManager mGridLayoutManager;
private SharedPreferences.Editor mEditor;
private static final String SHARED_KEY_SORT = "sort";
private static final String POPULARITY = "popular";
private static final String RATINGS = "top_rated";
public static String[] backdrop;
public static final String SAVE_LAST_UPDATE_ORDER = "save_last_update_order";
private String mLastUpdateOrder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.poster_fragment, container, false);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mGridLayoutManager = new GridLayoutManager(getActivity(),2, LinearLayoutManager.VERTICAL,false);
}else{
mGridLayoutManager = new GridLayoutManager(getActivity(), 4,LinearLayoutManager.VERTICAL,false);
}
mRecyclerView = view.findViewById(R.id.rv_movies);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSettings.edit();
mEditor.apply();
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), new ArrayList<Movies>()));
return view;
}
#Override
public void onStart() {
super.onStart();
if (needToUpdateUi()) {
updateUi();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVE_LAST_UPDATE_ORDER, mLastUpdateOrder);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mLastUpdateOrder = savedInstanceState.getString(SAVE_LAST_UPDATE_ORDER);
}
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
updateUi();
}
// OnCreateOptionMenues will be here
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.poster_fragment, menu);
Drawable drawable = menu.findItem(R.id.icon).getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
}
}
// OnOptionitemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.poularity:
mEditor.putString(SHARED_KEY_SORT, POPULARITY);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
case R.id.top_rated:
mEditor.putString(SHARED_KEY_SORT, RATINGS);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
if (sortBy.equals(POPULARITY)) {
menu.findItem(R.id.poularity).setChecked(true);
} else {
menu.findItem(R.id.top_rated).setChecked(true);
}
}
private void updateUi() {
if (isNetworkAvailable()) {
OnTaskCompleted taskCompleted = new OnTaskCompleted() {
#Override
public void onFetchMoviesTaskCompleted(ArrayList<Movies> movies) {
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), movies));
}
};
MoviesAsyncTask moviesAsyncTask = new MoviesAsyncTask(taskCompleted);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
mLastUpdateOrder = sortBy;
moviesAsyncTask.execute(sortBy);
} else {
Toast.makeText(this.getActivity().getApplicationContext(), "Need Internet Connection", Toast.LENGTH_LONG).show();
}
}
private boolean needToUpdateUi() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (!mLastUpdateOrder.equals(prefs.getString(SHARED_KEY_SORT, POPULARITY))) {
return true;
} else {
return false;
}
}
//Based on a stackoverflow snippet
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) this.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
DeatailActivityFragment
public class DetailActivityFragments extends Fragment {
private final String TAG = this.getClass().getSimpleName();
private static final String PARCEL_KEY = "movie_parcel";
Movies mMovie;
OnTaskCompleted mlistener;
ArrayList<Trailers> mTrailers;
ArrayList<Reviews> mReviews;
ImageView poster;
ImageView backdrop;
public DetailActivityFragments() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_detail_fragment,
container, false);
Movies parceableExtra = getActivity().getIntent().getParcelableExtra(PARCEL_KEY);
poster = view.findViewById(R.id.poster_IV);
TextView title = view.findViewById(R.id.title_TV);
TextView releaseDate = view.findViewById(R.id.relaesedate_TV);
TextView vote = view.findViewById(R.id.vote_TV);
TextView overView = view.findViewById(R.id.overview_TV);
backdrop = view.findViewById(R.id.image_id);
final FloatingActionButton fab1 = view.findViewById(R.id.fab);
//String gotPosition = getStringExtra("position");
//intGotPosition=Integer.parseInt(gotPosition);
// String url = "https://image.tmdb.org/t/p/w1280"+DetailActivityFragments.backdrop[intGotPosition];
title.setText(parceableExtra.getTitle());
releaseDate.setText(parceableExtra.getReleaseDate());
vote.setText(parceableExtra.getVote());
overView.setText(parceableExtra.getOverview());
Picasso.with(view.getContext()).load(parceableExtra.getPosterPath())
.into(poster);
Picasso.with(this.getActivity()).load( parceableExtra.getmBackdrop())
.error(R.drawable.sam).into(backdrop);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent i=new Intent(context , TrailerActivity.class);
startActivity(i);
}
});
return view;
}
}
MoviesAsyncTask.java
public class MoviesAsyncTask extends AsyncTask<String, Void, ArrayList<Movies>> {
private final String LOG_TAG = MoviesAsyncTask.class.getSimpleName();
final String MY_API_KEY = "removed deliberately";
ArrayList<Movies> mMovies;
private OnTaskCompleted mListener;
public MoviesAsyncTask(OnTaskCompleted listener) {
mListener = listener;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Movies> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
final String MOVIEDB_BASE_URL =
"https://api.themoviedb.org/3/movie/";
final String APIKEY = "api_key";
Uri builtUri = Uri.parse(MOVIEDB_BASE_URL).buildUpon()
.appendPath(params[0])
.appendQueryParameter(APIKEY, MY_API_KEY)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String response = null;
try {
response = MoviepediaJsonUtils.getResponseFromHttpUrl(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
return MoviepediaJsonUtils.getParseMovieJson(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Movies> movies) {
super.onPostExecute(movies);
mListener.onFetchMoviesTaskCompleted(movies);
mMovies = movies;
}
}
Try to add your string at the end of your class or remove all the parcelable generated code, add your string, then apply again the parcelable implementation.
This happens because you're not updating the parcel methods.
I'v tried to create a movies app so I create recycleview to display the poster in gridlayout using networking with api json data
now the app fetch the name of movies and it's popularity without problems but can't fetch the poster and when I debug the app I found the value of poster null when it comes to onbindviewholder why that?
this is the adapter of recycleview:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
ArrayList<MovieItem> mMoviesItems;
private Context context;
public RecyclerViewAdapter() {
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
public final TextView MoviePopularity;
public final ImageView MoviePoster;
public final TextView MovieName;
public RecyclerViewHolder(View view) {
super(view);
MoviePopularity = (TextView)itemView.findViewById(R.id.movie_popularity);
MoviePoster = (ImageView)itemView.findViewById(R.id.iv_item_movie);
MovieName = (TextView)itemView.findViewById(R.id.movie_name);
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
context = viewGroup.getContext();
int layoutIdForListItem = R.layout.movie_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.MoviePopularity.setText(String.valueOf(mMoviesItems.get(position).getPopularity()));
Picasso.with(this.context).load(mMoviesItems.get(position).getPhoto()).into(holder.MoviePoster);
holder.MovieName.setText(String.valueOf(mMoviesItems.get(position).getName()));
}
#Override
public int getItemCount() {
if (null == mMoviesItems)
return 0;
else {
return mMoviesItems.size();
}
}
public void setMovieData(ArrayList<MovieItem> movieData) {
mMoviesItems = movieData;
notifyDataSetChanged();
}
}
and this is the custom class:
public class MovieItem {
private double popularity;
private String photo;
private String name;
public MovieItem(double popularity, String poster_path, String original_title) {
this.popularity = popularity;
this.photo = poster_path;
this.name = original_title;
}
public double getPopularity() { return popularity; }
public String getPhoto() { return photo; }
public String getName() { return name; }
}
and this is the json class:
public final class OpenMovieJsonUtils {
public static ArrayList<MovieItem> getSimpleMovieStringsFromJson(Context context, String moviesJsonString)
throws JSONException {
final String RESULTS = "results";
final String POPULARITY = "popularity";
final String POSTER_PATH = "poster_path";
final String ORIGINAL_TITLE = "original_title";
ArrayList<MovieItem> parsedMovieData = new ArrayList<MovieItem>();
JSONObject moviesObject = new JSONObject(moviesJsonString);
JSONArray moviesArray = moviesObject.getJSONArray(RESULTS);
for (int i = 0; i < moviesArray.length(); i++) {
double popularity;
String poster_path;
String original_title;
moviesObject = moviesArray.getJSONObject(i);
popularity = moviesObject.getDouble(POPULARITY);
poster_path = moviesObject.getString(POSTER_PATH);
original_title = moviesObject.getString(ORIGINAL_TITLE);
parsedMovieData.add(new MovieItem(popularity, poster_path, original_title));
}
return parsedMovieData;
}
}
this is the networking class:
public final class NetworkUtils {
private static final String TAG = NetworkUtils.class.getSimpleName();
private static final String MOVIES_BASE_URL = "https://api.themoviedb.org/3/movie/";
private static final String MOVIES_URL = MOVIES_BASE_URL;
private static final String apiKey = "36666cbb5d7e20041e705d1b2c4e7a79";
final static String API_PARAM = "api_key";
public static URL buildUrl(String MoviesQuery) {
Uri builtUri = Uri.parse(MOVIES_URL).buildUpon()
.appendPath(MoviesQuery)
.appendQueryParameter(API_PARAM, apiKey)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Log.v(TAG, "Built URI " + url);
return url;
}
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
}
what's wrong with images so I get their values null instead of the popularity and name of movies works and not null
Your question is incomplete, doesn't specify the complete details about from where you are getting API response.
I could answer this question because I have just done this project in my ongoing Android Developer Nanodegree by Udacity.
Hopefully you are fetching the movie details from TMDB.
You should read the Project implementation guide thoroughly which says
You will need to append a base path ahead of this relative path to build the complete url you will need to fetch the image using Picasso
Following code will help you -
public class MovieItem {
private double popularity;
private String photo;
private String name;
public MovieItem(double popularity, String poster_path, String original_title) {
this.popularity = popularity;
this.photo = poster_path;
this.name = original_title;
}
public double getPopularity() { return popularity; }
public String getPhoto() { return photo; }
public String getName() { return name; }
public Uri getFullPosterPath() {
return Uri.parse("http://image.tmdb.org/t/p/")
.buildUpon()
.appendPath("w185")
.appendEncodedPath(getPhoto())
.build();
}
}
And in Adapter make this change -
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.MoviePopularity.setText(String.valueOf(mMoviesItems.get(position).getPopularity()));
Picasso.with(this.context).load(mMoviesItems.get(position).getFullPosterPath()).into(holder.MoviePoster);
holder.MovieName.setText(String.valueOf(mMoviesItems.get(position).getName()));
}
I’ve been trying to get recycler view working with retrofit. I seem to be pulling in the JSON fine from within getRecipes() method, and my logs are showing me that the some data is there.
However, when I call my getRecipes() method from onCreate(), something seems to be going wrong. When I check to see if my recipeList array contains my JSON results within onCreate, it is telling me it is empty. Why is it doing this if my logs within my getRecipes() method are showing me that data is there...?
Not sure if it is an issue with my recycler view or what I am doing with retrofit, or something else. Been trying for days to figure out, so any advice would be greatly appreciated.
JSON
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
public class ItemListActivity extends AppCompatActivity {
private boolean mTwoPane;
public static final String LOG_TAG = "myLogs";
public static List<Recipe> recipeList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getRecipes();
setContentView(R.layout.activity_item_list);
getRecipes();
//Logging to check that recipeList contains data
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.item_list);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
}
public void getRecipes(){
String ROOT_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/";
Retrofit RETROFIT = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RecipeService service = RETROFIT.create(RecipeService.class);
Call<List<Recipe>> call = service.getMyJson();
call.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {
Log.d(LOG_TAG, "Got here");
if (!response.isSuccessful()) {
Log.d(LOG_TAG, "No Success");
}
Log.d(LOG_TAG, "Got here");
recipeList = response.body();
//Logging to check data is there
Log.v(LOG_TAG, "LOGS" + recipeList.size());
for (int i = 0; i < recipeList.size(); i++) {
String newString = recipeList.get(i).getName();
Ingredients[] ingredients = recipeList.get(i).getIngredients();
for(int j = 0; j < ingredients.length; j++){
Log.d(LOG_TAG, ingredients[j].getIngredient());
}
Steps[] steps = recipeList.get(i).getSteps();
for(int k = 0; k < steps.length; k++){
Log.d(LOG_TAG, steps[k].getDescription());
}
Log.d(LOG_TAG, newString);
}
}
#Override
public void onFailure(Call<List<Recipe>> call, Throwable t) {
Log.e("getRecipes throwable: ", t.getMessage());
t.printStackTrace();
}
});
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<Recipe> mValues;
public SimpleItemRecyclerViewAdapter(List<Recipe> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getName());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View mView;
public TextView mContentView;
public Recipe mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
RecipeService
public interface RecipeService {
#GET("baking.json")
Call<List<Recipe>> getMyJson();}
Models
Recipe
public class Recipe{
private Ingredients[] ingredients;
private String id;
private String servings;
private String name;
private String image;
private Steps[] steps;
public Ingredients[] getIngredients ()
{
return ingredients;
}
public void setIngredients (Ingredients[] ingredients)
{
this.ingredients = ingredients;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getServings ()
{
return servings;
}
public void setServings (String servings)
{
this.servings = servings;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
public Steps[] getSteps ()
{
return steps;
}
public void setSteps (Steps[] steps)
{
this.steps = steps;
}
#Override
public String toString()
{
return "[ingredients = "+ingredients+", id = "+id+", servings = "+servings+", name = "+name+", image = "+image+", steps = "+steps+"]";
}}
Ingredients
public class Ingredients{
private String measure;
private String ingredient;
private String quantity;
public String getMeasure ()
{
return measure;
}
public void setMeasure (String measure)
{
this.measure = measure;
}
public String getIngredient ()
{
return ingredient;
}
public void setIngredient (String ingredient)
{
this.ingredient = ingredient;
}
public String getQuantity ()
{
return quantity;
}
public void setQuantity (String quantity)
{
this.quantity = quantity;
}
#Override
public String toString()
{
return "[measure = "+measure+", ingredient = "+ingredient+", quantity = "+quantity+"]";
}}
Steps
public class Steps{
private String id;
private String shortDescription;
private String description;
private String videoURL;
private String thumbnailURL;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getShortDescription ()
{
return shortDescription;
}
public void setShortDescription (String shortDescription)
{
this.shortDescription = shortDescription;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getVideoURL ()
{
return videoURL;
}
public void setVideoURL (String videoURL)
{
this.videoURL = videoURL;
}
public String getThumbnailURL ()
{
return thumbnailURL;
}
public void setThumbnailURL (String thumbnailURL)
{
this.thumbnailURL = thumbnailURL;
}
#Override
public String toString()
{
return "[id = "+id+", shortDescription = "+shortDescription+", description = "+description+", videoURL = "+videoURL+", thumbnailURL = "+thumbnailURL+"]";
}}
Logs
https://gist.github.com/2triggers/12b6eeb32ed8909ab50bbadd4742d7f7
this will be empty always because this line will execute before getting the response from a server.
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Better call this after this line recipeList = response.body();
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
it is because you are sending the recipelist into the adapter before even it is populated , after you are sending the recipelist into the adapter which is empty you are populating your recipelist from getRecipes method, you might be wondering you have declared the getRecipes method before even you are assigning the recipelist to adapter so how come it is empty, yea but the fact is your getRecipes work on background thread so even before your recipelist gets populated your adapter assignment takes place on the main thread so you are basically assigning the empty list, one thing you can do is notify when the adapter when the data changes or when the the recipelist is filled with data that is from within the getRecipe method.
when you assign the recipelist = response.body right after this you can notify the adapter
or move this two lines
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
right after the
recipelist = response.body;
in getRecipes method
Try create the Constructor with all atributes from your Recipe.class
Like:
public Ingredients(String measure, String ingredients, String quantity ){
this.measure = measure;
this.ingredients = ingredients;
this.quantity = quantity
}
Do same in all class where make up your object of list.
So am working with retrofit and rxjava for my application.so am using the #GET annociation to pull my blog details from the server that include blog_title, blog_content, blog_thumbnail etc and all this parameter are within an array called blog_post.
I have my APIClient:
public class ApiClient {
private static final String STAGING_BASE_URL = "https://watchnollywood.ml/api/";
private static ApiClient instance;
private ApiService apiService;
private ApiClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
// TODO: 21/03/2017 when going live change the log level to NONE, to enhance performance
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line for logging requests!
final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
//final Retrofit retrofit = new Retrofit.Builder().baseUrl(STAGING_BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient.build()).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(STAGING_BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
}
public static ApiClient getInstance(){
if(instance == null){
instance = new ApiClient();
}
return instance;
}
//API CALL FOR LOGIN
public Observable<UserItem> login(String email, String password){
return apiService.signIn(email,password);
}
//API CALL FOR SIGNUP
public Observable<StatusItem> signup(String email, String password, String full_name, String phone){
return apiService.signUp(email, password,phone,full_name);
}
//API CALL FOR BLOG DETAILS
public Observable<BlogResponse> blog_post(){
return apiService.blog_post();
}
}
ApiService:
public interface ApiService {
#FormUrlEncoded
#POST("signin")
Observable<UserItem> signIn(#Field("email") String email, #Field("password") String password);
#FormUrlEncoded
#POST("signup")
Observable<StatusItem> signUp(#Field("full_name")String full_name, #Field("phone") String phone, #Field("email") String email, #Field("password") String password);
#GET("blog")
Observable<BlogResponse> blog_post();
}
pojo classes:
public class BlogItem {
private int thumbNail;
private String title;
private String summary;
public int getThumbNail() {
return thumbNail;
}
public void setThumbNail(#DrawableRes int thumbNail) {
this.thumbNail = thumbNail;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
public class BlogResponse {
private BlogItem[] blogItems;
public BlogItem[] getBlogItems() {
return blogItems;
}
public void setBlogItems(BlogItem[] blogItems) {
this.blogItems = blogItems;
}
}
I have a recyclerview that will hold all the information that will be coming from the server. But the problem is that when I run it I get a log response in my RUN terminal but nothing is showing on the app screen.
this is my FragmentClass that holds the information from the server:
BlogFragment:
public class BlogFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
private RecyclerView recyclerView;
private BlogAdapter adapter;
private List<BlogItem> blogItems;
private View view;
public BlogFragment() {
// Required empty public constructor
}
public static BlogFragment newInstance(String param1) {
BlogFragment fragment = new BlogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_blog, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = (RecyclerView) view.findViewById(R.id.blog_posts_list);
setUpViews();
}
private void setUpViews() {
blogItems = new ArrayList<>();
adapter = new BlogAdapter(blogItems);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
BlogPost();
// populateLists();
}
private void BlogPost() {
ApiClient.getInstance().blog_post().observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread()).subscribe(new DisposableObserver<BlogResponse>() {
#Override
public void onNext(BlogResponse value) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(blogItem.getTitle().toString());
blogItem.setSummary(blogItem.getSummary().toString());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
}
});
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
/*
private void populateLists() {
int dummyPostArraySize = 10;
for (int i = 0; i < dummyPostArraySize; i++) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("Post title " + i+1);
blogItem.setThumbNail(isEven(i) ? R.drawable.profile_image : 0);
blogItem.setSummary(getString(isEven(i) ? R.string.summary2 : R.string.summary1));
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}*/
private boolean isEven(int position) {
return (position & 1) == 0;
}
}
Adapter class
public class BlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
private List<BlogItem> blogItems;
public BlogAdapter(List<BlogItem> blogItems) {
this.blogItems = blogItems;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_post_item,
parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
BlogItem blogItem = blogItems.get(position);
holder.bindModel(blogItem);
}
#Override
public int getItemCount() {
return blogItems == null ? (0) : blogItems.size();
}
}
View Holder class
public class BlogViewHolder extends RecyclerView.ViewHolder {
private ImageView cover;
private TextView title;
private TextView summary;
public BlogViewHolder(View itemView) {
super(itemView);
cover = (ImageView) itemView.findViewById(R.id.post_thumbnail);
title = (TextView) itemView.findViewById(R.id.post_title);
summary = (TextView) itemView.findViewById(R.id.post_summary);
}
public void bindModel(BlogItem blogItem) {
if (blogItem.getThumbNail() == 0) {
cover.setVisibility(View.GONE);
} else {
cover.setImageResource(blogItem.getThumbNail());
}
title.setText(Html.fromHtml(blogItem.getTitle()));
summary.setText(blogItem.getSummary());
}
}
What am I not doing right. Someone Please Help!!!
In the private void BlogPost() { method, you create BlogItems but then don't do anything with it. You probably forgot to add them to the blogItems list.
In addition, the call to adapter.notifyItemRangeChanged in that method happens way before the sequence receives data but you don't call that after each blogItem or when all blog items have arrived - the observer is on a complete different execution path than the outer BlogPost() method.
Edit spelled out:
#Override
public void onNext(BlogResponse value) {
for (BlogItem responseItem : value.getBlogItems()) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(responseItem.getTitle().toString());
blogItem.setSummary(responseItem.getSummary().toString());
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
blogItems.add(blogItem);
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
the listviews not loaded in the main i not find as data load.
I shows the main vacuum
please help.
pFragment.java
public class pFragment extends Fragment{
private ListView plistView;
public String url = "http://192.168.0.104/sproyect/getmovil";
AdaptadorPublicaciones adapter;
JSONObject jsonobject;
JSONArray jsonarray;
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.public_listv, container, false);
}
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
(new AsyncListViewLoader()).execute(url);
adapter = new AdaptadorPublicaciones(new ArrayList<Publicaciones>(), getActivity());
plistView = (ListView)getView().findViewById(R.id.plistView);
plistView.setAdapter(adapter);
}
private class AsyncListViewLoader extends AsyncTask<String, Void, List<Publicaciones>>{
private final ProgressDialog dialog = new ProgressDialog(getActivity());
protected void onPostExecute(List<Publicaciones> result){
super.onPostExecute(result);
dialog.dismiss();
adapter.setItemList(result);
adapter.notifyDataSetChanged();
}
protected void onPreExecute(){
super.onPreExecute();
dialog.setMessage("Cargando informacion");
dialog.show();
}
#Override
protected List<Publicaciones> doInBackground(String... params) {
List<Publicaciones> result = new ArrayList<Publicaciones>();
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection)u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while( is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i = 0; i < arr.length(); i++) {
result.add(convertItem(arr.getJSONObject(i)));
}
return result;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
private Publicaciones convertItem(JSONObject obj) throws JSONException {
String titulo = obj.getString("titulo");
String estado = obj.getString("estatus");
String fechap = obj.getString("fechreg");
int idpublic = obj.getInt("idpublic");
int avatar = R.drawable.notif;
return new Publicaciones(idpublic, titulo, estado, fechap, avatar);
}
}
AdaptadorPublicaciones.java
public class AdaptadorPublicaciones extends ArrayAdapter<Publicaciones>{
private List<Publicaciones> itemlist;
private Context context;
public AdaptadorPublicaciones(List<Publicaciones> itemlist, Context context){
super(context,android.R.layout.simple_list_item_1,itemlist);
this.itemlist = itemlist;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_views,parent, false);
}
Publicaciones pb = itemlist.get(position);
//AVATAR
ImageView avatar = (ImageView)v.findViewById(R.id.imgAvatar);
//avatar.setImageResource(resultp.get("avatar"));
//TITULO
TextView titulo = (TextView)v.findViewById(R.id.txTitulo);
titulo.setText(pb.getTitulo());
//DISPONIBILIDAD
TextView dispo = (TextView)v.findViewById(R.id.txDisponibilidad);
dispo.setText(pb.getEstado());
//FECHA
TextView fechap = (TextView)v.findViewById(R.id.txFecha);
fechap.setText(pb.getFechap());
//ID PUBLICACION OCULTO
TextView hdp = (TextView)v.findViewById(R.id.txhpublic);
hdp.setText(""+ pb.getIdpublic());
return v;
}
public List<Publicaciones> getList(){
return itemlist;
}
public void setItemList(List<Publicaciones> ilist){
this.itemlist = ilist;
}
#Override
public int getCount() {
if(itemlist != null)
return itemlist.size();
return 0;
}
#Override
public Publicaciones getItem(int position) {
if(itemlist != null)
return itemlist.get(position);
return null;
}
#Override
public long getItemId(int position) {
if(itemlist != null)
return itemlist.get(position).hashCode();
return 0;
}
}
Publicaciones.java
public class Publicaciones{
private int idpublic;
private String titulo;
private String estado;
private int avatar;
private String fechap;
public Publicaciones(int idpublic, String titulo, String estado, String fechap, int avatar) {
super();
this.idpublic = idpublic;
this.titulo = titulo;
this.estado = estado;
this.fechap = fechap;
this.avatar = avatar;
}
public int getAvatar() {
return avatar;
}
public int getIdpublic() {
return idpublic;
}
public String getTitulo() {
return titulo;
}
public String getEstado() {
return estado;
}
public String getFechap() {
return fechap;
}
}
en the json de retorno muestra este error:
11-09 19:43:45.545: W/System.err(608): org.json.JSONException: A JSONArray text must start with '[' at character 1 of {"publicaciones":[{"titulo":"Aperturado curso de ofimatica en los nuevos laboratorios.","estatus":"nuevo","idpublic":"9","avatar":"nivel_ofimatica.jpg","fechreg":"2013-11-07"},{"titulo":"Disponible curso sobre el manejador de bases de datos mysql.","estatus":"nuevo","idpublic":"8","avatar":"nivel_desarrollado_web.png","fechreg":"2013-11-06"}]}??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Try
Change
plistView = (ListView)getView().findViewById(R.id.plistView);
To
plistView = (ListView) getActivity().findViewById(R.id.plistView);
And also
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
(new AsyncListViewLoader()).execute(url);
adapter = new AdaptadorPublicaciones(new ArrayList<Publicaciones>(), getActivity());
plistView = (ListView)getView().findViewById(R.id.plistView);
plistView.setAdapter(adapter);
}
To
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
(new AsyncListViewLoader()).execute(url);
plistView = (ListView)getView().findViewById(R.id.plistView);
}
and
protected void onPostExecute(List<Publicaciones> result){
super.onPostExecute(result);
dialog.dismiss();
adapter.setItemList(result);
adapter.notifyDataSetChanged();
}
To
protected void onPostExecute(List<Publicaciones> result){
super.onPostExecute(result);
dialog.dismiss();
adapter = new AdaptadorPublicaciones(result, getActivity());
plistView.setAdapter(adapter);
}
Edited:-
Change
JSONArray arr = new JSONArray(JSONResp);
for (int i = 0; i < arr.length(); i++) {
result.add(convertItem(arr.getJSONObject(i)));
}
To
JSONObject json=new JSONObject(JSONResp);
JSONArray arr=json.getJSONArray("publicaciones");
for (int i = 0; i < arr.length(); i++) {
result.add(convertItem(arr.getJSONObject(i)));
}