I have a list with articles taken from an List and want to show the selected article in a PagerActivity so the user can easily flip to the article before and after when finished reading.
In iOS I can just pass the List (or a reference) with article objects to the PagerActivity. In Android however, calling on an Intent does not allow Lists to be passed on. So what would be the best way of doing it? Do I need to reload the array in the next Activity and then pass the position as an argument to the Intent?
(Reloading the List would be expensive, but should work if the DB hasn't changed since loading, otherwise the order might be different and the wrong item might be shown).
In Android
Used ParecleObjectif you have Custom Object ArrayList and if your have simple String ArrayList then pass directly in Intent
If you have Simple String ArrayList then refer below
Passing ArrayList of string arrays from one activity to another in android
and If you have Custom Object ArrayList then refer below
How to pass ArrayList<CustomeObject> from one activity to another?
Passing arraylist of objects between activities
Considering your list of type Department here:
public class Department implements Parcelable {
int department_id;
String title;
public Department() {
this.department_id = 0;
this.title = null;
}
public Department(int department_id, String title) {
this.department_id = department_id;
this.title = title;
}
public int getDepartmentId() {
return department_id;
}
public void setDepartmentId(int department_id) {
this.department_id = department_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flag) {
parcel.writeInt(department_id);
parcel.writeString(title);
}
public static final Creator<Department> CREATOR = new Creator<Department>(){
#Override
public Department createFromParcel(Parcel parcel) {
Department department = new Department();
department.setDepartmentId(parcel.readInt());
department.setTitle(parcel.readString());
return department;
}
#Override
public Department[] newArray(int size) {
return new Department[size];
}
};
}
List<Department> departments = new ArrayList<>();
Now you simply have to put this list in Intent Bundle like this
bundle.putParcelableArrayList("Departments_KEY", departments);
and receive the list in your child activity like this
List<Department> departments = getIntent() or getArguments().getParcelable("Departments_KEY");
Related
How to pass arraylist value (samplename, samplequote ) to the intent.putExtra.. for sharing the text..
In MainActivity.java
list = new ArrayList<>();
//loading list view item with this function
loadRecyclerViewItem();
}
private void loadRecyclerViewItem() {
list.add(new MyQuote("sample name","sample quote"));
In MyRecyclerViewAdapter.java
public void onBindViewHolder(final MyRecycleViewAdapter.ViewHolder myholder, int position) {
final MyQuote myQuote = myQuoteList.get(position);
myholder.tv_author.setText(myQuote.getAuthor());
myholder.tv_quote.setText(myQuote.getQuotedesc());
myholder.im_favlike.setImageResource(R.drawable.fav_border);
myholder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent (Intent.ACTION_SEND);
intent.setType("text/plain");
view.getContext().startActivity(Intent.createChooser(intent,"send to"));
}
});
}
EDIT
after implementing Parcelable in MyQuote class.. like this when i use intent.putParcelableArrayListExtra("mani" , MyQuote);....
i'm getting "expression expected ...in MyRecyclerViewAdapter.java"
public class MyQuote implements Parcelable{
private String author;
private String quotedesc;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(quotedesc);
parcel.writeString(author);
}
private MyQuote(Parcel parcel){
quotedesc = parcel.readString();
author = parcel.readString();
}
public static final Parcelable.Creator<MyQuote> CREATOR = new Parcelable.Creator<MyQuote>(){
#Override
public MyQuote createFromParcel(Parcel parcel) {
return new MyQuote(parcel);
}
public MyQuote[] newArray(int size){
return new MyQuote[size];
}
};
//constructor initializing values
public MyQuote(String author, String quotedesc) {
this.quotedesc = quotedesc;
this.author = author;
}
//getters
public String getAuthor() {
return author;
}
public String getQuotedesc() {
return quotedesc;
}
}
I have a recycler cardview which contains quotes,and authors.. as textviews..and a sharebutton.. in each card.. when user want to share the quote, author of a particular card.. he can share the quote(string) along with author(string) to apps like messeges, whatsapp ..etc..
how can i solve this ? is implementing parcelable is correct process..for this purpose or not..if it is correct what code should i use in onclick of a sharebutton
#Override
public void onBindViewHolder(final MyRecycleViewAdapter.ViewHolder myholder, int position) {
final MyQuote myQuote = myQuoteList.get(position);
myholder.tv_author.setText(myQuote.getAuthor());
myholder.tv_quote.setText(myQuote.getQuotedesc());
myholder.im_favlike.setImageResource(R.drawable.fav_border);
myholder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent (Intent.ACTION_SEND);
intent.putParcelableArrayListExtra("mani" , MyQuote);
intent.setType("text/plain");
view.getContext().startActivity(Intent.createChooser(intent,"send to"));
}
});
}
You have to implement Parcelable interface in MyQuote Class and then you can send it through intent like this :-
intent.putParcelableArrayListExtra(key_name,your_list);
The class of your array elements should implement Parcelable interface.
After doing so, you can use Intent.putParcelableArrayListExtra(ARRAY_LIST_KEY,fooArrayList) to send the array list and then Intent.getStringArrayListExtra(ARRAY_LIST_KEY) to retrieve the list
Hi check out this plugin Parcelable Code Generator.
It will help you to auto generate parcelable boilerplate for a POJO class and then you can directly use it as suggested by Abhishek
intent.putParcelableArrayListExtra(key_name, list);
I have an app on production, so changes has to be applied with a RealmMigration
I've looked the documentation and this example but I didn't find how to do the following.
In current version I have items of type Foo that has a boolean property called favorite.
Now I want to generalize that and create user custom Foo lists, so the users will be able to create their custom lists and add as many objects as they want.
I want to implement this with a new class called UserFooList with basically name and a RealmList<Foo>of elements.
In migration process I'm creating this new class with its fields.
That's easy, but here comes the difficult part:
I want to add all previous Foo items flagged with favorite to a new UserFooList and then remove the now unused Foo's field favorite
Some code to help to clarify:
Current class
public class Foo extends RealmObject{
private String title;
private boolean favorite;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isFavorite() {
return favorite;
}
public void setFavorite(boolean favorite) {
this.favorite = favorite;
}
}
Changed class
public class Foo extends RealmObject{
//favorite field will be removed
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
New class
public class UserFooList extends RealmObject{
private String name;
private RealmList<Foo> items;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public RealmList<Foo> getItems() {
return items;
}
public void setItems(RealmList<Foo> items) {
this.items = items;
}
}
I want to insert a UserFooList instance and populate it with:
name: "favorites"
items: all existing Foo instances with favorite == true
And I want to do it during Migration because in that way I will be able to remove favorite field after inserting all elements in the new created list.
Rely on the power of the DynamicRealm API.
public class MyMigration implements Realm.Migration {
#Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
if(oldVersion == 0) {
RealmObjectSchema foo = schema.get("Foo");
RealmObjectSchema userFooList = schema.create("UserFooList");
userFooList.addField("name", String.class);
userFooList.addRealmListField("items", foo);
DynamicRealmObject userList = realm.createObject("UserFooList");
userList.setString("name", "favorites");
RealmList<DynamicRealmObject> listItems = userList.getList("items");
RealmResults<DynamicRealmObject> favoriteFoos = realm.where("Foo").equalTo("favorite", true).findAll();
for(DynamicRealmObject fooObj: favoriteFoos) {
listItems.add(fooObj);
}
foo.removeField("favorite");
oldVersion++;
}
}
#Override public boolean equals(Object object) {
return object != null && object instanceof MyMigration;
}
#Override public int hashCode() {
return MyMigration.class.hashCode();
}
}
I have a POJO class. It holds some Strings and I want to pass values from RecyclerView to an Activity. I tried something and failed. How do I do that?
Model
public class DetailModel {
String title;
public DetailModel() {
}
public DetailModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Adapter, onClick
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
detailModel=new DetailModel();
detailModels= new ArrayList<>();
detailModel.setTitle(holder.headerText.getText().toString());
Intent detailIntent = new Intent(context.getApplicationContext(), DetailActivity.class);
context.startActivity(detailIntent);
}
});
Another Activity
DetailModel detailModel=new DetailModel();
detailBody.setText(detailModel.getTitle());
There is several ways to do that, but I will show you simplest one :
In your onBindViewHolder :
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,final int position) {
final MyView myHolder = (MyView) holder;
myHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
detailModel.setTitle(holder.headerText.getText().toString());
Intent detailIntent = new Intent(context, DetailActivity.class);
//To pass your class:
intent.putExtra("mypojo", details.get(position));
context.startActivity(detailIntent);
}
});
}
In this way you must implement Serializable in your POJO class :
public class DetailModel implements Serializable{
String title;
public DetailModel() {
}
public DetailModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
And in second Activity use this code to get class :
getIntent().getExtras().getSerializable("mypojo");
//also you can cast extra
DetailModel detailmodel=(Detailmodel) getIntent().getExtras().getSerializable("mypojo");
//if you implemented Parcelable
DetailModel detailmodel=(Detailmodel) getIntent().getExtras().getParcelable("mypojo");
This is the first way, in another and faster way is using Parcelable , checkout this answer but you must make some effort in Parcelable : how-to-send-an-object-from-one-android-activity-to-another-using-intent
I suggest you to use Parcelable maybe you need some time to learn it but you can feel speed difference in bigger classes.
Also if you have small amounts of Strings in your POJO, try to use intent extras instead of sending class like that :
intent.putExtra("model_name",pojo.getName());
//then get
getIntent().getExtras().getString("model_name");
A recycler view by itself doesn't hold any data. That is the job of your adapter. The recyclerview' a job is to display that data and intercept touch events. So on your click listener get a hold of the data(POJO object) and pass that to your activity.
I feel silly asking this, but how do I display a single object in an android layout after obtaining it's data from JSON? I know how to display data in a listview, but haven't learned how to display a single object. Do I need any kind of adapter?
Here's how I parse the data from Volley (I'm aware of libraries like Jackson and GSON):
public void parseDeal(JSONObject response) {
Deal dealItem = new Deal();
try {
dealItem.setId(response.getInt("id"));
dealItem.setHeadline(response.getString("headline"));
dealItem.setTimeStamp(response.getString("created_at"));
dealItem.setImge(response.getString("image_url"));
JSONObject mVendor = response.getJSONObject("vendor");
dealItem.setVendorPic(mVendor.getString("image_url"));
// how to adapt to the view?
} catch (JSONException e) {
e.printStackTrace();
}
}
There are certain JSON attributes in the object that may come back null, so I want to be able to handle those by changing their visibility in the view conditionally. I have done that in a list adapter before like this, but not sure if I need an adapter in this case:
if (!TextUtils.isEmpty(item.getHeadline())) {
headlineMsg.setText(item.getHeadline());
headlineMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
headlineMsg.setVisibility(View.GONE);
}
UPDATE
Here is my Deal object class.
public class Deal {
private int id;
private String headline, image, vendorPic, timeStamp;
public Deal() {
}
public Deal(int id, String image, String headline,
String vendorPic, String timeStamp) {
super();
this.id = id;
this.image = image;
this.headline = headline;
this.vendorPic = vendorPic;
this.timeStamp = timeStamp;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
public String getVendorPic() {
return vendorPic;
}
public void setVendorPic(String vendorPic) {
this.vendorPic = vendorPic;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
}
I think i can follow you're logic here. You should work on implementing a rendering class. This is called upon the loading of the visual component that holds all this information. The renderer should turn on and off the views that are not null. The rendering class is the actual code that takes the data you have pulled out of the json, checks it to make sure there is data actually there (not null) and sets the required view to the desired value.
if (dealItem.getTimeStamp() != null && dealItem.getTimeStamp() != "") {
LayoutView.setText(dealItem.getTimeStamp()));
LayoutView.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
LayoutView.setVisibility(View.GONE);
}
Why don't you simply create a Fragment or activity with TextViews (or whatever view you prefer...) ?
You don't need an adapter for that. Then you simply populate it on onCreate (activity) or fragment (onViewCreated) with the values from the object !
Hope it helps !
I have an Object that I need to pass via the Intent to another Activity via the onclick method.
I was following this answer here How to send an object from one Android Activity to another using Intents?
Which works fine however my Object has within it an Array of objects.
How do I pass this object with its Array of Objects?
Below are the classes before using Parcelable
List (the object to be passed)
public class List {
private String Name;
private ArrayList<ListItem> items;
public List(){
items = new ArrayList<ListItem>();
}
public void addItem(String title, String d, String s, int p){
ListItem i = new ListItem();
i.setDecription(d);
i.setPrice(p);
i.setSite(s);
i.setTitle(title);
items.add(i);
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getCount() {
return items.size();
}
public ArrayList<ListItem> getList(){
return items;
}
}
ListItem
public class ListItem {
private String title;
private String decription;
private String site;
private int price;
public void setTitle(String title) {
this.title = title;
}
public void setDecription(String d){
this.decription = d;
}
public void setSite(String s){
this.site = s;
}
public void setPrice(int i){
this.price = i;
}
public String getTitle(){
return title;
}
public String getDecription(){
return decription;
}
public String getSite(){
return site;
}
public int getPrice(){
return price;
}
}
So how would I use Parcelable on List to send the ArrayList as well.
THank you and if you need any more info please ask!
You're trying to pass around data that shouldn't normally be passed around. A list is an ideal candidate for an SQLite Database. Try that or another way to persist data in android: http://developer.android.com/guide/topics/data/data-storage.html
If you insist on using Parcelable:
How can I make my custom objects Parcelable?
Also don't use List as your own type, it's standard JAVA.