Hi i have an arraylist that i want to access from another class, i'm new to android please try to explain in a simple way
//Adding item to ArrayList
Cursor cursor2=shoppingListDB.rawQuery("SELECT * FROM " + selected_spinner + ";", null);
if (cursor2.moveToFirst()){
list.clear();
do{
String itemName = cursor2.getString(cursor2.getColumnIndex("ITEM_NAME"));
String shopList = cursor2.getString(cursor2.getColumnIndex("SHOP_LIST"));
String numbItems = cursor2.getString(cursor2.getColumnIndex("NUMB_ITEMS"));
//Adding Items to the arraylist
list.add(numbItems + " x"+ " " +itemName + " " + "#"+shopList);
}
while (cursor2.moveToNext());
//====CODE FOR SHOWING DATA AS A SIMPLE LIST ITEM=========================================
view_list = (ListView)findViewById(R.id.listItems);
ArrayAdapter <String> adapter=new ArrayAdapter<String>(CreateList.this,android.R.layout.simple_list_item_1,list);
view_list.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "DATA NOT AVAILABLE", 3000).show();
}
cursor2.close();
I think you should use basic OOP concept for this.
in your class you can declare the list as class instance variable and use getter method to get the list in other class.
public class abcd {
private List<String> list;
public List<String> getList() {
return list;
}
//your code which uses list
}
Hope this will help you.
Related
I made an app where i show all songs, albums, artists, genres and playlist.
I was reviewing my code for a bit because i got an error because i was checking if a String passed as a parameter was the same as a String inside my Album class getGenre() method which returns a String.
i resolved this error by changing
public ArrayList<Song> getSongsByGenre(String genreName) {
ArrayList<Song> songsByGenre = new ArrayList<>();
for (Song song : songs) {
String currentSongGenre = song.getGenre();
if (currentSongGenre.equals(genreName))
songByGenre.add(song);
}
}
To
public ArrayList<Song> getSongsByGenre(String genreName) {
ArrayList<Song> songsByGenre = new ArrayList<>();
for (Song song : songs) {
String currentSongGenre = song.getGenre();
if (Objects.equals(currentSongGenre, genreName))
songsByGenre.add(song);
}
}
What is the difference between Objects.equals and just currentSongGenre.equals(genreName); ?
Also what i don't understand is when i logged the values for 'currentSongGenre' , 'genreName' and the if statement in logcat.
Log.d(TAG, "value currentSongGenre: " + currentSongGenre);
Log.d(TAG, "value genreName: " + genreName);
Log.d(TAG, "value ifstat: " + currentSongGenre + " Equals " + genreName);
Logcat debug
SongList: value currentSongGenre: null
SongList: value genreName: Hip-Hop/Rap
SongList: value ifstat: null Equals Hip-Hop/Rap
So how does it work when both String Values are clearly not the same?
p.s this is how i set a genre, let me know if you need a more code because it's alot of code.
I use 2 Hashmaps:
songIdToGenreIdMap & genreIdToGenreNameMap, in the first one i add all song Id's and genre Id's found on the device and the second one i use to get the genre names.
String currentGenreID = songIdToGenreIdMap.get(Long.toString(song.getId()));
String currentGenreName = genreIdToGenreNameMap.get(currentGenreID);
song.setGenre(currentGenreName);
In your first block you are not comparing to "genreName", but to "genre".
if (currentSongGenre.equals(genre))
Should be
if (currentSongGenre.equals(genreName))
I am trying to display a retrieved data from MySQL database with the help of Volley, and populate it into a ListView.
So far as I tried every method I am unable to do it.
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
ArrayList<HashMap<String, String>> authorList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject obj = (JSONObject) response.get(i);
String username = obj.getString("username");
String email = obj.getString("email");
String password = obj.getString("password");
usernameAll += "UserName: " + username + "\n\n";
emailAll += "Email: " + email + "\n\n";
passwordAll += "Password: " + password + "\n\n";
}
As I have retrieved 'username', 'email', and 'password' I can successfully show it in TextView by myTextView.setText(usernameAll + " " + ..);. But for now I just want to print/populate 'username' in Simple ListView
HashMap<String, String> myData = new HashMap<>();
myData.put("justKey", usernameAll);
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, myData);
listView.setAdapter(adapter1);
When I take some Array and call that array it works but why myData isn't working. Can you please help me understanding the actual problem.
My next step will be to use the Custom ListView but now I am eager "how actually stuff works"
I will really appreciate if you correct my approach of solving this problem.
Thank You.
PS: I am getting this error from Android Studio 2.1.2:
Cannot resolve constructor 'ArrayAdapter(android.content.Context, int,
int, java.lang.String)'
u can't pass hashmap to the array adapter
https://developer.android.com/reference/android/widget/ArrayAdapter.html
convert it to the list as mentioned in the documentation also
//Code Getting Collection of values from HashMap
Collection<String> values = myData.values();
//Creating an ArrayList of values
ArrayList<String> listOfValues = new ArrayList<String>(values);
For details check out the link below
http://javaconceptoftheday.com/how-to-convert-hashmap-to-arraylist-in-java/
I am trying to add users to a model.
I want to add all the users that are in MembersArray but not in membersAvailableArray.
membersAvailableArray = all members in the class.
MembersArray = all members
Im trying to get all members that are in MembersArray but not membersAvailableArray
DefaultListModel<String> model2 = new DefaultListModel<>();
for(Member allMems: MembersArray)
{
for(Member mems: membersAvailableArray)
{
if(!allMems.getUsername().equals(mems.getUsername()))
{
model2.addElement(allMems.getFirstName() + " " + allMems.getLastName());
}
}
}
availableMembersJList.setModel(model2);
You do not need any looping here, just some good old "All" operations:
ArrayList<Member> membersToAdd = members.clone();
membersToAdd.removeAll(availableMembers);
membersToAdd now has all the members you need to add.
If you happen to have Java 8, there is an even simpler way to do this:
members.stream()
.filter(p->!availableMembers.contains(p))
.forEach(p->model2.addElement(p));
try this tricky way, add all to an ArrayList and remove those you do not want
ArrayList<Member> tmp = new ArrayList<Member>();
tmp.addAll(MembersArray);
tmp.removeAll(membersAvailableArray);
for(Member allMems: tmp){
model2.addElement(allMems.getFirstName() + " " + allMems.getLastName());
}
I'm trying to retrieve a column (a database column where names are saved) and puting them to a listview. I have a class called Data with "getters" and "setters".
The following code is placed in a DBHandler class which extends SQLiteOpenHelper. This code is called from the MainActivity.java where the listview is meant to be updated with an onClickButton event.
public String[] getNames (int a, int b) {
String[] names = new String[] {};
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " WHERE " + KEY_ONE + " = ? AND " + KEY_TWO + " = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(a), String.valueOf(b)});
if (cursor.moveToFirst()) {
int i = 0;
do {
Data myData = new Data();
names [i] = cursor.getString(1); //Names in cursor
++i;
} while (cursor.moveToNext());
}
return names;
}
In the MainActivity.java I call the following code before updating and notifying the update of the listview adapter:
values = db.getNames (1, 1);
I don't know why but this isn't working, it throws many errors with String lengths and crashes the app when I click the button that is suposed to enter the onClickButton.
Thanks
Follow the laalto answer and at last convert your ArrayList to Array like below:
String[] arrRecords = names.toArray(new String[names.size()]);
String[] names = new String[] {};
...
names [i] = cursor.getString(1); //Names in cursor
You're assigning to an empty array which causes ArrayIndexOutOfBoundsException.
Consider using a list such as ArrayList where you can append your values, e.g.
List<String> names = new ArrayList<String>();
...
names.add(cursor.getString(1));
If you really need to return a String[], you can convert the list with toArray():
String[] arr = new String[names.size()];
names.toArray(arr);
return arr;
Also, when posting questions that involve exceptions, always include the exception stacktrace from logcat in the question itself.
Why use like this
String[] names = new String[] {}; //no size
names [i] = cursor.getString(1); //it can work?
Use ArrayList<String>
List<String> names = new ArrayList<String>(); //declare
names.add(<column-val>); //add column value to list
public List<UserDataHelper> getData() {
List<UserDataHelper> list = new ArrayList<UserDataHelper>();
String selectQuery = "SELECT * FROM " + TABLE;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
UserDataHelper quest = new UserDataHelper();
quest.setID(cursor.getInt(0));
quest.setName(cursor.getString(1));
quest.setSent(cursor.getInt(2));
quest.setRecieved(cursor.getInt(3));
quest.setTotal(cursor.getInt(4));
quest.setTimeSpent(cursor.getString(5));
list.add(quest);
} while (cursor.moveToNext());
}
return list;
}
This is for a listView but I want to fetch data individually and display it in textView. How can I achieve that? There are a lot of tutorials for listviews but not for textViews so can someone help me out please.
try this
for (UserDataHelper user:getData())
{
textView.append(user.getID()+" "+user.getName()
+" "+user.getRecieved()+" "+user.getSent()
+" "+user.getTimeSpent()+" "+user.getTotal()+"\n");
}
You could simply use the class object to set/get values, do following for string values:-
textView.setText(quest.getName());
and for the integer values make sure to use one
of the following:-
textView.setText(""+quest.getId());
or
textView.setText(String.valueOf(integer));