android: fragment not load fragment AsyncTask ArrayAdapter - java

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)));
}

Related

Data parsed from Json cant fetch properly when add another argument in constructor

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.

recycleview doesn't fetch json data

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 ?

How to Populate 2 strings in Listview from webservice?

Am an newbie to android ...kindly help me guys...I have 2 strings in my sample webservice(Not in an array) and I want to populate it in the listview .I wrote code to populate with a single string.But I don't know how to populate with 2nd strings below to 1st string in listview.Any suggestion will be appreciated.
Here is my complete code
HTTPURLCONNECT
class HttpULRConnect {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2","test");
String line;
while ((line= reader.readLine())!=null) {
sb.append(line+"\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally{
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}}}
Here is my FETCH.java
public class Fetch extends Activity {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fetch);
new BackTask().execute(url);
}
public class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content =HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonobject = ar.getJSONObject(i);
Flowers flowers = new Flowers();
flowers.setName(jsonobject.getString("NAME"));
flowersList.add(flowers);
}
}
catch (JSONException e){
e.printStackTrace();
}
FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flower_lis_item, flowersList);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
}
}
static class Flowers {
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
private String NAME;
}
public static class FlowerAdapter extends ArrayAdapter<Flowers> {
private ArrayList<Flowers> items;
private Context mContext;
public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){
super(context,textViewResourceID,items);
mContext = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Flowers flowers = items.get(position);
if(v==null){
LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.flower_lis_item,null);
}
TextView title = (TextView)v.findViewById(R.id.textView3);
TextView text =(TextView)v.findViewById(R.id.textView2);
if (title != null) {
title.setText(flowers.getName());
text.setText(flowers.getName());
}
return v;
}
}
}

filtering listview results after selecting spinner value

I have 3 spinners in my project named standard, division and age. They contain values from json data. When I select a value from each individual spinner it shows all data of students in a listview respectivly (fetched from json).
I'm working with the following JSON data:
[
{
"name":"aarti",
"surname":"singh",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"seema",
"surname":"desai",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"tina",
"surname":"joshi",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"megha",
"surname":"kale",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"swati",
"surname":"marathe",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"rekha",
"surname":"surve",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"madhu",
"surname":"dalvi",
"age":"18",
"div":"B",
"standard":"6"
}
I am trying to do it like this way:
When I select standard 7 from the spinner it should display students information studying in 7th standard ("aarti", "seema", "megha", "rekha") and their other information too.
Then I am selecting value from division spinner say "A", it should take above result granted and accordingly display students from standard 7 and division "A". It should shows the result as ("aarti", "megha", "rekha") and their other informations too.
Finally when I am selecting value from age spinner say "17", it should take above result granted and accordingly display students from standard 7 and division "A" and age "17". Accordingly it shows "megha" and "rekha".
Can anyone please assist me
This is my MainActivity.java class:
public class MainActivity extends AppCompatActivity {
ArrayList<String> AllStandards = new ArrayList<>();
ArrayList<String> AllDivision = new ArrayList<>();
ArrayList<String> AllAge = new ArrayList<>();
JSONArray jsonArray;
Spinner spinner_std, spinner_div, spinner_age;
private ArrayList<StudInfo> studentVOList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<String> item_Std = getStandard("data.json");
final List<String> items_div = getDivision("data.json");
final List<String> items_age = getAge("data.json");
/*spinner for standard*/
spinner_std = (Spinner) findViewById(R.id.spinnerStandard);
ArrayAdapter<String> adapter_std = new ArrayAdapter<String>(this, R.layout.spinner_standard_layout, R.id.textViewStandard, item_Std);
adapter_std.getFilter().filter(txt);
spinner_std.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String standard = AllStandards.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String stand = jsonObject.getString("standard");
if (stand.equalsIgnoreCase(standard)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setStandard(stand);
studentVOList.add(studentVO);
}
}
// Log.d("TAG", "List With All Students in selected standard: " + studentVOList.size());
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_std.setAdapter(adapter_std);
/*spinner for division*/
spinner_div = (Spinner) findViewById(R.id.spinnerDiv);
ArrayAdapter<String> adapter_div = new ArrayAdapter<String>(this, R.layout.spinner_division_layout, R.id.textViewDivision, items_div);
adapter_div.getFilter().filter(txt);
spinner_div.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String division = AllDivision.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String div = jsonObject.getString("div");
// Collections.sort(AllDivision);
if (div.equalsIgnoreCase(division)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setDiv(div);
studentVOList.add(studentVO);
}
}
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_div.setAdapter(adapter_div);
/*spinner for age*/
spinner_age = (Spinner) findViewById(R.id.spinerAge);
ArrayAdapter<String> adapter_age = new ArrayAdapter<String>(this, R.layout.spinner_age_layout, R.id.textViewAge, items_age);
adapter_age.getFilter().filter(txt);
spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String age = AllAge.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String age_list = jsonObject.getString("age");
Collections.sort(AllAge);
if (age_list.equalsIgnoreCase(age)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setAge(age_list);
studentVOList.add(studentVO);
}
}
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_age.setAdapter(adapter_age);
}//onCreate Method
private List<String> getStandard(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
// AllStandards.clear();
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("standard");
if (!AllStandards.contains(stand)) {
AllStandards.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllStandards;
}
private List<String> getDivision(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("div");
if (!AllDivision.contains(stand)) {
AllDivision.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllDivision;
}
private List<String> getAge(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("age");
if (!AllAge.contains(stand)) {
AllAge.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllAge;
}
this is my ListAdapter.java class
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
public ListAdapter(Context context, int vg, int id, ArrayList<StudInfo> list) {
super(context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById(R.id.txtName);
TextView textViewSurname = (TextView)itemView.findViewById(R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById(R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById(R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById(R.id.txtStandard);
textViewName.setText(list.get(position).getName());
textViewSurname.setText(list.get(position).getSurname());
textViewAge.setText(list.get(position).getAge());
textViewDiv.setText(list.get(position).getDiv());
textViewStd.setText(list.get(position).getStandard());
return itemView;
}
}
this is my StudentsInfo.java class
public class StudentsInfo extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.studentsinfo_layout);
Bundle b = getIntent().getBundleExtra("bundle");
ArrayList<StudInfo> studentVOList = (ArrayList<StudInfo>) b.getSerializable("list");
ListView listView = (ListView) findViewById(R.id.listViewShow);
ListAdapter listAdapter = new ListAdapter(this, R.layout.list_layout, R.id.txtName, studentVOList);
listView.setAdapter(listAdapter);
}
}
this is my StudInfo.java class,
import java.io.Serializable;
public class StudInfo implements Serializable
{
private String name;
private String surname;
private String age;
private String div;
private String standard;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDiv() {
return div;
}
public void setDiv(String div) {
this.div = div;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
}
i tried googling to find out solution but the questions i found all are based on searching listview items using edittext.i didn't found ant similar post matching with my question which solve my problem.can anyone please help me to solve this??
1. Override getFilter method in your adapter class
2. Use adapter.getFilter().filter(txt) in your spinner selection
package com.hughesnet.adapters;
import com.hughesnet.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
ItemFilter mFilter;
ArrayList<StudInfo> filteredData;
public ListAdapter (Context context, int vg, int id, ArrayList<StudInfo> list) {
super (context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView (int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate (vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById (R.id.txtName);
TextView textViewSurname = (TextView) itemView.findViewById (R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById (R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById (R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById (R.id.txtStandard);
textViewName.setText (list.get (position).getName ());
textViewSurname.setText (list.get (position).getSurname ());
textViewAge.setText (list.get (position).getAge ());
textViewDiv.setText (list.get (position).getDiv ());
textViewStd.setText (list.get (position).getStandard ());
return itemView;
}
ItemFilter mFilter = new ItemFilter ();
public Filter getFilter () {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering (CharSequence constraint) {
String filterString = constraint.toString ().toLowerCase ();
FilterResults results = new FilterResults ();
int count = list.size ();
final ArrayList<StudInfo> nlist = new ArrayList<StudInfo> (count);
String filterableString;
for (int i = 0; i < count; i++) {
StudInfo info = list.get (i);
// Check for standard, division and age here
if (info.getAge().contains(filterString) || info.getStandard().contains(filterString ) || info.getDiv().contains(filterString )) {
nlist.add (filterableString);
}
}
results.values = nlist;
results.count = nlist.size ();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<StudInfo>) results.values;
notifyDataSetChanged();
}
}
}

Open Navigator after clicked on a Rss Reader

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())));
}

Categories

Resources