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.
Related
I've already tried to use
String mystring = getResources().getString(R.string.mystring);
And I found the same theme in this article How can I convert the android resources int to a string. eg.: android.R.string.cancel?. But it doesn't work in my situation.
This is my code:
public class Film{
private int image;
private String name;
private String schedule;
private String description;
public Film() {
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
...
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class FilmList {
public static ArrayList<Film> getFilms(){
ArrayList<Film>films=new ArrayList<>();
Film film=null;
film =new Film();
film.setName(getResources().getString(R.string.name1));
film.setImage(R.drawable.img1);
film.setDescription(getResources().getString(R.string.desc1));
films.add(film);
film =new Film();
film.setName(getResources().getString(R.string.name2));
film.setImage(R.drawable.img2);
film.setDescription(getResources().getString(R.string.desc2));
films.add(film);
return films
}
}
If you don't have access to a Context (e.g. via an Activity, Service, ContentProvider, or BroadcastReceiver), you cannot get a string resource.
If you have a class that is not one of the above and it needs to get a string resource, you must either have pass a Context to that class so it can retrieve the resource, or pass that class an already-resolved resource.
Make an application class and add a hold its reference in a static varialble. then you can access context anywhere in the app
public class MyApp extends Application {
private static AppLWP instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
Then you can access this instance for context anywhere in the app
public static ArrayList<Film> getFilms(){
ArrayList<Film>films=new ArrayList<>();
Film film=null;
film =new Film();
film.setName(MyApp.instance.getResources()
.getString(R.string.name1));
film.setImage(R.drawable.img1);
film.setDescription(MyApp.instance.getResources()
.getString(R.string.desc1));
films.add(film);
film =new Film();
film.setName(MyApp.instance.getResources()
.getString(R.string.name2));
film.setImage(R.drawable.img2);
film.setDescription(MyApp.instance.getResources()
.getString(R.string.desc2));
films.add(film);
return films
}
}
First, provide context to the class Film via the activity you are calling the object of Film.
If you call from Main Activity you will have to do something like this:
public class MainActivty extends AppCompatActivity {
private static MainActivty obj;
onCreate() {
//usual functions
obj = MainActivity.this;
}
}
Once you have the context, simply try this:
String mystring = context.getString(R.string.mystring);
Or, if you floowed my MainActivty method:
String mystring = MainActivty.obj.getResources().getString(R.string.mystring);
I am currently building an app to retrieve information for a remote server. the data received are JSON and I am build a list of Data using the class below :
public class RedditData {
private RedditTopic data;
public RedditTopic getData() {
return data;
}
}
and RedditTopic class is defined as below:
public final class RedditTopic {
private static final String TAG = RedditTopic.class.getSimpleName();
private String author;
private String thumbnail;
private String title;
private String num_comments;
private long created_utc;
private String data;
private String name;
public RedditTopic(){};
public String getData() {
return data;
}
public String getAuthor() {
return author;
}
public String getThumbnail(){
return thumbnail;
}
public String getTitle(){
return title;
}
public String getComments(){
return num_comments + " comments";
}
public long getCreated_utc(){
return created_utc;
}
public String getRedditName(){
return name;
}
}
both of these classes are used to translate a JSON into an Object formatted data.
I do not want to really change them to make them Parceable to avoid impacting the extraction of JSON.
I have added :
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> SAVE");
savedInstanceState.putParcelableArrayList("RedditList", myListOfData );
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> RESTORE");
List<RedditData> myListOfData = savedInstanceState.getParcelableArrayList("RedditList");
}
Android complain because I need to implement Parceable in my class RedditData and I assume probably in the RedditTopic Class as well because RedditData returned a List of RedditTopic.
Is there a better way to do it? keep the List as I have it without requiring the Parceable option.
I do not have a List of String, it's a list of object.
Any idea?
Regards
Make your model objects parcleable.
There is a great extension, https://plugins.jetbrains.com/plugin/7332-android-parcelable-code-generator that will generate the neccesary parcelable methods for your class.
I highly recommend it.
I recently heard about Realm for android (also available for iOS) in this talk by Joaquim Verques . Very interesting and very powerful tool for persistent data.
I decided to give it a try after the video, researching and reading the documentation.
I found it very easy to use and set up but i end up stuck in the middle of my project because i couldn't manage to successfully make a query with many to many relationships.
I have created a small example for this topic.
My models:
public class Feed extends RealmObject {
#PrimaryKey
private int id;
private String title;
private String description;
private String link;
private Terms terms;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Terms getTerms() {
return terms;
}
public void setTerms(Terms terms) {
this.terms = terms;
}
}
public class Terms extends RealmObject {
private String tag;
private RealmList<Category> categories;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public RealmList<Category> getCategories() {
return categories;
}
public void setCategories(RealmList<Category> categories) {
this.categories = categories;
}
}
public class Category extends RealmObject {
#PrimaryKey
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So far so good, now im going to save a list of feeds to realm (make it persistent) and then try to make some query.
public static void test(final Context context,final List<Feed> feedList) {
Realm realm = null;
try {
realm = Realm.getInstance(context);
realm.beginTransaction();
realm.copyToRealmOrUpdate(feedList);
realm.commitTransaction();
RealmResults<Feed> realmResults = realm.where(Feed.class).findAll();// return me all feeds
RealmResults<Feed> realmResults1 = realm.where(Feed.class).equalTo("id", 1).findAll(); // return feed with id 1
RealmResults<Feed> realmResults2 = realm.where(Feed.class).equalTo("terms.tag", "tech").findAll(); // return feeds //with tag = "tech"
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.category.name", "test").findAll(); //exception here
}
} catch (Exception e) {
//Empty
Log.d("Test","",e);
} finally {
if (realm != null)
realm.close();
}
}
}
Everything run well untill the last query and i get this exception:"java.lang.IllegalArgumentException: Invalid query: category does not refer to a class."
So my question is How do i do that kind of query successfully, as i will like realm to return me every feed with terms which has at least 1 category with name = "test"
Thank you very much
Your field is called "categories" and not "category". The third query should be:
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.categories.name", "test").findAll();
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");
In my app I have a list of Trucks that are displayed in a lisview, and every Truck has a list of cases inside it. My question is how do I get a reference to that list of cases inside the truck from the main activity.
public class Truck {
private String name;
public List<Roadcase> cases;
public Truck() {
cases = new ArrayList<Roadcase>();
}
public Truck(String name) {
this.name = name;
this.cases = new ArrayList<Roadcase>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addRoadcase(Roadcase roadcases) {
cases.add(roadcases);
}
public void deleteRoadcase(Roadcase roadcases){
cases.remove(roadcases);
}
public int numberOfRoadcases(){
return cases.size();
}
public List<Roadcase> getList() {
return cases;
}
}
my Truck class.
Thanks in advance.
You should call the method getList from your activity (
public List<Roadcase> getList() {
return cases;
}
)
For example:
Truck truck = new Truck();
List<Roadcase> list = truck.getList();