How do I set my Object to a JList? - java

I'm trying to create a JList that displays items of an object that I created.
The object is an items object and the items class looks like this:
public class items {
private ArrayList<Item> itemlistweapons = new ArrayList<Item>();
private ArrayList<Item> itemlistapparel = new ArrayList<Item>();
private ArrayList<Item> itemlistaid = new ArrayList<Item>();
private ArrayList<Item> itemlistmisc = new ArrayList<Item>();
public void additem(String name, String type){
if("Weapon".equals(type)){
itemlistweapons.add(new Item(name, type));
}
else if ("Apparel".equals(type)){
itemlistapparel.add(new Item(name, type));
}
else if ("Aid".equals(type)){
itemlistaid.add(new Item(name, type));
}
else if ("Misc.".equals(type)){
itemlistmisc.add(new Item(name, type));
}
}
public void dropitem(String name){
for(int i = 0; i < itemlistweapons.size(); i++){
if(itemlistweapons.get(i).getname().equals(name)){
itemlistweapons.remove(i);
}
}
for(int i = 0; i < itemlistapparel.size(); i++){
if(itemlistapparel.get(i).getname().equals(name)){
itemlistapparel.remove(i);
}
}
for(int i = 0; i < itemlistaid.size(); i++){
if(itemlistaid.get(i).getname().equals(name)){
itemlistaid.remove(i);
}
}
for(int i = 0; i < itemlistmisc.size(); i++){
if(itemlistmisc.get(i).getname().equals(name)){
itemlistmisc.remove(i);
}
}
}
public ArrayList<Item> getItemlistweapons() {
return itemlistweapons;
}
public ArrayList<Item> getItemlistapparel() {
return itemlistapparel;
}
public ArrayList<Item> getItemlistaid() {
return itemlistaid;
}
public ArrayList<Item> getItemlistmisc() {
return itemlistmisc;
}
#Override
public String toString(){
String items = "";
if (itemlistweapons.size() > 0){
items += "Weapons\n";
for (Item itemlist1 : itemlistweapons) {
items += itemlist1 + "\n";
}
}
if (itemlistapparel.size() > 0){
items += "Apparel\n";
for (Item itemlist2 : itemlistapparel) {
items += itemlist2 + "\n";
}
}
if (itemlistaid.size() > 0){
items += "Aid\n";
for (Item itemlist3 : itemlistaid) {
items += itemlist3 + "\n";
}
}
if (itemlistmisc.size() > 0){
items += "Misc.\n";
for (Item itemlist4 : itemlistmisc) {
items += itemlist4 + "\n";
}
}
return items;
}
}
So, how would I take the variable itemlistweapons and set it so that it displays on a JList. The itemlistweapons is an array list of the Item time, and the Item class looks like this:
public class Item {
private String name;
private String type;
public Item(String itemname, String itemtype){
name = itemname;
type = itemtype;
}
public String getname(){
return name;
}
#Override
public String toString(){
String iteminfo;
iteminfo = name;
return iteminfo;
}
}
Can someone please tell me how to take an ArrayList<Item> from an items object and put it into a JList?

I think you may have a 3rd class with the GUI, in there you have the Jlist object
then you can do:
JList list = new JList(itemlistweapons .toArray());
and repeat respectively to any arrayList you want to display there.

Related

Save Object into file and read object from file

I'm new to OOP Programming and I'm doing a project.
At some point i've to save information into a file using json notation.
My classes:
FeedGroup
public class FeedGroup implements FeedGroupContract {
private int feedGroupID;
private String feedGroupTitle;
private String feedGroupDescription;
private Feed[] feeds;
private int tamanho;
private final int DEFAULT_SIZE = 10;
/*
private int feedGroupIDGenerator(){
}
*/
public FeedGroup(String feedGroupTitle, String feedGroupDescription) {
this.feeds= new Feed[DEFAULT_SIZE];
this.feedGroupTitle = feedGroupTitle;
this.feedGroupDescription = feedGroupDescription;
}
public FeedGroup(){
this.feeds= new Feed[DEFAULT_SIZE];
}
public FeedGroup(int feedGroupID, String feedGroupTitle, String feedGroupDescription, Feed[] feeds) {
this.feedGroupID = feedGroupID;
this.feedGroupTitle = feedGroupTitle;
this.feedGroupDescription = feedGroupDescription;
this.feeds = new Feed[DEFAULT_SIZE];
}
private void increaseSize() {
this.tamanho++;
}
#Override
public int getID() {
return this.feedGroupID;
}
#Override
public String getTitle() {
return this.feedGroupTitle;
}
#Override
public void setTitle(String string) {
this.feedGroupTitle = feedGroupTitle;
}
#Override
public String getDescription() {
return this.feedGroupDescription;
}
#Override
public void setDescription(String string) {
this.feedGroupDescription = feedGroupDescription;
}
#Override
public boolean addFeed(String feedS) throws GroupException {
Feed newFeed = new Feed();
for (int i = 0; i < this.feeds.length; i++) {
System.out.println("Saving...");
if (this.feeds[i] == null) {
//this.feeds[i] = (Feed) ;
System.out.println("Add object class: " + this.feeds[i]);
System.out.println("Saved successfully.");
increaseSize();
return true;
}
}
return false;
}
#Override
public boolean addFeed(FeedContract fc) throws GroupException {
for (int i = 0; i < this.feeds.length; i++) {
System.out.println("Saving...");
if (this.feeds[i] == null) {
this.feeds[i] = (Feed) fc;
System.out.println("Add object class: " + this.feeds[i]);
System.out.println("Saved successfully.");
increaseSize();
return true;
}
}
return false;
}
#Override
public boolean removeFeed(FeedContract fc) throws ObjectmanagementException {
boolean found = false;
for (int i = 0; i < this.feeds.length; i++) {
if (feeds[i] == fc) {
found = true;
this.feeds[i] = this.feeds[i + 1];
} else {
found = false;
}
}
return found;
}
#Override
public FeedContract getFeed(int i) throws ObjectmanagementException {
return this.feeds[i];
}
#Override
public FeedContract getFeedByID(int i) throws ObjectmanagementException {
Feed found = new Feed();
for (int j = 0; j < this.feeds.length; j++) {
if (feeds[i].getID() == i && this.feeds[i] != null) {
found = this.feeds[i];
}
}
return found;
}
#Override
public int numberFeeds() {
int count = 0;
for (Feed feed : feeds) {
if (feed != null) {
count++;
}
}
return count;
}
#Override
public void getData() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public String toString() {
return "FeedGroup{" + "feedGroupID=" + feedGroupID + ", feedGroupTitle=" + feedGroupTitle + ", feedGroupDescription=" + feedGroupDescription + ", feeds=" + feeds + ", tamanho=" + tamanho + ", DEFAULT_SIZE=" + DEFAULT_SIZE + '}';
}
}
Feed
public class Feed implements FeedContract {
private String feedTitle;
private String feedDescription;
private String feedLanguage;
private Calendar buildDate;
private FeedItem feedItemPos;
private String feedURL;
private String[] categories;
private int categoryID;
private FeedItem[] items;
private int tamanho;
private final int DEFAULT_SIZE = 10;
public Feed(String feedTitle, String feedDescription, String feedLanguage, Calendar buildDate, FeedItem feedItemPos, String feedURL, String[] categories, int categoryID) {
this.feedTitle = feedTitle;
this.feedDescription = feedDescription;
this.feedLanguage = feedLanguage;
this.buildDate = buildDate;
this.feedItemPos = feedItemPos;
this.feedURL = feedURL;
this.categories = categories;
this.categoryID = categoryID;
this.items = new FeedItem[DEFAULT_SIZE];
}
public Feed(String feedGroupURL){
}
public Feed() {
this.items = new FeedItem[DEFAULT_SIZE];
}
#Override
public String getTitle() {
return this.feedTitle;
}
#Override
public void setTitle(String string) {
this.feedTitle = feedTitle;
}
#Override
public String getDescription() {
return this.feedDescription;
}
#Override
public void setDescription(String string) {
this.feedDescription = feedDescription;
}
#Override
public String getLanguage() {
return this.feedLanguage;
}
#Override
public void setLanguage(String string) {
this.feedLanguage = feedLanguage;
}
#Override
public Calendar getBuildDate() {
return this.buildDate;
}
#Override
public void setBuildDate(Calendar clndr) {
this.buildDate = buildDate;
}
private void increaseSize() {
this.tamanho++;
}
#Override
public boolean addItem(String string, String string1, String string2, Calendar clndr, String string3, String string4) {
FeedItem item = new FeedItem(string, string1, string2, clndr, string3, string4);
System.out.println(item.getAuthor());
//System.out.println(items);
if (this.items[0] == null) {
System.out.println("ENTROU");
this.items[0] = item;
} else {
for (int i = 0; i < this.items.length; i++) {
System.out.println("AQUII");
if (items[i] == null) {
items[i] = item;
System.out.println("Add object: " + this.items[i]);
increaseSize();
return true;
}
}
}
return false;
}
#Override
public FeedItemContract getItem(int i) throws ObjectmanagementException {
return this.feedItemPos;
}
#Override
public boolean addCategory(String categoria) {
for (int i = 0; i < this.categories.length; i++) {
if (categories[i] == null) {
categories[i] = categoria;
System.out.println("Add object: " + categoria);
increaseSize();
return true;
}
}
return false;
}
#Override
public String getCategory(int i) throws ObjectmanagementException {
return this.categories[i];
}
#Override
public int numberCategories() {
int count = 0;
for (String category : categories) {
if (category != null) {
count++;
}
}
return count;
}
#Override
public int numberItems() {
int count = 0;
for (FeedItem item : items) {
if (item != null) {
count++;
}
}
return count;
}
#Override
public int getID() {
return this.categoryID;
}
#Override
public String getURL() {
return this.feedURL;
}
#Override
public void setURL(String string) throws FeedException {
this.feedURL = string;
}
}
And App
public class App implements AppContract {
private FeedGroup feedGroupPosition;
private FeedGroup feedGroupID;
private Tag tag;
private FeedItem feedItem;
private FeedGroup[] groups;
private int tamanho;
public App() {
this.groups = new FeedGroup[10];
}
private void increaseSize() {
this.tamanho++;
}
/**
* Método para adicionar um grupo
*
* #param string titulo do grupo
* #param string1 descrição do grupo
* #return true se adicionar, false se não o fizer
*/
#Override
public boolean addGroup(String string, String string1) {
FeedGroup group = new FeedGroup(string, string1);
//System.out.println(group);
//System.out.println(this.groups.length);
if (this.groups.length == 0) {
this.groups[0] = group;
} else {
for (int i = 0; i < this.groups.length; i++) {
System.out.println("Saving...");
if (this.groups[i] == null) {
this.groups[i] = group;
System.out.println("Add object class: " + this.groups[i]);
System.out.println("Saved successfully.");
increaseSize();
//System.out.println(this.groups.length);
return true;
}
}
}
return false;
}
#Override
public boolean removeGroup(int i) throws ObjectmanagementException {
boolean found = false;
for (int j = i; j < this.groups.length; j++) {
if (groups[j] != null) {
found = true;
this.groups[j] = this.groups[j + 1];
} else {
found = false;
}
}
return found;
}
#Override
public FeedGroupContract getGroup(int i) throws ObjectmanagementException {
return this.groups[i];
}
#Override
public FeedGroupContract getGroupByID(int i) throws ObjectmanagementException {
FeedGroup found = new FeedGroup();
for (int j = 0; j < this.groups.length; j++) {
if (groups[i].getID() == i && this.groups[i] != null) {
found = this.groups[i];
}
}
return found;
}
#Override
public int numberGroups() {
int count = 0;
for (FeedGroup group : groups) {
if (group != null) {
count++;
}
}
return count;
}
#Override
public FeedItemContract[] getItemsByTag(String string) {
//for(int i = 0; i<)
return null;
}
#Override
public void saveGroups() throws Exception {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
for (int i = 0; i < this.groups.length; i++) {
FeedGroup fg = (FeedGroup) this.getGroup(i);
JSONArray jsonArrayTemp = new JSONArray();
for (int j = 0; j < fg.numberFeeds(); j++) {
Feed feed = (Feed) fg.getFeed(i);
jsonArrayTemp.add(feed.getURL());
}
jsonObject.put("Group", jsonArrayTemp);
jsonObject.put("Title", groups[i].getTitle());
jsonObject.put("Description", groups[i].getDescription());
// System.out.println("URL: "+ groups[i].getFeed(i).getURL());
jsonObject.put("URL", groups[i].getFeed(i).getURL());
// if(groups[i].getFeed(i).getURL() != null){
// jsonObject.put("URL", groups[i].getFeed(i).getURL());
// } else {
// jsonObject.put("URL", "");
// }
jsonArray.add(jsonObject);
}
FileWriter file = null;
file = new FileWriter("group.json");
file.write(jsonArray.toJSONString());
file.flush();
}
#Override
public void loadGroups() throws Exception {
}
#Override
public FeedGroupContract[] getAllGroups() {
return this.groups;
}
#Override
public FeedItemContract[] getAllSavedItems() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public boolean removeSavedItem(int i) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
The App class is a kind of Container of Objects.
So in resumen, i want to save FeedGroup attributes in a file using json, and then load the file. These methods are implemented in App class (saveGroup() and loadGroup()).
FeedGroup has an instance of Feed class: "private Feed[] feeds" and from Feed class, i just want to get the feedURL to save in the file.
Am i doing it right?
I've tried to do loadResults() method seeing other projects(yes, even without knowing if the saveGroup() method was done correctly) and i got the idea. I've to use set and then valueOf, but i think that without the saveGroup() method done correctly, worth nothing to me.
Can someone help me?
Sorry for the long(?) description.
Thanks.

ListView OnItemClickListener Song

I've created a ListView (myList). By pressing on one of the items on the ListView, the app is supposed to direct the user to the PlaySongActivity page.
I used a searchById function to try to match the ID of the song and the song in my database.( get ID of the song and match the song ID in database to play the same song) However, my teacher told me I am searching by the ID of the ListView, not the song.
So is there any way I can either search by the song title or possibly add an ID to each item in the ListView?
I'm a beginner in coding and have searched for hours and found no solution on the internet :(
private SongCollection mySongCollection = new SongCollection();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(SearchSong.this, PlaySongActivity.class);
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
AppUtil.popMessage(SearchSong.this, "Streaming music: " + selectedSong.getTitle());
intent.putExtra("id", selectedSong.getId());
intent.putExtra("title", selectedSong.getTitle());
intent.putExtra("artiste", selectedSong.getArtiste());
intent.putExtra("fileLink", selectedSong.getFileLink());
intent.putExtra("coverArt", selectedSong.getCoverArt());
startActivity(intent);
}
});
SongCollection.class codes
package com.example.musix;
public class SongCollection {
private Song[] allSongs = new Song[9];
public SongCollection (){
prepareSongs();
}
private void prepareSongs(){
Song theWayYouLookTonight = new Song ("S1001", "The Way You Look Tonight", "Michael Buble", "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=2afe87a64b0042dabf51f37318616965", 4.66, "michael_buble_collection");
Song billiejean = new Song ("S1002", "Billie Jean", "Michael Jackson", "4eb779428d40d579f14d12a9daf98fc66c7d0be4?cid=2afe87a64b0042dabf51f37318616965", 4.9, "billie_jean");
Song somethingJustLikeThis = new Song("S1003", "Something Just Like This","The Chainsmokers","499eefd42a24ec562c464bd7acfad7ed41eb9179?cid=2afe87a64b0042dabf51f37318616965", 4.13, "something_just_like_this");
Song southOfTheBorder = new Song("S1004", "South of the Border","Ed Sheeran","7b43dd0c94b0af0c0401381a683d2f4833180ba3?cid=2afe87a64b0042dabf51f37318616965", 3.41, "south_of_the_border");
Song oldTownRoad = new Song("S1005", "Old Town Road","Lil Nas X","3bc62106123fcafad475271e72e74cd7f519ab83?cid=2afe87a64b0042dabf51f37318616965", 1.9, "old_town_road");
Song noGuidance = new Song("S1006", "No Guidance", "Chris Brown", "7c3bc7b4d1741a001463b570fe29f922d9c42bd6?cid=2afe87a64b0042dabf51f37318616965", 4.34, "no_guidance");
Song closer = new Song("S1007", "Closer", "The Chainsmokers", "8d3df1c64907cb183bff5a127b1525b530992afb?cid=2afe87a64b0042dabf51f37318616965", 4.08, "closer");
Song sideface = new Song("S1008", "側臉", "于果", "c8cc891a7cacb36857ea15c8fcfc4da6e4b1583d?cid=2afe87a64b0042dabf51f37318616965", 3.63, "sideface");
Song kebukeyi = new Song("S1009", "可不可以", "张紫豪", "2d790215acf7c4e6c5e093255b94a936064f75ed?cid=2afe87a64b0042dabf51f37318616965", 4.01, "kebukeyi");
allSongs[0]= theWayYouLookTonight;
allSongs[1]= billiejean;
allSongs[2]= somethingJustLikeThis;
allSongs[3]= southOfTheBorder;
allSongs[4]= oldTownRoad;
allSongs[5]= noGuidance;
allSongs[6]= closer;
allSongs[7]= sideface;
allSongs[8]= kebukeyi;
}
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
//create a method to retrieve the next song
public Song getNextSong(String currentSongId){
Song nextSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x < allSongs.length -1)){
nextSong = allSongs[x+1];
break;
}
}
return nextSong;
}
//create a method to retrieve the previous song
public Song getPrevSong(String currentSongId){
Song PrevSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x > 0)){
PrevSong = allSongs[x-1];
break;
}
}
return PrevSong;
}
//create a method to get random song
public Song getRandomSong(){
Song randomSong = null;
int max = 2;
int min = 0;
int randomNum = (int)(Math.random()*4);
randomSong = allSongs[randomNum];
return randomSong;
}
}
Song.class codes
package com.example.musix;
public class Song {
//private attributes are hidden from other classes/files
private String id;
private String title;
private String artiste;
private String fileLink;
private double songLength;
private String coverArt;
public Song(String _id, String _title, String _artiste, String _fileLink, double _songLength, String _coverArt){
this.id = _id;
this.title = _title;
this.artiste = _artiste;
this.fileLink = _fileLink;
this.songLength = _songLength;
this.coverArt = _coverArt;
}
//encapsulation
//SET methods for setting/changing of the values of the attributes
public void setId(String id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setArtiste(String artiste) {
this.artiste = artiste;
}
public void setFileLink(String fileLink) {
this.fileLink = fileLink;
}
public void setSongLength(double songLength) {
this.songLength = songLength;
}
public void setCoverArt(String coverArt) {
this.coverArt = coverArt;
}
//GET methods allows us to retrieve values of the attributes
public String getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
public String getArtiste() {
return this.artiste;
}
public String getFileLink() {
return this.fileLink;
}
public double getSongLength() {
return this.songLength;
}
public String getCoverArt() {
return this.coverArt;
}
}
codes for getResourceId
public final class AppUtil
{
public static void popMessage(Context context, String message)
{
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static String getResourceId(Context context, View view)
{
String id = context.getResources().getResourceEntryName(view.getId());
return id;
}
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
resourceId is going to be the id of the element of the list view (eg. first element id = 0, 2nd id = 1 and so on).
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
Should be:
public Song searchById (String id){
//we are returning the song selected by the index of its Arrays
Song selectedSong = allSongs[Integer.parseInt(id)];
return selectedSong;
}
Why?:
Your returning the actual songid, but in
Song selectedSong = mySongCollection.searchById(resourceId); <-- resourceId is already the Id stored in the database and not the index of mySongCollection.
intent.putExtra("id", selectedSong.getId());
you are using already the actuals song id. This doesen't make sense as you can already identify the actual song.
So either apply these changes or change this line:
intent.putExtra("id", resourceId);

How to addsong in User class using Playlist arrays?

addSong(title:String,filePath: String, artist:String):int
adds the song to the play list and returns 0 if added and –1 if the song can not be added because the list is full.
*** I keep on getting errors like method addsong(String, String, String) is not applicable for agrument int and also the getArtist method is not defined. How do I go upon it? Any suggestions or solutions to make it work?
PLaylist Class:
public class Playlist {
//Instance Variables
private int numOfSongs;
private Songs[] songList;
// Constructors
public Playlist(int maxNumofSongs){
this.numOfSongs = 0;
this.songList = new Songs[maxNumofSongs];
}
//Getters
public Songs[] getSongList(){
return songList;
}
//Methods
public void addSong(String title, String filePath, String artist){
Songs p = new Songs(title, filePath, artist);
addSong(p);
}
public void addSong(Songs p){
songList[this.numOfSongs] = p;
this.numOfSongs++;
}
public Songs getSong(int pos){
if (pos <= this.songList.length)
return this.songList[pos];
else
return null;
}
public int getSongByTitle(String title){
int pos = -1;
for (int i = 0; i < this.numOfSongs; i++)
if (this.songList[i].getTitle() == title)
pos = i;
return pos;
}
public String toString(){
String playlistDesc = "";
playlistDesc += "Number of Songs added in Playlist: "+ numOfSongs;
return playlistDesc;
}
}
User CLass:
public class User {
//Instance Variables
private String name;
private String email;
private Playlist favoriteSongs;
Songs[] songs = this.favoriteSongs.getSongList();
//Constructors
public User(String name, String email, Playlist favoriteSongs){
this.name = name;
this.email = email;
this.favoriteSongs = favoriteSongs;
}
public User(String name, String email){
this.name = name;
this.email = email;
}
//Setters
public void setPlayList(Playlist list){
this.favoriteSongs = list;
}
//Get song title by inputting the position in the playlist array
public String getSongTitle(int pos){
if (pos < songs.length){
Songs s = songs[pos];
//you can then get the title of the song using
s.getTitle();
}
return songs[pos].getTitle();
}
//Add new song to the playlist
public int addSong(String title, String filePath, String artist){
for(int i = 0; i < songs.length; i++) {
if (addSong(i) == songs[i].getTitle().getArtist()){ // or what ever you want to compare
return 0;
}
// if you do not found any thing
return -1;
}
}
//Counts how many songs with the same artist
public int artistSongCount(String artist){
int count = 0;
for (int i=0; i < songs.length; i++)
if (this.songs[i].getArtist() == artist)
count++;
return count;
}
//Print out details of user
public String toString(){
String userOutput = "";
userOutput += "Name: "+ name;
userOutput += "Email: "+ email;
return userOutput;
}
}

Android ArrayList, how to get onClick of ListView

I was testing the sample code from foursquare-api
What I would like to know, How can I get the onClick item for the list view ?
so after the get the list of venue, If the user click on the list item, I want to send the avenue name to another fragment to handle it.
thanks
Java Coding
ArrayList<FoursquareVenue> venuesList;
ArrayAdapter<String> myAdapter;
private static ArrayList<FoursquareVenue> parseFoursquare(final String response) {
ArrayList<FoursquareVenue> temp = new ArrayList<FoursquareVenue>();
try {
// make an jsonObject in order to parse the response
JSONObject jsonObject = new JSONObject(response);
// make an jsonObject in order to parse the response
if (jsonObject.has("response")) {
if (jsonObject.getJSONObject("response").has("venues")) {
JSONArray jsonArray = jsonObject.getJSONObject("response").getJSONArray("venues");
for (int i = 0; i < jsonArray.length(); i++) {
FoursquareVenue poi = new FoursquareVenue();
if (jsonArray.getJSONObject(i).has("name")) {
poi.setName(jsonArray.getJSONObject(i).getString("name"));
if (jsonArray.getJSONObject(i).has("location")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("address")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("city")) {
poi.setCity(jsonArray.getJSONObject(i).getJSONObject("location").getString("city"));
}
if (jsonArray.getJSONObject(i).has("categories")) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").length() > 0) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).has("icon")) {
poi.setCategory(jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).getString("name"));
}
}
}
temp.add(poi);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<FoursquareVenue>();
}
return temp;
}
#Override
protected void onPostExecute(String result) {
if (temp == null) {
// we have an error to the call
// we can also stop the progress bar
} else {
// all things went right
// parseFoursquare venues search result
venuesList = (ArrayList<FoursquareVenue>) parseFoursquare(temp);
List<String> listTitle = new ArrayList<String>();
for (int i = 0; i < venuesList.size(); i++) {
// make a list of the venus that are loaded in the list.
// show the name, the category and the city
listTitle.add(i, venuesList.get(i).getName() + ", " + venuesList.get(i).getCategory() + "" + venuesList.get(i).getCity());
}
// set the results to the list
// and show them in the xml
myAdapter = new ArrayAdapter<String>(LocationActivity.this, R.layout.row_layout, R.id.listText, listTitle);
setListAdapter(myAdapter);
}
}
Thanks
I have tried this :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(getApplicationContext(), "position => " + position +
" - ListView =>" + l +
" - View => " + v +
" - id => " + id
, Toast.LENGTH_LONG).show();
}
I can get the position of the listView Item, But I can not the the data of the list view.
I am also using this:
public class FoursquareVenue {
private String name;
private String city;
private String category;
public FoursquareVenue() {
this.name = "";
this.city = "";
this.setCategory("");
}
public String getCity() {
if (city.length() > 0) {
return city;
}
return city;
}
public void setCity(String city) {
if (city != null) {
this.city = city.replaceAll("\\(", "").replaceAll("\\)", "");
;
}
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
init your listview from main.xml
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(this);
and add
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
}
Just override
onListItemClick(ListView l, View v, int position, long id)
which is called when an item in the list is selected. Since, you are invoking setListAdapter() I'm assuming you've extended either ListActivity or ListFragment.
To retrieve the ListView data use ListView#getItemAtPosition() method.
Now, here's where you would realise that using an ArrayAdapter<FoursquareVenue> instead of ArrayAdapter<String> would have been better because with the String version, all you would be able to retrieve with getItemAtPosition(), is exactly the same string that you passed at
listTitle.add(i, venuesList.get(i).getName() + ", " +
venuesList.get(i).getCategory() + "" + venuesList.get(i).getCity());
which is clearly not very flexible. You should pass your venuesList directly to the adapter as
myAdapter = new ArrayAdapter<FoursquareVenue>(
LocationActivity.this, R.layout.row_layout, R.id.listText, venuesList);
and then override FoursquareVenue#toString()
public String toString() {
return new StringBuilder(name).append(", ")
.append(category).append(", ").append(city).toString();
}

How to pass selected parents "child elements" from one custom adapter to another new custom adapter?

I am having a custom adapter with checkbox and child elements in an expandable custom adapter, and when the parent items - for my case Orders are selected /checked the Orders are passed to a new custom adapter without checkbox . I am able pass the parent ie Orders but i am not able to pass the Child elements ie Items which are the childreen of ORDERS. So i need to pass the child elements of the orders that are selected to the new adapter view.
My code :
try {
System.out.println("READ/PARSING JSON");
serverStatus = jobj.getString("SERVER_STATUS");
System.out.println("serverStatusObj: "+serverStatus);
JSONArray serverResponseArray2=jobj.getJSONArray("SERVER_RESPONSE");
for (int m = 0; m < serverResponseArray2.length(); m++) {
String SERVER_RESPONSE = serverResponseArray2.getString(m);
JSONObject Open_Orders_obj = new JSONObject(SERVER_RESPONSE);
mMAX_ORDERS_TOBEPICKED = Open_Orders_obj.getInt("MAX_ORDERS_TOBEPICKED");
JSONArray ja = Open_Orders_obj.getJSONArray("ORDER_ITEM_DETAILS");
order_Item_Values.clear();
mOpenOrders = new ArrayList<OpenOrders>(ja.length());
for(int i=0; i<ja.length(); i++){
String ORDER_ITEM_DETAILS = ja.getString(i);
jobj1 = new JSONObject(ORDER_ITEM_DETAILS);
String ORDERNAME = jobj1.getString("ORDERNAME");
String ORDERID = jobj1.getString("ORDERID");
final OpenOrders parent = new OpenOrders();
parent.setOrderName(ORDERNAME+ " "+ i);
parent.setOrderID(ORDERID);
parent.setChecked((i % 2) == 0);
OpenOrders openOrderObj= new OpenOrders(ORDERID,ORDERNAME);
JSONArray Order_Items = jobj1.getJSONArray("ITEMS");
itemList =new ArrayList<String>();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<Order_Items.length(); k++){
String ITEMS = Order_Items.getString(k);
System.out.println(ITEMS);
ItemObj = new JSONObject(ITEMS);
String ITEMNUMBER = ItemObj.getString("ITEMNUMBER");
String ITEMNAME = ItemObj.getString("ITEMNAME");
itemList.add(ITEMNAME);//This adds item name's to the ArrayList named 'itemList'
openOrderObj.setItemID(ITEMNUMBER);
openOrderObj.setItemName(ITEMNAME);
System.out.println("item name"+ITEMNAME);
final Child child = new Child();
child.setName(ITEMNAME + i + "/" + k);
parent.getChildren().add(child);
}
mOpenOrders.add(parent);
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //***End code to read json content from text file saved in device
enter code here
My open Order class:
import java.io.Serializable;
import java.util.ArrayList;
import com.kits.ddf_order_model.Child;
public class OpenOrders implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String orderID;
private String orderName;
private boolean selected;
private boolean checked;
private ArrayList<Child> children;
private String itemID;
private String itemName;
public OpenOrders(String orderID, String orderName) {
super();
this.orderID = orderID;
this.orderName = orderName;
}
public OpenOrders() {
// TODO Auto-generated constructor stub
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
#Override
public String toString() {
return this.orderName;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public ArrayList<Child> getChildren()
{
return children;
}
public void setChildren(ArrayList<Child> children)
{
this.children = children;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
my Child class:
public class Child
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
So When the button is clicked what i do is :
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mAdapter != null) {
int isSelectedOrderNumber=0;//This Variable will check with the parameter passed from server
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
// mOpenOrdersSelected.add(new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName()));
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
Iterator<Child> i = mOpenOrderItems.iterator();
mOpenOrdersSelected.add(parent);
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
//Below code is to Call again the adapter and Displays the Order's which are checked/selected.
expListView = (ExpandableListView) findViewById(R.id.expandable_order_item_list);
ExpandableOrderSelectedListAdapter mOrderSelectedAdapter = new ExpandableOrderSelectedListAdapter(SelectLocationActivity.this,mOpenOrdersSelected);
expListView.setAdapter(mOrderSelectedAdapter);
expListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//nothing to do , as Null Pointer exception Occurred ,to avoid that I just used this "setOnItemClickListener"
}
});
button.setVisibility(View.GONE);//Hide the Initial Button in the view
fullfilment_btn.setVisibility(View.VISIBLE);//Displays the confirm Button
fullfilment_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
});
So here in this part of the code i get error while iterating the child elements .
Any help will be greatfull
I Solved this issue by a for loop, which will add the child to the new "mOpenOrderSelected" variable:
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<mOpenOrderItems.size(); k++){
final Child child = (Child) mOpenOrderItems.get(k);
Log.d("ChildItemsname", "ChildItemsname:"+child.getName());
parent.getChildren().add(child);
}
mOpenOrdersSelected.add(parent);
}
So the new button click code will be like this:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mAdapter != null) {
int isSelectedOrderNumber=0;//This Variable will check with the parameter passed from server
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<mOpenOrderItems.size(); k++){
final Child child = (Child) mOpenOrderItems.get(k);
Log.d("ChildItemsname", "ChildItemsname:"+child.getName());
parent.getChildren().add(child);
}
mOpenOrdersSelected.add(parent);
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
//Below code is to Call again the adapter and Displays the Order's which are checked/selected.
expListView = (ExpandableListView) findViewById(R.id.expandable_order_item_list);
ExpandableOrderSelectedListAdapter mOrderSelectedAdapter = new ExpandableOrderSelectedListAdapter(SelectLocationActivity.this,mOpenOrdersSelected);
expListView.setAdapter(mOrderSelectedAdapter);
expListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//nothing to do , as Null Pointer exception Occurred ,to avoid that I just used this "setOnItemClickListener"
}
});
button.setVisibility(View.GONE);//Hide the Initial Button in the view
fullfilment_btn.setVisibility(View.VISIBLE);//Displays the confirm Button
fullfilment_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
});

Categories