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
Related
Thanks to those who will try to help me!
First time I sent a message. I'm stuck with my parcel.
I try to send an object Neighbour in a recyclerView for a class DetailedNeighbour. After I send my variable to DetailedActivity.putExtra("DNeighbour", neighbour); is well equal to what I want and after in DetailedNeighbourActivity is equal to null.
Neighbour:
package com.openclassrooms.entrevoisins.model;
/**
* Model object representing a Neighbour
*/
public class Neighbour implements Parcelable {
/** Identifier */
private long id;
/** Full name */
private String name;
/** Avatar */
private String avatarUrl;
/** Adress */
private String address;
/** Phone number */
private String phoneNumber;
/** About me */
private String aboutMe;
/**
* Constructor
* #param id
* #param name
* #param avatarUrl
*/
public Neighbour(long id, String name, String avatarUrl, String address,
String phoneNumber, String aboutMe) {
this.id = id;
this.name = name;
this.avatarUrl = avatarUrl;
this.address = address;
this.phoneNumber = phoneNumber;
this.aboutMe = aboutMe;
}
public Neighbour (Parcel in){ //constructor //Protected ?
id =in.readLong(); //read and set saved values from parcel
name=in.readString();
avatarUrl=in.readString();
address=in.readString();
phoneNumber=in.readString();
aboutMe=in.readString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAboutMe() {
return aboutMe;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Neighbour neighbour = (Neighbour) o;
return Objects.equals(id, neighbour.id);
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public void writeToParcel(Parcel parcel, int flags) { // In this method you add all your class properties to the parcel which are needed to transfer.
parcel.writeString(name);
parcel.writeString(phoneNumber);
parcel.writeString(avatarUrl);
parcel.writeString(aboutMe);
parcel.writeString(address);
parcel.writeLong(id); /// for favoris ?
}
public static final Parcelable.Creator<Neighbour> CREATOR = new Parcelable.Creator<Neighbour>() { ///This is the method which is used to bind everything together. Nothing much is done here.
#Override
public Neighbour createFromParcel(Parcel in) {
return new Neighbour(in);
}
#Override
public Neighbour[] newArray(int size) {
return new Neighbour[size];
}
};
public static Creator<Neighbour> getCREATOR() {
return CREATOR;
}
#Override
public int describeContents() {
return 0;
}
}
RecyclerViewAdapter:
package com.openclassrooms.entrevoisins.ui.neighbour_list;
public class MyNeighbourRecyclerViewAdapter extends RecyclerView.Adapter<MyNeighbourRecyclerViewAdapter.ViewHolder> {
private final List<Neighbour> mNeighbours;
public MyNeighbourRecyclerViewAdapter(List<Neighbour> items) {
mNeighbours = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_neighbour, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Neighbour neighbour = mNeighbours.get(position);
holder.mNeighbourName.setText(neighbour.getName());
Glide.with(holder.mNeighbourAvatar.getContext())
.load(neighbour.getAvatarUrl())
.apply(RequestOptions.circleCropTransform())
.into(holder.mNeighbourAvatar);
holder.mNeighbourName.setOnClickListener(new View.OnClickListener() { /// Observe le clic sur bouton name
#Override
public void onClick(View view) {
Intent DetailedActivity = new Intent(view.getContext(), DetailedNeighbourActivity.class); //
DetailedActivity.putExtra("DNeighbour", neighbour);
view.getContext().startActivity(DetailedActivity);//
EventBus.getDefault();//
Log.i("DEBUG","l'utilisateur essaye d'ouvrir le détaille");
}
});
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventBus.getDefault().post(new DeleteNeighbourEvent(neighbour));
}
});
}
#Override
public int getItemCount() {
return mNeighbours.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_list_avatar)
public ImageView mNeighbourAvatar;
#BindView(R.id.item_list_name)
public TextView mNeighbourName;
#BindView(R.id.item_list_delete_button)
public ImageButton mDeleteButton;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
DetailedNeighboursActivity:
public class DetailedNeighbourActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_neighbour);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
Neighbour neighbour = (Neighbour) getIntent().getParcelableExtra("DNeighbour");
String name = neighbour.getName();
EventBus.getDefault();
Log.i("DEBUG", "Le détaille "+ name);
}
}
I'm not really smart ! Sorry for you time .
parcel and writeparcel constructor need the same order for variables. it's ok my code work.
I have a problem regarding the creation of an intent and the handover of an object with the getParcelableExtra() method to it.
The aim of the project is the creation of a recycler view. If an item from the recycler is selected a new intent gets started and should display more detailed data.
Because the data is fetched from an external MySQL DB I'm using Volley for most of the networking stuff.
The recycler is implemented inside the Volley onResponse() method which is first called at app start (onCreate). Until this point everything works fine and the recycler is loaded and displayed correctly.
public class UserAreaActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
initializeRecycler();
}
public void initializeRecycler() {
operations.getFoodFromDB(getFoodID(), new IDatabaseOperations() {
#Override
public void onSuccess(final ArrayList<Food> food_list) {
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLayoutmanager = new LinearLayoutManager(UserAreaActivity.this);
mAdapter = new FoodAdapter(food_list);
mRecyclerView.setLayoutManager(mLayoutmanager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new FoodAdapter.OnItemClickListener() {
#Override
public void OnItemClick(int position) {
Intent intent = new Intent(UserAreaActivity.this, FoodProfile.class);
GETS CORRECT OBJECT----->intent.putExtra("food", food_list.get(position));
startActivity(intent);
}
});
}
});
}
}
As you see I created an interface for the Volley onResponse method called onSuccess. Inside this method I am creating an onItemClickListener and this is where it gets ugly.
The onItemClickListener opens up the more detailed view of the item, but the method getParcelableExtra() returns NULL. Whatever I do it never returns an object of the class Food.
public class FoodProfile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_food_profile);
Food food = getIntent().getParcelableExtra("food");<----RETURNS NULL
String price = food.getPrice();
String name = food.getName();
String rating = ((Float)food.getRating()).toString();
String imageRes = food.getmimgId();
TextView mPrice = (TextView) findViewById(R.id.Price);
mPrice.setText(price);
TextView mName = (TextView) findViewById(R.id.Name);
mName.setText(name);
TextView mRating = (TextView) findViewById(R.id.Rating);
mRating.setText(rating);
}
}
So the putExtra() works as intended and gets the correct object of the food class. But getParcelableExtra() returns NULL everytime. So no value is displayed in the started intent.
Food class:
public class Food implements Parcelable {
public int id;
public String name;
public String category;
public String date;
public int vegan;
public int vegetarian;
public String price;
public String uuid;
public float rating;
public String mimgId;
public Food(int id, String name, String category, int vegan, int vegetarian, String price, String uuid, float rating, String mimgId){
this.id = id;
this.name = name;
this.category = category;
this.date = date;
this.vegan = vegan;
this.vegetarian = vegetarian;
this.price = price;
this.uuid = uuid;
this.rating = rating;
this.mimgId = mimgId;
}
protected Food(Parcel in) {
id = in.readInt();
name = in.readString();
category = in.readString();
date = in.readString();
vegan = in.readInt();
vegetarian = in.readInt();
price = in.readString();
uuid = in.readString();
rating = in.readFloat();
mimgId = in.readString();
}
public static final Creator<Food> CREATOR = new Creator<Food>() {
#Override
public Food createFromParcel(Parcel in) {
return new Food(in);
}
#Override
public Food[] newArray(int size) {
return new Food[size];
}
};
public int getId() {
return id;
}
public String getName() {
if(name != null) {
name = name.replaceAll(System.getProperty("line.separator"), (""));
}
return name;
}
public String getDate() {
return date;
}
public int isVegan() {
return vegan;
}
public int isVegetarian() {
return vegetarian;
}
public String getPrice() {
return price;
}
public String getUuid() {
return uuid;
}
public float getRating(){return rating;}
public String getmimgId() {
return mimgId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(price);
dest.writeString(name);
dest.writeString(((Float)rating).toString());
dest.writeString(mimgId);
}
}
Has anyone an idea whats causing the getParcelableExtra() to return null?
Thanks for your help in advance!
As I commented above, the writeToParcel() is problematic. The parcel should be written and read in the same order.
Please refer to the following pages as reference:
What is Parcelable in android
Using Parcelable
Understanding Androids Parcelable - Tutorial
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);
}
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'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"