I'm trying to pass data from a json file to a viewpager. I have followed most of the advice previously given to me here but it returns blank, without even crashing.
The four files involved in this:
1. The main fragment:
public class FashionFeed extends Fragment {
ViewPager viewPager;
PagerAdapter adapter;
ThePagerAdapter newdapter;
public static final String URL =
"http://celebirious.com/bey/data/space.json";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_whats_hot, null);
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPager.setClipToPadding(false);
viewPager.setPadding(4, 0, 4, 0);
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20 * 2, getResources().getDisplayMetrics());
viewPager.setPageMargin(-margin);
new SimpleTask().execute(URL);
return v;
}
private class SimpleTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// Create Show ProgressBar
}
protected String doInBackground(String... urls) {
String result = "";
try {
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader
(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return result;
}
protected void onPostExecute(String jsonString) {
showData(jsonString);
}
}
private void showData(String jsonString) {
Gson gson = new Gson();
Style style = gson.fromJson(jsonString, Style.class);
List<Space> space = style.getSpace();
newdapter = new ThePagerAdapter(getActivity(), space);
viewPager.setAdapter(newdapter);
}
}
The Adapter extending the Pager:
public class ThePagerAdapter extends PagerAdapter {
List<Space> list;
LayoutInflater inflater;
Context context;
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
public ThePagerAdapter(Context context,List<Space> list) {
this.list = list;
this.context = context; // red as well
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.styledeets, container,
false);
// Locate the TextViews in viewpager_item.xml
txtrank = (TextView) itemView.findViewById(R.id.date);
txtcountry = (TextView) itemView.findViewById(R.id.where);
txtpopulation = (TextView) itemView.findViewById(R.id.info);
// Capture position and set to the TextViews
txtrank.setText(list.get(position).getName());
txtcountry.setText(list.get(position).getDates());
txtpopulation.setText(list.get(position).getInfo());
String url = (list.get(position).getAvatarUrl());
imgflag = (ImageView) itemView.findViewById(R.id.photo);
Picasso.with(context)
.load(url)
.placeholder(R.mipmap.ic_launcher)
.error(R.drawable.ic_launcher_gmail)
.fit()
.tag(context)
.into(imgflag);
// Locate the ImageView in viewpager_item.xml
// Capture position and set to the ImageView
//imgflag.setImageResource(flag[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Gson data retreived from jsonschema2pojo.org:
Space.java
public class Space {
#Expose
private String name;
#Expose
private String dates;
#Expose
private String type;
#Expose
private String social;
#Expose
private String info;
#SerializedName("avatar_url")
#Expose
private String avatarUrl;
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The dates
*/
public String getDates() {
return dates;
}
/**
*
* #param dates
* The dates
*/
public void setDates(String dates) {
this.dates = dates;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* #return
* The social
*/
public String getSocial() {
return social;
}
/**
*
* #param social
* The social
*/
public void setSocial(String social) {
this.social = social;
}
/**
*
* #return
* The info
*/
public String getInfo() {
return info;
}
/**
*
* #param info
* The info
*/
public void setInfo(String info) {
this.info = info;
}
/**
*
* #return
* The avatarUrl
*/
public String getAvatarUrl() {
return avatarUrl;
}
/**
*
* #param avatarUrl
* The avatar_url
*/
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
Lastly, Style.java
public class Style {
#Expose
private List<Space> space = new ArrayList<Space>();
/**
*
* #return
* The space
*/
public List<Space> getSpace() {
return space;
}
/**
*
* #param space
* The space
*/
public void setSpace(List<Space> space) {
this.space = space;
}
}
All the xml data is properly linked 'cause this all works when it is retrieving data locally. What could be wrong?
I figured this out !!!!! How silly of me.
Was
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
should have been:
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
Related
I am developing an app in android studio in which contents are coming form an Api in a recyclerview. In the api there is an element "content" that sends all html tags with images like a full page. I have to display that page in textview. I have tried Htm.fromHtml method but it is not displaying the images. I have searched all answers and got the solution of ImageGetter method, but I am not able to display dynamic content in the recycleradapter from ImageGetter. I have to keep the images in the drawable of my app and match the source URL that is being parsed. Please help. Below is my code.
PageActivity.java
public class PageActivity extends AppCompatActivity {
RequestQueue queue;
String menuidpage;
RecyclerView recyclerView;
List<MenuFeeds> feedsList = new ArrayList<MenuFeeds>();
String newimage = "http://www.groveus.com/micro/assets/uploads/page/";
PageRecyclerAdapter adapter;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle bundle=getIntent().getExtras();
menuidpage=bundle.getString("page_id");
recyclerView = (RecyclerView) findViewById(R.id.recyclerviewpage);
pDialog = new ProgressDialog(this);
adapter = new PageRecyclerAdapter(this, feedsList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
//Getting Instance of Volley Request Queue
queue = NetworkController.getInstance(this).getRequestQueue();
//Volley's inbuilt class to make Json array request
pDialog.setMessage("Loding...");
pDialog.show();
String url = "http://www.groveus.com/micro/api/index.php/pages/view?
id="+menuidpage;
JsonArrayRequest menuReq = new JsonArrayRequest(url, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pDialog.dismiss();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MenuFeeds feeds = new MenuFeeds(obj.getInt("page_id"),
obj.getString("status"), obj.getString("title"),
newimage+obj.getString("image"),obj.getString("content"));
// adding movie to movies array
feedsList.add(feeds);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
//Notify adapter about data changes
adapter.notifyItemChanged(i);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
pDialog.dismiss();
}
});
//Adding JsonArrayRequest to Request Queue
queue.add(menuReq);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
PageRecyclerAdapter.java
public class PageRecyclerAdapter extends
RecyclerView.Adapter<PageRecyclerAdapter.MyViewHolder> implements
View.OnTouchListener
{
private List<MenuFeeds> feedsList;
private Context context;
private LayoutInflater inflater;
public PageRecyclerAdapter(Context context, List<MenuFeeds> feedsList) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.list_layout5, parent, false);
return new MyViewHolder(rootView);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final MenuFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
//holder.idmenu.setText(feeds.getMenuId());
//holder.title.setText(feeds.getFeedName());
/* holder.description.setText(Html.fromHtml(feeds.getDescription(), 0,
new Html.ImageGetter() {
#Override
public Drawable getDrawable(String s) {
int id;
if
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT
INFECTION 1.png")) {
id = R.drawable.urin1;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT
INFECTION 2.png")) {
id = R.drawable.urin2;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE
INFECTION 1.png")) {
id = R.drawable.skinsoft1;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE
INFECTION 2.png")) {
id = R.drawable.skinsoft2;
}
else if
(s.equals("http://groveus.com/micro/assets/images/RESPIRATORY TRACT
INFECTION.png")) {
id = R.drawable.respo;
}
else if (s.equals("http://groveus.com/micro/assets/images/LOCAL
BACTERIAL INFECTIONS.png")) {
id = R.drawable.local;
}
else if
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION
2nd 1.png")) {
id = R.drawable.urine2nd1;
}
else if
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION
2nd 2.png")) {
id = R.drawable.urine2nd2;
}
else if
(s.equals("http://groveus.com/micro/assets/images/table.png")) {
id = R.drawable.table;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/table 2.png")) {
id = R.drawable.table2;
}
else {
return null;
}
Drawable d = context.getResources().getDrawable(id);
d.setBounds(0,0,1020,600);
return d;
}
}, null));*/
holder.description.setText(Html.fromHtml(feeds.getDescription()));
holder.description.setOnTouchListener(this);
holder.description.setMovementMethod(new ScrollingMovementMethod());
holder.imageview.setImageUrl(feeds.getImgURL(),
NetworkController.getInstance(context).getImageLoader());
// holder.ratingbar.setProgress(feeds.getRating());
}
#Override
public int getItemCount() {
return feedsList.size();
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title,description;
private NetworkImageView imageview;
//private ProgressBar ratingbar;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.ImageNameTextView);
description = (TextView) itemView.findViewById(R.id.desc);
//idmenu = (TextView) itemView.findViewById(R.id.ImageNameTextView2);
UrlImageParser p=new UrlImageParser(description,context);
// Volley's NetworkImageView which will load Image from URL
imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
MenuFeeds.java
public class MenuFeeds
{
private String imgURL, feedName, description,page;
//private String id;
private int id;
public MenuFeeds(int menuid, String page, String name, String imgurl,String
desc) {
this.id=menuid;
this.page=page;
this.feedName = name;
this.imgURL = imgurl;
this.description = desc;
//this.rating = rating;
}
public int getMenuId() {
return id;
}
public String getPageID()
{
return page;
}
public String getDescription() {
return description;
}
public String getImgURL() {
return imgURL;
}
public String getFeedName() {
return feedName;
}
}
I also faced a similar problem month ago and used this and it works fine :
String htmlData = listData.get(position).getValue();
String showData = htmlData.replace("\n", "");
URLImageParser p = new URLImageParser(holder.textt, context);
Spanned htmlAsSpanned = Html.fromHtml(showData,p,null);
holder.yourTextView.setText(htmlAsSpanned);
Now copy and paste these 2 methods :
First method :
public class URLDrawable extends BitmapDrawable {
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
if(drawable != null) {
drawable.draw(canvas);
}
}
}
///Second Method :
public class URLImageParser implements Html.ImageGetter {
Context c;
TextView container;
/***
* Construct the URLImageParser which will execute AsyncTask and refresh the container
* #param t
* #param c
*/
public URLImageParser(TextView t, Context c) {
this.c = c;
this.container = t;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
// return reference to URLDrawable where I will change with actual image from
// the src tag
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
#Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
#Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.container.invalidate();
URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
+ result.getIntrinsicHeight()));
}
/***
* Get the Drawable from URL
* #param urlString
* #return
*/
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
} `enter code here`catch (Exception e) {
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
}
try this
load your image using piccaso
add below library in your build.gradle
implementation 'com.squareup.picasso:picasso:2.71828'
when you need to set image use piccaso this way
Picasso.get()
.load(your_image)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.your_error_image_or_blank)
.into(your_imageView);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm doing some project and I'm stuck ... I'm doing something wrong, probably with AsyncTask and I have no idea what to fix and how .... there is code I have right now.
ReviewData.class
public class ReviewData implements Parcelable {
private String mAuthor, mContent;
public ReviewData(String author, String content) {
this.mAuthor = author;
this.mContent = content;
}
private ReviewData(Parcel in) {
mAuthor = in.readString();
mContent = in.readString();
}
public static final Creator<ReviewData> CREATOR = new Creator<ReviewData>() {
#Override
public ReviewData createFromParcel(Parcel in) {
return new ReviewData(in);
}
#Override
public ReviewData[] newArray(int size) {
return new ReviewData[size];
}
};
//Getter method for review author
public String getAuthor() {
return mAuthor;
}
//Setter method for review author
public void setAuthor(String author) {
this.mAuthor = author;
}
//Getter method for review content
public String getContent() {
return mContent;
}
//Setter method for review content
public void setContent(String content) {
this.mContent = content;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mAuthor);
dest.writeString(mContent);
}
}
ReviewAdapter.class
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ReviewViewHolder> {
private ArrayList<ReviewData> mReviewList;
private Context mContext;
public ReviewAdapter(Context context, ArrayList<ReviewData> reviewList) {
this.mContext = context;
this.mReviewList = reviewList;
}
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
View view = LayoutInflater.from(mContext).inflate(R.layout.review_item_list,
parent, false);
view.setFocusable(true);
return new ReviewViewHolder(view);
}
#Override
public void onBindViewHolder(final ReviewViewHolder holder, int position) {
if(mReviewList != null) {
ReviewData reviewData = mReviewList.get(position);
holder.reviewAuthor.setText(reviewData.getAuthor());
holder.reviewContent.setText(reviewData.getContent());
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
if(mReviewList == null) {
return 0;
} else {
return mReviewList.size();
}
}
public void setReviewList(ArrayList<ReviewData> reviewList) {
if(reviewList != null) {
mReviewList = new ArrayList<>(reviewList);
}
notifyDataSetChanged();
}
public class ReviewViewHolder extends RecyclerView.ViewHolder {
TextView reviewAuthor;
TextView reviewContent;
public ReviewViewHolder(View itemView) {
super(itemView);
reviewAuthor = itemView.findViewById(R.id.review_author);
reviewContent = itemView.findViewById(R.id.review_content);
}
}
}
NetworkUtils.class (but only code for Review url builder, for other thing works perfectly). PS. this parse is written as API documentation said ... it should be someurl/movie/{id}/reviews
//URL builder for reviews
public static URL buildReviewUrl(String id) {
Uri builtUri = Uri.parse(BASE_MOVIE_URL + id + REVIEW).buildUpon()
.appendQueryParameter(QUERY_API_KEY, API_KEY)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
JsonData. class (also, only for Reviews, for other works perfectly...)
//JSON for Review
public static ArrayList<ReviewData> getReviewFromJson(String json) throws JSONException {
ArrayList<ReviewData> listOfReviews = new ArrayList<>();
try {
JSONObject reviews = new JSONObject(json);
JSONArray reviewsArray = reviews.getJSONArray(QUERY_RESULTS);
for(int i = 0; i < reviewsArray.length(); i++) {
JSONObject jsonReview = reviewsArray.getJSONObject(i);
String author = jsonReview.optString(REVIEW_AUTHOR);
String content = jsonReview.optString(REVIEW_CONTENT);
ReviewData reviewData = new ReviewData(author, content);
listOfReviews.add(reviewData);
}
} catch(JSONException e) {
e.printStackTrace();
Log.e("ReviewJson", "JSON Review Error");
}
return listOfReviews;
}
ReviewAsyncTask.class
public class ReviewAsyncTask extends AsyncTask<String, Void, ArrayList<ReviewData>> {
private ReviewData mReviewData;
public interface ReviewResponse {
void finished(ArrayList<ReviewData> output);
}
private ReviewResponse reviewResponse = null;
public ReviewAsyncTask(ReviewResponse reviewResponse) {
this.reviewResponse = reviewResponse;
}
#Override
protected ArrayList<ReviewData> doInBackground(String... strings) {
String rawData = "";
ArrayList<ReviewData> reviewList = new ArrayList<>();
try {
rawData = NetworkUtils.getResponseFromHttpRequest(NetworkUtils
.buildReviewUrl(String.valueOf(mReviewData)));
reviewList = JsonData.getReviewFromJson(rawData);
} catch (IOException e) {
e.printStackTrace();
Log.e("ReviewAsyncTask", "Error in ReviewAsyncTask");
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONAsync", "JSON problem");
}
return reviewList;
}
#Override
protected void onPostExecute(ArrayList<ReviewData> reviewData) {
reviewResponse.finished(reviewData);
}
}
and MovieDetails activity (everything works fine except from the comment recycle review to next comment.
public class MovieDetails extends AppCompatActivity implements ReviewAsyncTask.ReviewResponse {
private final static String BASE_URL = "http://image.tmdb.org/t/p/";
private final static String SIZE = "w185/";
private ArrayList<ReviewData> mReviewList;
private ReviewAdapter mReviewAdapter;
#BindView(R.id.poster_detail)
ImageView mMoviePoster;
#BindView(R.id.title_detail)
TextView mMovieTitle;
#BindView(R.id.release_date)
TextView mReleaseDate;
#BindView(R.id.average_vote)
TextView mAverageVote;
#BindView(R.id.synopsis)
TextView mSynopsis;
#BindView(R.id.review_recycler)
RecyclerView mReviewRecycle;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
ButterKnife.bind(this);
displayMovieDetail();
//Review RecycleView
mReviewList = new ArrayList<>();
mReviewAdapter = new ReviewAdapter(this, mReviewList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mReviewRecycle.setLayoutManager(layoutManager);
mReviewRecycle.setHasFixedSize(true);
mReviewRecycle.setAdapter(mReviewAdapter);
}
#Override
public void finished(ArrayList<ReviewData> output) {
ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this);
reviewAsyncTask.execute();
}
/* Method for displaying the info about movies in activity details
* #param mMoviePoster sets the movie poster
* #param mMovieTitle sets original title of the movie
* #param mReleaseDate sets release date of the movie
* #param mAverageVote sets average rating grade of the movie
* #param mSynopsis sets plot of the movie */
private void displayMovieDetail() {
int idMovie = (Integer) getIntent().getExtras().get(getString(R.string.movie_id));
List<MovieData> movieList;
movieList = getIntent().getParcelableArrayListExtra(getString(R.string.movie_lsit));
MovieData movieData = movieList.get(idMovie);
Picasso.with(mContext).load(BASE_URL + SIZE +
movieData.getPoster()).into(mMoviePoster);
mMovieTitle.setText(movieData.getTitle());
mReleaseDate.setText(movieData.getReleaseDate());
mAverageVote.setText(Double.toString(movieData.getRating()));
mSynopsis.setText(movieData.getSynopsis());
}
}
P.S. I would share github link but I should give you my personal API key. :(
You need to start the AsyncTask in onCreate() (like you did before) and in finished() you take the results and add them to the Adapter's data list.
Finally, don't forget to call notifyDatasetChanged().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
// skipping some lines of code here...
mReviewRecycle.setAdapter(mReviewAdapter);
ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this);
reviewAsyncTask.execute();
}
#Override
public void finished(ArrayList<ReviewData> output) {
mReviewList.addAll(output);
mReviewAdapter.notifyDatasetChanged();
}
(Please note that I skipped null checks and error handling for brevity's sake)
In MovieDetails onCreate retrieve current movie ID like you do in displayMovieDetail.
Send that ID to ReviewAsyncTask (you'll need to modify constructor of ReviewAsyncTask)
Retrieve id in ReviewAsyncTask, save it as member variable, and then in doInBackground method send that id to buildReviewUrl as an argument.
I want to update a textview into a listView when i get my current position (GPS).
So i send a broadcast in my activity when i had my position. In my listViewAdapter, i have a receiver who set text. But i don't know where i can registrer and unregistrer my broadcast.
May be there is an other solution to send parameter to my listViewAdapter when my current position is available.
MainActivity :
private ArrayList<Establishment> listEstablishment;
private ListViewEstablishmentsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
pr = new PositionReceiver();
//Get the list view
ListView l = (ListView) findViewById(R.id.listviewEstablishments);
//Create WebService to retrieve establishments datas
EstablishmentInfosWebService ews = new EstablishmentInfosWebService("select * from establishment");
listEstablishment = ews.getData();
//Create a new adapter View
adapter = new ListViewEstablishmentsAdapter(this, listEstablishment);
l.setAdapter(adapter);
public class PositionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Location l = (Location) intent.getExtras().get("LOCATION");
int i = 0;
for(Establishment e : listEstablishment) {
double d = distance(e.getLatitude(), e.getLongitude(), l.getLatitude(), l.getLongitude(), 'K');
e.setDistance(d+"");
Log.d(TAG,"onreceive "+i);
i++;
}
}
}
#Override
public void onResume() {
super.onResume();
registerReceiver(pr, new IntentFilter("com.example.smartoo.POSITION_INTENT"));
}
/*
* Called when the Activity is going into the background.
* Parts of the UI may be visible, but the Activity is inactive.
*/
#Override
public void onPause() {
unregisterReceiver(pr);
super.onPause();
}
ListViewAdapter :
public class ListViewEstablishmentsAdapter extends BaseAdapter {
private static final String TAG = "com.example.smartoo.ListViewEstablishmentAdapter";
//Un mécanisme pour gérer l'affichage graphique depuis un layout XML
private LayoutInflater mInflater;
//Le contexte dans lequel est présent notre adapter
private final Context context;
// Une liste d'établissements
private ArrayList<Establishment> establishmentsList = null;
private ViewHolder holder;
//TODO add my currentLocation to constructor
/**
*
* #param context
* #param values
*
* Constructor
*/
public ListViewEstablishmentsAdapter(Context context, ArrayList<Establishment> values) {
super();
this.context = context;
establishmentsList = values;
mInflater = LayoutInflater.from(context);
}
/**
* #return number of establishments
*/
#Override
public int getCount() {
return establishmentsList.size();
}
/**
* #param position
* #return Establishment to position "position"
*/
#Override
public Object getItem(int position) {
return establishmentsList.get(position);
}
/**
* #param position
* #return The position of item
*/
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//ViewHolder holder = null;
// Si la vue n'est pas recyclée
if (convertView == null) {
// On récupère le layout
convertView = mInflater.inflate(R.layout.item, null);
holder = new ViewHolder();
// On place les widgets de notre layout dans le holder
holder.Name = (TextView) convertView.findViewById(R.id.name);
holder.Description = (TextView) convertView.findViewById(R.id.description);
holder.Distance = (TextView) convertView.findViewById(R.id.distance);
// puis on insère le holder en tant que tag dans le layout
convertView.setTag(holder);
}
else {
// Si on recycle la vue, on récupère son holder en tag
holder = (ViewHolder) convertView.getTag();
}
// Dans tous les cas, on récupère le contact téléphonique concerné
Establishment e = (Establishment) getItem(position);
// Si cet élément existe vraiment…
if (e != null) {
// On place dans le holder les informations sur le contact
holder.Name.setText(e.getName());
holder.Description.setText(e.getDescription());
//TODO calculate distance with my position and longitude and latitdue
holder.Distance.setText(e.getDistance());
}
return convertView;
}
static class ViewHolder {
public TextView Name;
public TextView Description;
public TextView Distance;
}
public void updateEstablishmentList(ArrayList<Establishment> newlist) {
establishmentsList.clear();
establishmentsList.addAll(newlist);
this.notifyDataSetChanged();
}
}
Establishment :
public class Establishment {
//An identifer
private int idEstablishment;
//A Name
private String name;
//An address
private String address;
//An url picture
private String urlImage;
//A description
private String description;
//A phone number
private String phoneNumber;
//A type of establishment_fragment
private int type;
//A location
private double latitude;
private double longitude;
//A distance
private String distance = "0m";
public Establishment () {
super();
idEstablishment = 0;
name = "";
address = "";
urlImage = "";
description = "";
phoneNumber = "";
type = 0;
latitude = 0;
longitude = 0;
}
/**
*
* #param id
* #param n
* #param url
* #param d
* #param p
* #param t
* #param lat
* #param lon
*
* Constructor
*/
public Establishment (int id, String n, String a, String url, String d, String p, int t, double lat, double lon) {
idEstablishment = id;
name = n;
address = a;
urlImage = url;
description = d;
phoneNumber = p;
type = t;
latitude = lat;
longitude = lon;
}
public int getIdEstablishment() {
return idEstablishment;
}
public void setIdEstablishment(int idEstablishment) {
this.idEstablishment = idEstablishment;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUrlImage() {
return urlImage;
}
public void setUrlImage(String urlImage) {
this.urlImage = urlImage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
Manifest :
<activity
android:name=".HomeActivity"
android:label="Home"
android:theme="#style/Theme.AppCompat.Light" >
<action android:name="android.location.PROVIDERS_CHANGED" />
<receiver android:name=".PositionReceiver">
<intent-filter>
<action android:name="com.example.smartoo.POSITION_INTENT">
</action>
</intent-filter>
</receiver>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
** ANSWER : **
public void updateEstablishmentList(ArrayList<Establishment> newlist) {
establishmentsList = newlist;
this.notifyDataSetChanged();
}
You shouldn't put the BroadcastReceiver in the Adapter, it doesn't belong there. Put it in the Activity or Fragment which contains the ListView. To pass a new location to the ListView you need to implement a method to set the location to a specific row in the Adapter:
Of course your class Establishment needs to contain a field to store the Location along with appropriate getters and setters:
public void setLocationAtPosition(int position, Location location) {
Establishment e = (Establishment) getItem(position);
e.setLocation(location);
notifyDataSetChanged();
}
And in getView() of your Adapter:
Establishment e = (Establishment) getItem(position);
if (e != null) {
holder.Name.setText(e.getName());
holder.Description.setText(e.getDescription());
Location location = e.getLocation();
double longitude = location.getLongitude();
double latitude = location.getLatitude()
holder.Distance.setText(longitude + "/" + latitude);
}
I have to pass a ArrayList from one activity to another activity. So I use
intent.putParcelableArrayListExtra("Items",sendinglist);
And I get the sendinglist through
ArrayList<GeoItem> revd = new ArrayList<GeoItem>();
Bundle b = getIntent().getExtras();
if (b != null)
revd = b.getParcelableArrayList("Items");
Log.i("Element details",revd.get(0).getLatitude()+"");// Error
But i cant access the GeoItem object in that list.
UPDATE the class based on the answers...
My GeoItem class is
public class GeoItem implements Parcelable, Serializable {
/** id of item. */
protected long id_;
/** item location in GeoPoint. */
// protected GeoPoint location_;
/** selection state flag. true if selected. */
protected boolean isSelected_;
protected int latitude;
protected int longitude;
protected String incident_no;
protected String title;
protected String date;
protected String address;
/**
* #param id
* item id.
* #param latitudeE6
* latitude of the item in microdegrees (degrees * 1E6).
* #param longitudeE6
* longitude of the item in microdegrees (degrees * 1E6).
*/
public GeoItem(long id, int latitudeE6, int longitudeE6, String inc_no,
String tlt, String dates, String addr) {
id_ = id;
// location_ = new GeoPoint(latitudeE6, longitudeE6);
isSelected_ = false;
incident_no = inc_no;
title = tlt;
date = dates;
address = addr;
latitude=latitudeE6;
longitude=longitudeE6;
}
public long getId_() {
return id_;
}
public void setId_(long id_) {
this.id_ = id_;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void setIncident_no(String incident_no) {
this.incident_no = incident_no;
}
public int getLatitude() {
return latitude;
}
public void setLatitude(int latitude) {
this.latitude = latitude;
}
public int getLongitude() {
return longitude;
}
public void setLongitude(int longitude) {
this.longitude = longitude;
}
/**
* #param src
* source GeoItem
*/
public GeoItem(GeoItem src) {
id_ = src.id_;
// location_ = new
// GeoPoint(src.location_.getLatitudeE6(),src.location_.getLongitudeE6());
isSelected_ = src.isSelected_;
}
/**
* #param src
* source Parcel
*/
public GeoItem(Parcel src) {
id_ = src.readLong();
// location_ = new GeoPoint(src.readInt(), src.readInt());
isSelected_ = src.readInt() == 0 ? false : true;
address = src.readString();
date = src.readString();
}
/* describeContents */
public int describeContents() {
return 0;
}
/**
* getId
*
* #return id of the item.
*/
public long getId() {
return id_;
}
public String getIncident_no() {
return incident_no;
}
/**
* setId
*
* #param id
* of the item.
*/
public void setId(long id) {
id_ = id;
;
}
/**
* getLocation
*
* #return GeoPoint of the item.
*
* public GeoPoint getLocation() { return location_; }
*/
/**
* isSelected
*
* #return true if the item is in selected state.
*/
public boolean isSelected() {
return isSelected_;
}
/**
* setSelect
*
* #param flg
* flag to be set.
*/
public void setSelect(boolean flg) {
isSelected_ = flg;
}
/**
* Parcelable.Creator
*/
public static final Parcelable.Creator<GeoItem> CREATOR = new Parcelable.Creator<GeoItem>() {
public GeoItem createFromParcel(Parcel in) {
return new GeoItem(in);
}
public GeoItem[] newArray(int size) {
return new GeoItem[size];
}
};
/**
* writeToParcel
*
* #param parcel
* Parcel to be written.
* #param flags
* flag.
*/
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(id_);
parcel.writeString(address);
parcel.writeString(date);
parcel.writeInt(latitude);
parcel.writeInt(longitude);
int flg = isSelected_ ? 1 : 0;
parcel.writeInt(flg);
}
}
Please provide me the best way...
GeoPoint is not a Parceable therefore it can be marshalled. You may want to save the data somehow without GeoPoint or extend GeoPoint so it implements Parceable
**To pass an arraylist of Category to another activity,**
intent i = new Intent(_av.getContext(), ItemList.class);
Bundle b = new Bundle();
b.putParcelableArrayList("categories", categories);
b.putInt("index", _index);
i.putExtras(b);
startActivityForResult(i, ITEM_LIST);
**To retrieve the data,**
Bundle b = this.getIntent().getExtras();
ArrayList<Category> cats = b.getParcelableArrayList("categories");
int index = b.getInt("index");
My actual task is to send the list of GeoItems object through intent. Also My GeoItems class is serializable . Obviously list of serializable object is also serialibale So I used,
Intent listview = new Intent(context, ReportList.class);
Bundle send = new Bundle();
send.putSerializable("Items", (Serializable) items);
listview.putExtras(send);
context.startActivity(listview);
where items is a list of GeoIems objects
And in receiving activity,
Bundle b = this.getIntent().getExtras();
if (b != null) {
data = (List<GeoItem>) b.getSerializable("Items");
}
where data is a list of GeoIems objects
Without using Parceable interface, now i can set my list of serializable objects through intent to next activity
I'm getting a json exception when I try to run my code.
The problem happens on the onclick listener. I'm trying to have the application go to the article of the rss feed on click
Here is the main activity
public class Blocku extends ListActivity {
private RssListAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<JSONObject> jobs = new ArrayList<JSONObject>();
try {
jobs = BlockuReader.getLatestRssFeed();
} catch (Exception e) {
Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
}
adapter = new RssListAdapter(this,jobs);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String link = null;
try {
String url = Article.getUrl().toString();
link = adapter.getItem(position).getString(url).toString();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(link));
startActivity(i);
} catch (JSONException e) {
Context context = getApplicationContext();
CharSequence text = "error";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
e.printStackTrace();
}
}
}
here is the adapter:
public class RssListAdapter extends ArrayAdapter<JSONObject> {
public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts) {
super(activity, 0, imageAndTexts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
// Inflate the views from XML
View rowView = inflater.inflate(R.layout.image_text_layout, null);
JSONObject jsonImageText = getItem(position);
//////////////////////////////////////////////////////////////////////////////////////////////////////
//The next section we update at runtime the text - as provided by the JSON from our REST call
////////////////////////////////////////////////////////////////////////////////////////////////////
TextView textView = (TextView) rowView.findViewById(R.id.job_text);
try {
Spanned text = (Spanned)jsonImageText.get("text");
textView.setText(text);
} catch (JSONException e) {
textView.setText("JSON Exception");
}
return rowView;
}
}
and the article class
public class Article {
private long articleId;
private long feedId;
private String title;
private String description;
private String pubDate;
private static URL url;
private String encodedContent;
private static String link;
/**
* #return the articleId
*/
public long getArticleId() {
return articleId;
}
/**
* #param articleId the articleId to set
*/
public void setArticleId(long articleId) {
this.articleId = articleId;
}
/**
* #return the feedId
*/
public long getFeedId() {
return feedId;
}
/**
* #param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
/**
* #return the title
*/
public String getTitle() {
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #return the url
*/
public static URL getUrl() {
return url;
}
/**
* #param url the url to set
*/
public void setUrl(URL url) {
Article.url = url;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
/**
* #return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* #param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
}
/**
* #return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
}
JSONException is usually thrown when there are issues with parsing. Check how you are parsing the JSON. this says that you are trying to get a value for a key named "then it lists the site i want"