Adding items to Array List with specified objects - android

I am working in a translator kind of app and i need some help.
I have a class with getters and setters for my Array List objects. Each object has a phrase, a meaning, and usage.
so i have this to create my list:
ArrayList<PhraseCollection> IdiomsList = new ArrayList<PhraseCollection>();
now how do i add these objects to the list, each object containing the phrase, its meaning, and a use in a sentence?
For Example: The Layout would be something like this
Phrase
Kick the bucket
Meaning
When someone dies
Usage
My grandfather kicked the bucket
Thanks a lot

this is what i came up with that worked for me
private void loadIdioms() {
//creating new items in the list
Idiom i1 = new Idiom();
i1.setPhrase("Kick the bucket");
i1.setMeaning("When someone dies");
i1.setUsage("My old dog kicked the bucket");
idiomsList.add(i1);
}

ArrayList has a method call add() or add(ELEMENT,INDEX);
In order to add your objects you must first create them
PhraseCollection collection=new PhraseCollection();
then create the ArrayList by
ArrayList<PhraseCollection> list=new ArrayList<PhraseCollection>();
add them by :
list.add(collection);
Last if you want to render that in your ListView item, you must override the toString() in your PhraseCollection.

I suppose you would use the add(E) method (http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(E)).
Here is an example using your example provided.
public class Phrase {
public final String phrase, meaning, usage;
//TODO: implement getters?
public Phrase(String phrase, meaning, usage) {
this.phrase = phrase;
this.meaning = meaning;
this.usage = usage;
}
}
and use it like this:
// create the list
ArrayList<Phrase> idiomsList = new ArrayList<Phrase>();
// create the phrase to add
Phrase kick = new Phrase("kick the bucket", "When someone dies", "My grandfather kicked the bucket");
// add the phrase to the list
idiomsList.add(kick);

Related

Populate a list in Kotlin with a for loop

It's been a while that I just started to learn how to develop in Kotlin.
There is this thing that I am working on, I am trying to parse a list into another type of list. Basically they are the same thing but with different names. But when I try to populate the new list with the data that I get from the list given as parameter in the function the list only gets populated with the first object.
Here is my function:
fun convertRoomClass(course: List<Course>) : List<Courses> {
lateinit var list : List<Courses>
course.forEach {
val id = it.pathID
val name = it.pathName
val desc = it.pathDescription
val crs : Courses = Courses(id, name!!, desc!!)
list = listOf(crs)
}
return list
}
The error in your code is that you are making a list in every iteration of the loop. You should make the list first and then add every item from the loop to it!
fun convertRoomClass(courses: List<Course>) : List<AnotherCourseClass> {
val newList = mutableListOf<AnotherCourseClass>()
courses.forEach {
newList += AnotherCourseClass(it.pathID, it.pathName, it.pathDescription)
}
return newList
}
A better solution is to use the map function
fun convertRoomClass(courses: List<Course>) = courses.map {
AnotherCourseClass(it.pathID, it. pathName, it.pathDescription)
}
You might be looking for Kotlin Map
Example:
course.map { Courses(it.pathID, it.pathName,it.pathDescription) }
You're getting the list with only on object, cause the function listOf(crs) returns a list of all objects that are passed as a parameters. Saying the same thing in Java you're doing something like this:
for (course: Courses) {
Course course = new Course(...);
List<Course> list = new ArrayList<>();
list.add(course);
return list;
}
As you can see the it created new list with a single object per iteration.
What you're trying to achieve, can be done with operator map{...} which simply transforms every object in the initial list using code passed inside map and returns list of transformed objects
course.map{ Courses(...) }
Also, I've noticed that you're using the !! operator when creating a Courses object. Probably because the Course can have nullable name, while Courses can't. I'm considering this as a bad practice, cause in this case you're saying
Please throw an Exception if the name is null.
I think that a much better approach is to provide an alternative, like:
val name = course.name ?: "default", saying
Please use name or "default" if the name is null.
or skip objects without name, or any other approach that suits your situation.
You could use MutableList instead of List. That enable you to append new element at the end of your list instead of replace the entire list by doing : list = listOf(crs)
So replace the type of your var lateinit var list : List<Courses> by lateinit var list : MutableList<Courses> then replace list = listOf(crs) by list.add(crs)
Hope it helps and have fun :)

Android Realm: Retrieve collection ids from realm Object

I have saved my User to the realm. When I query the user I get this object:
User{id=0, hairColor=Red, favoriteSongs=FavoriteSong#[16,17]}
When I want the list of favorite songs, realm makes it easy to get a list back:
mUser.getFavoriteSongs();
But I'd like to get an array of the user's favoriteSong ids. This will make it easy to pass in a bundle as an int[].
Is this possible in Realm?
I would propose you two options:
Create a helper responsible of iterate the list of Songs and return a list of ids.
class SongHelper {
public static List<Integer> getSongIds(List<Song> songs) {
List<Integer> songIds = new ArrayList<>();
for( Song song : songs )
songIds.add( song.getId() );
return songIds;
}
}
Override the getFavoriteSongs method and make it return List<Integer> instead of List<Song> or create an additional method for this in the User.
Option 1 is more elegant. You should always keep your model classes as clean as possible. In other words, just declare attributes, getter and setters without business logic.

Android and parse

i made a listview with all the posts in the list.
what i want is when i click the child in the list i want another activity to be opened showing that specific post and the related comments
the question is how to know which item is clicked and how to show that particular post ParseObject in next activity
as they do in messaging app in which you click the message from the listview and subsequent messages are shown in the next activity
i might be very thankful to you if you solve this for me!!
Please Try this code:
Please implement your object class with Serializable
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
try
{
Log.v("position",position); // hear is your list item position
MyClass obj = new MyClass(); // Class must be implements with Serializable
Intent showintent = new Intent(context,<activity class to open>);
showcontactintent.putExtra("obj",obj);
startActivity(showintent);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
Use: Relational Data
Objects can have relationships with other objects. To model this behavior, any ParseObject can be used as a value in other ParseObjects. Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency.
For example, each Comment in a blogging app might correspond to one Post. To create a new Post with a single Comment, you could write:
// Create the post
ParseObject myPost = new ParseObject("Post");
myPost.put("title", "I'm Hungry");
myPost.put("content", "Where should we go for lunch?");
// Create the comment
ParseObject myComment = new ParseObject("Comment");
myComment.put("content", "Let's do Sushirrito.");
// Add a relation between the Post and Comment
myComment.put("parent", myPost);
// This will save both myPost and myComment
myComment.saveInBackground();
You can also link objects using just their objectIds like so:
// Add a relation between the Post with objectId "1zEcyElZ80" and the comment
myComment.put("parent", ParseObject.createWithoutData("Post", "1zEcyElZ80"));
By default, when fetching an object, related ParseObjects are not fetched. These objects' values cannot be retrieved until they have been fetched like so:
fetchedComment.getParseObject("post")
.fetchIfNeededInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject post, ParseException e) {
String title = post.getString("title");
// Do something with your new title variable
}
});
You can also model a many-to-many relation using the ParseRelation object. This works similar to List, except that you don't need to download all the ParseObjects in a relation at once. This allows ParseRelation to scale to many more objects than the List approach. For example, a User may have many Posts that they might like. In this case, you can store the set of Posts that a User likes using getRelation. In order to add a post to the list, the code would look something like:
ParseUser user = ParseUser.getCurrentUser();
ParseRelation<ParseObject> relation = user.getRelation("likes");
relation.add(post);
user.saveInBackground();
You can remove a post from the ParseRelation with something like:
relation.remove(post);
For more read: https://parse.com/docs/android/guide#objects-relational-data
^why did I copy all the words here instead of just providing the link? Because parse links are broken sometimes and doesn't direct you to the section you need (instead it just sends you to https://parse.com/docs/android/guide and because the doc is so large, you won't be able to find it.

How do I store multiple values in an array in Android?

For this example I have an array:
String[] books = new String[x];
I would like to store the id and title in each location:
books[0]=>id:0, title:"book title1"
books[0]=>id:1, title:"book title2"
books[0]=>id:2, title:"book title3"
books[0]=>id:3, title:"book title4"
I want to store the id since it may change. I'm getting the id and title from a database. Getting the info isn't the issue. I want to store it this way so in my other functions this returns to I can use something like:
btn.setText(regions[i].title)
Any suggestion on how to handle this would be great.
Do one thing, first create a bean class like BookBean.
Under this declare two variables ID and Title. and declare getters and setters (If u are using eclipse u can easily do this by (Source -> generate getters and setters.. option)
and then declare a ArrayList to store BookBean vale as of follow.
ArrayList<BookBean> bookArrayList=new ArrayList<BookBean>();
for(int i=0;i<=urSize;i++)
{
// create a object for BookBean
BookBean book =new BookBean();
book.setID("what ever");
book.setTitle("what ever");
bookArrayList.ass(book)
}
It is better to use Arraylist with custom class.
see this
class Book
{
String id,title;
/* Cunstructor to store data */
public Book(String id,String title)
{
this.id = id;
this.title = title;
}
}
//declare arraylist
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add("1","book1");
bookList.add("2","book2");
bookList.add("3","book3");
bookList.add("4","book4");
btn.setText(bookList.get(i).title)
I think you have several options
Use a HashMap where you can use your id as key and value title
Define a class and keep id and title as attributes , define get and set methods.
Keep the objects of the class in a ArrayList

Android Can't save to an array

I have global array. When i want to save something in some method and after that show it from that array it has error NullPointerException. Array is Object type. Code is like this
class Something {
public CoordinatesObject[] coordinates;
Something() {
coordinates = new CoordinatesObject[4];
}
public String myMethod() {
if (coordinates.length==0){
coordinates[0] = new CoordinatesObject(0,0);
}
}
return Integer.toString(coordinates[0].getX());
}
What's wrong?
Sorry I have updated the code. I've created a new array in constructor
You created an array with this line:
coordinates = new CoordinatesObject[4];
and then you're trying to create CoordinatesObject like that:
if (coordinates.length==0){
coordinates[0] = new CoordinatesObject(0,0);
}
but coordinates.length is going to be equal to 4 which means an object of CoordinatesObject class won't be created.
You need to actually allocate space for the array, right now you just have a reference to nothing.
Also note that arrays are fixed-length, you may want to consider using a collection (like a list) instead, depending on your needs.
You have to create the Array with new as well.
Currently, you have a NULL reference. As the previous poster points out, you need to define and create some space for your array.

Categories

Resources