i have a news reader (using rss), it's work as well, now i'm trying to open the navigator after clicked on a news, but i don't know how to get the link (i just know that i have to use getLink() but i don't know where):
Actualites.java
public class Actualites extends android.support.v4.app.Fragment{
AsyncTask<Void, Void, List> a = null;
NewsAdapter adapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_actualites, container, false);
ListView list = (ListView) view.findViewById(R.id.listView1);
adapter = new NewsAdapter(getActivity(), new ArrayList<News>());
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.solutis.fr")));
}
});
a = new AsyncTask<Void, Void, List>() {
#Override
protected List doInBackground(Void... params) {
ArrayList<News> res = new ArrayList<News>();
try {
URL url = new URL("http://www.solutis.fr/actualites-rachat-credit,rss.html?format=feed");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
RssParser parser = new RssParser();
try {
return parser.parse(urlConnection.getInputStream());
} catch (XmlPullParserException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(List result) {
adapter.update(result);
}
};
a.execute();
TextView textView =(TextView)getActivity().findViewById(R.id.main_toolbar_title);
textView.setText(getString(R.string.title_actu));
textView.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
return view;
}
}
NewsAdapter.java
public class NewsAdapter extends BaseAdapter {
List<News> news;
Context context;
public NewsAdapter(Context context, List<News> news) {
this.news = news;
this.context = context;
}
public void update(List<News> news) {
this.news = news;
notifyDataSetChanged();
}
#Override
public int getCount() {
return news.size();
}
#Override
public Object getItem(int arg0) {
return news.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
LayoutInflater li = LayoutInflater.from(context);
View v = li.inflate(R.layout.three_line_list_item, null);
TextView tv1 = (TextView)v.findViewById(android.R.id.text1);
tv1.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/GothamBold.ttf"));
tv1.setTextSize(15);
TextView tv3 = (TextView)v.findViewById(android.R.id.title);
tv3.setTextColor(Color.parseColor("#2B729F"));
tv3.setTextSize(13);
tv3.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/GothamBook.ttf"));
TextView tv2 = (TextView)v.findViewById(android.R.id.text2);
tv2.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/GothamBook.ttf"));
tv2.setTextSize(14);
News n = (News)getItem(arg0);
tv1.setText(n.getTitle());
String pubDate = Html.fromHtml(n.getPubDate()).toString().replace((char) 65532, (char) 32).trim();
tv3.setText(pubDate);
String content = Html.fromHtml(n.getContent()).toString().replace((char) 65532, (char) 32).trim();
tv2.setText(content);
return v;
}
}
RssParser.java
public class RssParser {
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
private static final String ns = null;
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
public ArrayList<News> parse(InputStream in) throws XmlPullParserException, IOException {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
ArrayList<News> entries = new ArrayList<News>();
parser.require(XmlPullParser.START_TAG, ns, "rss");
parser.nextTag();
parser.require(XmlPullParser.START_TAG, ns, "channel");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("item")) {
String title = "";
String link = "";
String pubDate = "";
String content = "";
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (name.equals("title")) {
title = readText(parser);
} else if (name.equals("link")) {
link = readText(parser);
} else if (name.equals("pubDate")) {
pubDate = readText(parser);
} else if (name.equals("description")) {
content = readText(parser);
} else
skip(parser);
}
entries.add(new News(title, pubDate, content));
} else
skip(parser);
}
return entries;
}
}
News.java
public class News {
private String title;
private String content;
private String pubDate;
private String link;
public News(String title, String pubDate, String content) {
this.title = title;
this.content = content;
this.pubDate = pubDate;
}
public News(String link, String title, String pubDate, String content) {
this.link = link;
this.title = title;
this.content = content;
this.pubDate = pubDate;
}
public String getTitle() {
return (title);
}
public String getContent() {
return (content);
}
public String getPubDate(){
return (pubDate);
}
public String getLink(){
return (link);
}
}
I have to change public void onItemClick(), i've just put a url, but i have to get the url of the news, but i don't know how to do that. Someone can help me ?
You can get the news object from the adapter using the position parameter in the onItemClick. I haven't tested the code but it will be something like the following;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News news = (News) adapter.getItem(position)
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(news.getLink())));
}
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 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 ?
I'm getting the follwoing error:
Type mismatch: cannot convert from String to List
on the line this.videos = videos; from the following code:
public void setVideos(String videos) {
this.videos = videos;
}
I've tried following both of Eclipse's suggestions:
Change type of videos to string
Change type of videos to List
However, neither seems to resolve the issue and both cause additonal errors.
I'm not sure exactly what I can do to resolve the issue at this point.
Cmd.java
public class Cmd implements ListAdapter {
private String success;
private String cmd;
List<Cmd> videos;
private String video;
private String numberofvideos;
private String videoname;
private String videourl;
private LayoutInflater mInflater;
Button fav_up_btn1;
Button fav_dwn_btn1;
Context my_context;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_user_video,
parent, false);
}
ImageView thumb = (ImageView) convertView
.findViewById(R.id.userVideoThumbImageView);
TextView title = (TextView) convertView
.findViewById(R.id.userVideoTitleTextView);
TextView uploader = (TextView) convertView
.findViewById(R.id.userVideouploaderTextView);
TextView viewCount = (TextView) convertView
.findViewById(R.id.userVideoviewsTextView);
uploader.setText(videos.get(position).getTitle());
viewCount.setText(videos.get(position).getviewCount() + " views");
// Get a single video from our list
final Cmd video = videos.get(position);
// Set the image for the list item
// Set the title for the list item
title.setText(video.getTitle());
uploader.setText("by " + video.getUploader() + " | ");
return convertView;
}
public String getUploader() {
// TODO Auto-generated method stub
return null;
}
public String getviewCount() {
// TODO Auto-generated method stub
return null;
}
public CharSequence getTitle() {
// TODO Auto-generated method stub
return null;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getNumberOfVideos() {
return numberofvideos;
}
public void setNumberOfVideos(String numberofvideos) {
this.numberofvideos = numberofvideos;
}
public List<Cmd> getVideos() {
return videos;
}
public void setVideos(String videos) {
this.videos = videos;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getVideoName() {
return videoname;
}
public void setVideoName(String videoname) {
this.videoname = videoname;
}
public String getVideoURL() {
return videourl;
}
public void setVideoURL(String videourl) {
this.videourl = videourl;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Cmd> videos;
private String tempVal;
// to maintain context
private Cmd cmd;
public SAXXMLHandler() {
videos = new ArrayList<Cmd>();
}
public List<Cmd> getResponse() {
return videos;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("cmd")) {
// create a new instance of cmd
cmd = new Cmd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("videos")) {
// add it to the list
videos.add(cmd);
} else if (qName.equalsIgnoreCase("success")) {
cmd.setSuccess(tempVal);
} else if (qName.equalsIgnoreCase("numberofvideos")) {
cmd.setNumberOfVideos(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setVideos(tempVal);
} else if (qName.equalsIgnoreCase("video")) {
cmd.setVideo(tempVal);
} else if (qName.equalsIgnoreCase("videoname")) {
cmd.setVideoName(tempVal);
} else if (qName.equalsIgnoreCase("videourl")) {
cmd.setVideoURL(tempVal);
}
}
}
Update the setter method for variable List<Cmd> videos as below :
public void setVideos(List<Cmd> videos) {
this.videos = videos;
}
setVideos(String videos) should be defined as setVideos(List<Cmd> videos)
I'm attempting to populate a ListView with XML Data by using an ArrayList - which I've been able to accomplish thus far - the issue is the ArrayList does not seem to populate the ListView with data beyond the first item in the listView and I'm unsure why.
Screenshot
XML Data:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<response>
<cmd>getVideos</cmd>
<success>1</success>
<NumberOfVideos>4</NumberOfVideos>
<Videos>
<Video>
<VideoName>sample_iPod</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_mpeg4</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_sorenson</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_iTunes</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov
</VideoUrl>
<VideoTags/>
</Video>
</Videos>
</response>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<Cmd> {
Activity context;
List<Cmd> videos;
public CustomListViewAdapter(Activity context, List<Cmd> videos) {
super(context, R.layout.list_item2, videos);
this.context = context;
this.videos = videos;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtSuccess;
TextView txtCmd;
TextView txtPrice;
}
public Cmd getItem(int position) {
return videos.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item2, null);
holder = new ViewHolder();
holder.txtSuccess = (TextView) convertView.findViewById(R.id.success);
holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Cmd cmd = (Cmd) getItem(position);
holder.txtSuccess.setText(cmd.getSuccess());
holder.txtCmd.setText(cmd.getCmd());
// holder.imageView.setImageBitmap(cmd.getImageBitmap());
holder.txtPrice.setText(cmd.getVideoName() + "");
return convertView;
}
}
SAXParserAsyncTaskActivity.java
public class SAXParserAsyncTaskActivity extends Activity implements
OnClickListener, OnItemClickListener {
Button button;
ListView listView;
List<Cmd> videos = new ArrayList<Cmd>();
CustomListViewAdapter listViewAdapter;
static final String URL = "http://mobile.example.com/api/xml.php?cmd=getVideos&username=fake&password=";
public static final String LIBRARY = "Library";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
findViewsById();
button.setOnClickListener(this);
listView.setOnItemClickListener(this);
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[] { URL });
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
listView = (ListView) findViewById(R.id.cmdList);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
// GetXMLTask task = new GetXMLTask(this);
// task.execute(new String[] { URL });
}
// private inner class extending AsyncTask
private class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
protected void onPostExecute(List<Cmd> videos) {
listViewAdapter = new CustomListViewAdapter(context, videos);
listView.setAdapter(listViewAdapter);
}
/*
* uses HttpURLConnection to make Http request from Android to download
* the XML file
*/
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<Cmd> doInBackground(String... urls) {
List<Cmd> videos = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
videos = SAXXMLParser.parse(stream);
for (Cmd cmd : videos) {
String videoName = cmd.getVideoName();
// String getVideos = cmd.getVideos();
String getVideo = cmd.getVideo();
String getVideoURL = cmd.getVideoURL();
String getNumberOfVideos = cmd.getNumberOfVideos();
Bitmap bitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
bitmap = BitmapFactory.decodeStream(
new URL(videoName).openStream(), null,
bmOptions);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// stream.close();
return videos;
}
}
}
Cmd.java
public class Cmd implements ListAdapter {
private String success;
private String cmd;
List<Cmd> videos;
private String video;
private String numberofvideos;
private String videoname;
private String videourl;
private LayoutInflater mInflater;
Button fav_up_btn1;
Button fav_dwn_btn1;
Context my_context;
// private Bitmap imageBitmap;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If convertView wasn't null it means we have already set it to our
// list_item_user_video so no need to do it again
if (convertView == null) {
// This is the layout we are using for each row in our list
// anything you declare in this layout can then be referenced below
convertView = mInflater.inflate(R.layout.list_item_user_video,
parent, false);
}
// We are using a custom imageview so that we can load images using urls
ImageView thumb = (ImageView) convertView
.findViewById(R.id.userVideoThumbImageView);
//thumb.setScaleType(ScaleType.FIT_XY);
TextView title = (TextView) convertView
.findViewById(R.id.userVideoTitleTextView);
TextView uploader = (TextView) convertView
.findViewById(R.id.userVideouploaderTextView);
TextView viewCount = (TextView) convertView
.findViewById(R.id.userVideoviewsTextView);
uploader.setText(videos.get(position).getTitle());
viewCount.setText(videos.get(position).getviewCount() + " views");
fav_up_btn1 = (Button) convertView.findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(my_context.getResources()
.getDrawable(R.drawable.fav_up_btn1)
.getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
// Get a single video from our list
final Cmd video = videos.get(position);
// Set the image for the list item
// / thumb.setImageDrawable(video.getThumbUrl());
//thumb.setScaleType(ScaleType.FIT_XY);
// Set the title for the list item
title.setText(video.getTitle());
uploader.setText("by " + video.getUploader() + " | ");
return convertView;
}
public String getUploader() {
// TODO Auto-generated method stub
return null;
}
public String getviewCount() {
// TODO Auto-generated method stub
return null;
}
public CharSequence getTitle() {
// TODO Auto-generated method stub
return null;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getNumberOfVideos() {
return numberofvideos;
}
public void setNumberOfVideos(String numberofvideos) {
this.numberofvideos = numberofvideos;
}
public List<Cmd> getVideos() {
return videos;
}
public void setVideos(List<Cmd> videos) {
this.videos = videos;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getVideoName() {
return videoname;
}
public void setVideoName(String videoname) {
this.videoname = videoname;
}
public String getVideoURL() {
return videourl;
}
public void setVideoURL(String videourl) {
this.videourl = videourl;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public boolean areAllItemsEnabled() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
return false;
}
public String getId() {
// TODO Auto-generated method stub
return null;
}
}
SAXXMLParser.java
public class SAXXMLParser {
public static List<Cmd> parse(InputStream is) {
List<Cmd> response = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHandler saxHandler = new SAXXMLHandler();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// get the `Video list`
response = saxHandler.getResponse();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return video list
return response;
}
}
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Cmd> videos;
private String tempVal;
// to maintain context
private Cmd cmd;
public SAXXMLHandler() {
videos = new ArrayList<Cmd>();
}
public List<Cmd> getResponse() {
return videos;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("cmd")) {
// create a new instance of cmd
cmd = new Cmd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("videos")) {
// add it to the list
videos.add(cmd);
} else if (qName.equalsIgnoreCase("success")) {
cmd.setSuccess(tempVal);
} else if (qName.equalsIgnoreCase("numberofvideos")) {
cmd.setNumberOfVideos(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setVideos(videos);
} else if (qName.equalsIgnoreCase("video")) {
cmd.setVideo(tempVal);
} else if (qName.equalsIgnoreCase("videoname")) {
cmd.setVideoName(tempVal);
} else if (qName.equalsIgnoreCase("videourl")) {
cmd.setVideoURL(tempVal);
}
}
}
parser_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/button" />
<ListView
android:id="#+id/cmdList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
XML Screenshot
P.S.
If any additional information is required - please let me know (I will be at my desk working on this for the next few hours and will gladly answer any questions and accept any answers promptly)
In SAXXMLHandler.java's endElement() method you only add the cmd to the videos list if qName.equalsIgnoreCase("videos").
In all other cases you modify the cmd but you dont actually add it to the list. You want to add a videos.add(cmd) statement in the else if blocks as well so all the cmd's get added to the list.
This mistake right here is the cause of your List<Cmd> videos only having one item and thus only showing one item in your listview.
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)));
}