Broadcast receiver in BaseAdaper - java

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

Related

Cannot display images in Html.fromHtml() in text view for images coming dynamically

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

Method getParcelableExtra() returns null when creating an intent

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

From Json To ViewPager

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

Android: Exception Unmarshalling unknown type

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

error when setting an onclick to a listview/json

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"

Categories

Resources