ListFragment with multiple strings per row - java

I am new to Android development and I am trying to create a ListFragment that can create a ListView from 3 ArrayList objects each containing 30 Strings. Each row would contain a string from each array.
In my reading, I have found that a ListView is essentially created from an ArrayAdapter. The only examples I've seen of this however only show 1 String[] array being used (http://goo.gl/Yrkn0k, http://goo.gl/hqkdl).
How can I pass the three arrays to ArrayAdapter to create this ListView?

ArrayAdapters can work on lists of any sort. If you need to have an ArrayAdapter operate on three separate lists at once, you will need to do two things:
Create a new object class that is the combination of the three lists, eg. an Item class that has three fields: Title, Description, Price. Once you have a suitable object, turn your three lists into a single list of your object.
Then you will need to create a custom adapter class that extends ArrayAdapter, overriding the getView method in order to properly display your items.
Edit
Example:
public class Item {
private String title, desc, price;
public Item(String title, String desc, String price) {
this.title = title;
...
}
*provide standard getters and setters*
}
...
ArrayList<Item> items = new ArrayList<Item>();
for(int i = 0; i < titles.length; i++) {
items.add(new Item(titles[i], descriptions[i], prices[i]);
}
Then new adapter should take the form of
private class CustomAdapter extends ArrayAdapter<Item> {
public CustomAdapter(ArrayList<Item> items) {
super(getActivity(), 0, items);
}
...

The ArrayAdapter<T> class is generic, so you can use it with java Collections. To do what you're trying to do, you could use an ArrayList<ArrayList<String>> or just build model objects that contain your 3 string fields and use ArrayList<YourModel>.
For Example:
public class MyAdapter extends ArrayAdapter<ArrayList<ArrayList<String>>>{
//Constructor
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ArrayList<String> current = getItem(position);
//Do Something
}
}

Related

Accessing and using custom Objects and ArrayList<Object> in different methods

I am currently working on an app that will use many objects as information holders (music things - artist, song, id of album cover img, and another id of 2nd img).
I decided that it would be the best to create "Track" class and use it to make objects and store them in ArrayList.
I created the class, I created the list, but I'm having trouble with accessing it (I want to change the ImageViews and TextViews basing on current Track object).
Here's the Track Class: (Track.java separate)
public class Track {
private String mNameArtist;
private String mNameTrack;
private int mTabResource;
private int mCoverResource;
public Track(String nameArtist, String nameTrack, int tabResourceId, int coverResourceId){
mNameArtist = nameArtist;
mNameTrack = nameTrack;
mTabResource = tabResourceId;
mCoverResource = coverResourceId;
}
public String getArtistName() {
return mNameArtist;
}
public String getTrackName() {
return mNameTrack;
}
public int getTabResourceId() {
return mTabResource;
}
public int getCoverResourceID() {
return mCoverResource;
}}
And here's ArrayList declaration: (PlayActivity.java, inside onCreate method)
ArrayList<Track> Tracks = new ArrayList<Track>();
Tracks.add(new Track("Artist Name", "Track Name", R.drawable.tabtemplate, R.drawable.testcover));
Tracks.add(new Track("Pink Floyd", "Comfortably Numb Solo 1", R.drawable.CNS1Tab, R.drawable.pink_floyd_the_wall));
There are more positions, but you get the idea.
Everything seems to work fine up to this point.
When I want to access it inside another method (even in the same PlayActivity.java) nothing happens or I see errors. I tried many different approaches but every single one fails. For example:
Track.getTabResource(); // can't even use the method.
Tracks.get(3); // does not work as well.
I just can not use objects or that arraylist inside my methods. The "Tracks array" won't even show up in Android Studio when typing. Track does, but I can't access positions from Array.
So to sum up, is there any other way I can use my Objects (ArrayList) items inside other classes and methods?
Thank you for your help in advance.
Create List as instance variable and access through Object of that class.
public class PlayActivity {
List<Track> tracks = new ArrayList<Track>();
public void onCreate() {
tracks.add(new Track("Artist Name", "Track Name", R.drawable.tabtemplate, R.drawable.testcover));
tracks.add(
new Track("Pink Floyd", "Comfortably Numb Solo 1", R.drawable.CNS1Tab, R.drawable.pink_floyd_the_wall));
}
public List<Track> getAllTracks() {
return Collections.unmodifiableList(tracks);
}
public Track getTrack(int index) {
return tracks.get(index);
}
}

Android populate the same custom listview layout with 2 different ArrayLists

I'm new to android and I need help. I couldn't find a link that explains me what I'm going to ask, that's why I'm asking here.
I have a listview with one layout.
My customLayout have some textviews and images, all that I get from 2 jsonArrays inside one json object.
TEXT1 TEXT2 IMAGE1
I want to populate this layout from 2 different Array Lists.
I get this array lists from 2 jsonArrays on my webservice.
My class is a simple one, like this:
public class Example{
private String text;
private String text2;
private String imageLink;
Constructor...
Getter and Setter...
}
I can put the values of ArrayList1 inside the customLayout but not the values of ArrayList2.
Like this:
public class CustomListAdapterStreams extends ArrayAdapter<StreamsData> {
ArrayList<MyClass> ArrayList;
ArrayList<MyClass> ArrayList2;
Context context;
int resource;
public CustomListAdapterStreams(Context context, int resource, ArrayList<MyClass> ArrayList, ArrayList<MyClass> ArrayList2;) {
super(context, resource, ArrayList);
this.ArrayList= ArrayList;
this.context = context;
this.resource = resource;
this.ArrayList2= ArrayList2;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.activity_custom_list_adapter, null);
}
MyClass myclass= ArrayList.get(position);
String getUsername = myclass.getUsername();
String quality = myclass.getQuality();
TextView txtUsername = (TextView) convertView.findViewById(R.id.txtUsername);
txtUsername.setText(getUsername);
and so on
So I need to understand how to put in the same custom layout, in the same views, dinamically, different values. Like when Array List 1 has nothing left, populate the rest of the list with the values of Array List 2.
EDIT:
Answers saying I should put both json arrays in the same arraylist.
By a rookir mistake I thought that I shouldn't mix up two JSONArrays, into the same ArrayList but that is what solved my problems.
Thank you Wizard, I know it was a stupid question. Rookie mistake here.
I would join the two arrays.
for (Example item: arrayList2)
{
    arrayList1.add(item)
}
If you need to show different data for each array item, at the time of joining I would put a property to differentiate, type:
for (Example item: arrayList2)
{
   item.setIsArrayList2(true)
    arrayList1.add(item)
}
And it would apply to the Adapter where you could show the two and so on.
One tip: Use optString instead of getString to not get a JSONException in case it comes null
Seems your two arrayList have same Pojo..
What you can do is Merge two arrayList and keep data in one arrayList before setting an adapter;
Here is how you can do that -
arraList1.addAll(arraList2)

Cannot resolve constructor when using ArrayAdapter

I'm getting myself in a muddle with an ArrayAdapter I'm trying to put together. I've got a constructor, Person, which is used to put together people to go in a list. I'm then putting together an ArrayList of type Person to make a readable list.
I then put together an ArrayAdapter so that the list can be seen in a ListView, but I'm constantly getting "Cannot resolve constructor" with my code.
I've tried countless possible solutions on this site including trying to use getActivity() or this in place of PeopleActivity.this, but I just cannot get my code to compile. I've also tried referencing my constructor class in the ArrayAdapter, but that just gives me an error that it's not an enclosing class.
Person.class (constructor)
import android.text.Editable;
public class Person {
public Person Person;
private Editable personName;
public Person(Editable a) {
personName = a;
}
public void setName(Editable personName){
this.personName = personName;
}
public Editable getName() {
return personName;
}
}
PeopleActivity - populateListView
ArrayList<Person> peoplelistv = new ArrayList<Person>();
...
private void populateListView() {
ListView list = (ListView) findViewById(R.id.peopleListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PeopleActivity.this, android.R.layout.simple_list_item_1, peoplelistv);
list.setAdapter(adapter);
}
Any ideas folks?
Thanks
You are declaring the ArrayAdapter as ArrayAdapter<String>. However, the third parameter that you are passing to the constructor is neither a String[] nor a List<String>. If you are trying to wrap an ArrayList<Person> in an ArrayAdapter, it needs to be an ArrayAdapter<Person>, not ArrayAdapter<String>.

Sugar ORM: How to display values

I use Sugar ORM for Android Development via Android Studio.
But I think I have a quite similar question.
How can I display one/multiple result queries as String or int?
My entity looks like this:
public class PersonsDatabase extends SugarRecord<PersonsSelection>{
String adultText, childText;
int adultCount, childCount;
public PersonsDatabase()
{
}
public PersonsDatabase(String adultText, String childText, int adultCount, int childCount)
{
this.adultText = adultText;
this.childText = childText;
this.adultCount = adultCount;
this.childCount = childCount;
this.save();
}
}
It saves correctly. But when I want to display like this:
public class PersonsSelection extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_persons_selection);
PersonsDatabase personsDatabase = new PersonsDatabase("1 Adult","No Childs",1,0);
List<PersonsDatabase> personsList = PersonsDatabase.findWithQuery(PersonsDatabase.class,"Select adult_Text from PERSONS_DATABASE");
list = (ListView)findViewById(R.id.listView);
list.setAdapter(new ArrayAdapter<PersonsDatabase>(this, android.R.layout.simple_list_item_1, personsList));
}
}
I get something like: PACKAGENAME.PersonsDatabase#4264c038
But I want the values that I wrote in the constructor.
Thanks for help.
From the docs on ArrayAdapter:
However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.
In short: just override the toString() method in your PersonsDatabase class to return the desired textual respresentation.
Alternatively:
To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.
(again from the docs). Plenty of examples out there on how to go about doing that.
Simply override the toString() method.
In that method, return whichever database value you want to retrieve.
In my case, I returned a variable name that I needed (i.e. message) :
#Override
public String toString() {
return message;
}

How to create ListView from an Object with multiple arrays

I am lost again. My object is as follows:
public class LogInfo implements Serializable{
public ArrayList<Point[][]> strokes;
public LinkedList<byte[]> codes;
public int[] times;
...
}
First of all I populate the ListView from an ArrayList of this objects. Then I select an object from the ListView, and I would like to populate new list in new fragment with fields
public ArrayList<Point[][]> strokes;
public LinkedList<byte[]> codes;
However, to create an ArrayAdapter I can't just pass an object to it (as I understand). I need to pass an array. the problem is, that I would like to pass an object previously created and selected, and then populate the list from its fields (not only strokes or codes, but both of them).
How should my ObjectAdapter class look like and what class should it extend? To select an Object from ArrayList of Objects I used:
public class LogInfoObjectAdapter extends ArrayAdapter<LogInfo>
Example (real life):
I have a lot of cars on the parking and I need to make a list of them, so I use ArrayAdapter to populate the list. After I choose one car from the list (car object) it has two arrays in it (for example broken bulbs and broken tires, but both array are same size). Now I want to will the new list with information from selected car. I hope it is clear enough. My problem is that to use ArrayAdapter I have to pass an array in the constructor, but I want to pass the whole object and inside my adapter class process it and add choosen fields to ListView
If you have an object with multiple lists, you don't need to extend ArrayAdapter, you can just extend the BaseAdapter and implement the methods needed (getCount(), getView(), etc).
public class Adapter extends BaseAdapter {
class LogInfo implements Serializable {
public ArrayList<Point[][]> strokes;
public LinkedList<byte[]> codes;
public int[] times;
}
private LogInfo mInfo;
public Adapter(LogInfo info) {
mInfo = info;
}
#Override
public int getCount() {
if (mInfo != null && mInfo.strokes != null) {
return mInfo.strokes.size();
}
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (mInfo != null) {
Point[][] p = mInfo.strokes.get(i);
byte[] b = mInfo.codes.get(i);
//create the view
}
return null;
}
}
1) Array adapter has method getItem() you can use it to get particaular item by index.
2) Make your LogInfo implements IIterable interface
http://developer.android.com/reference/java/lang/Iterable.html
public class LogInfo implements Serializable, Iterable<Point[][]>{
public ArrayList<Point[][]> strokes;
public LinkedList<byte[]> codes;
public int[] times;
public abstract Iterator<Point[][]> iterator (){
//Iterator implementation
}
Now you can use this object directly in other list whitch has following signature
public class LogInfoObjectAdapter extends ArrayAdapter<Point[][]>

Categories

Resources