Alphabet Indexed ListView Without a cursor - android

I receive data from a server using JSON and I want to order them alphabetically with alphabet indexed section and store them in a ListView.
Maybe something that will happen in :
for(int i=0;i<jArray.length();i++){
// here
}
I read that you can order elements like that only using a cursor. In my case would be very inefficient to store the elements from the server in the database and read them again. Waste of time and memory.
So, I am asking you if there could be any solution for my problem : order alphabetically with alphabet indexed section string received from JSON .
EDIT: I want my listview to look like this http://eshyu.wordpress.com/2010/08/15/cursoradapter-with-alphabet-indexed-section-headers/ . I mean with those sections . All tutorials I found said that you need to fetch information with a cursor. My question was if I could't do this wihout a cursor, because it would be a waste of memory to store them in the local database too.

You may need to parse the JSON Array :
List<Project> list = new ArrayList<Project>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = (JSONObject) jArray.get(i);
project = new Project();
project.setId( Long.parseLong(obj.get("id").toString()));
project.setKey(obj.get("key").toString());
project.setName(obj.get("name").toString());
list.add(project);
}
You can use the comparator class like this to sort them :
Collections.sort(list), new Comparator<Project>() {
public int compare(Project p1, Project p2) {
return p1.getKey().compareToIgnoreCase(p2.getKey());
}
});
You can also have Project class and implements Comparable:
public class Project implements Comparable<Project> {
private long id;
private String key;
private String name;
public int compareTo(Project p) {
if (this.key > p.key)
return -1;
else if (this.key < p.key)
return 1;
return 0;
}
}
And then sort the list by Collections.sort(list);
My suggestion is try to sort the data in the Server-side, because the memory of the phone is limited and it may make you application time consuming to show the data, but you do not have memory limitation problem in the Server-side.

use a comparator to sort the arraylist as described here . And then use an ArrayAdapter to show the items in Listview

Related

Android ArrayList<String> stored not restored back to its saved sorted order

I have an myArrayList which is to be stored and restored back in its saved sorted order. But the code does not do that. Why?
ArrayList<String> myArrayList
// save:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit;
edit = prefs.edit();
edit.putStringSet("mydata", new LinkedHashSet<String>(myArrayList));
edit.commit();
// read:
myArrayList = new ArrayList<String>(PreferenceManager
.getDefaultSharedPreferences(getBaseContext()).getStringSet(
"mydata", new LinkedHashSet<String>()));
adapterAppList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
myArrayList);
Is there any better way I can store the value of myArrayList and restored back to its original saved sorted order?
HashSet is not keeping orders, it is ordering for quickest find to it. You can convert list to json and save as string.
When you need to it, you can convert it to ArrayList from json with keeped ordering.
Example:
String listAsString = new Gson().toJson(arrayList); //list to string
List<String> arrayList = Arrays.asList(new Gson().fromJson(listAsString,String[].class)) //string to list
dont forget add library to build.gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
You can serialize arrayList like string:
1 with gson
public ArrayList<String> convertToArrayList(String json) {
if (TextUtils.isEmpty(json)){
return null; // or new ArrayList<>()
}
Type type = new TypeToken<ArrayList<String>>(){}.getType();
return new Gson().fromJson(json, type);
}
public String convertFromArrayList(ArrayList<String> list) {
if (list == null){
return null;
}
return new Gson().toJson(list);
}
2 without gson
public ArrayList<String> convertToArrayList(String st) {
if (!TextUtils.isEmpty(st)){
String[] str = st.split(",");
if (str.length > 0){
return new ArrayList<>(Arrays.asList(str));
}
}
return null;
}
public String convertFromArrayList(ArrayList<String> list) {
if (list!=null && !list.isEmpty()){
return TextUtils.join(",", list);
}
return null;
}
Yes, you are right, the order is not stored in string set, coz it is a set (duh).
When I was bugged with this, I got the serializing solution where, you can serialize your string.
Read this only if you haven't read about serializing, else go down and read my hack
In order to store array items in order, we can serialize the array into a single string (by making a new class ObjectSerializer (copy the code from – www.androiddevcourse.com/objectserializer.html , replace everything except the package name))
Entering data in Shared preference :
the rest of the code on line 38 -
Put the next arg as this, so that if data is not retrieved it will return empty array(we cant put empty string coz the container/variable is an array not string)
Coming to my Hack :-
Merge contents of array into a single string by having some symbol in between each item and then split it using that symbol when retrieving it.
If you are worried about splitting just look up "splitting a string in java".
[Note: This works fine if the contents of your array is of primitive kind like string, int, float, etc. It will work for complex arrays which have its own structure, suppose a phone book, but the merging and splitting would become a bit complex. ]
PS: I am new to android, so don't know if it is a good hack, so lemme know if you find better hacks.

Fetch a single column from Realm Database (Android)

I'm a beginner in Realm.
I have a table with 3 columns which named Id, Name, Email,Address.
To get the data of Name column, we use a query like 'SELECT Name from table_name' for SQLite.
If we using Realm in Android, then which method do we have to use for fetching the data of only one column?
I searched alot on Google & documentation but to no avail.
Could anyone help me?
Update:
What I am tried:
RealmResults<User> results = query.findAll();
ArrayList<String> name = new Arraylist();
for(i=0; i<results.size; i++){
name.add(result.get(i).getName();
}
My problem:
results.size() > 10k. So I want to avoid 10k iteration
for(i=0; i<results.size; i++){
}
Look at queries section at the documentation:
All fetches (including queries) are lazy in Realm, and the data is never copied.
This mean, that data of particular column (property) will be fetched when you call getMyProperty() method. Not after call of finadAll() method of RealmQuery object
If we using Realm in Android, then which method do we have to use for fetching the data of only one column?
You can't, because Realm is an object store, it doesn't have concept of "columns".
My problem:
results.size() > 10k. So I want to avoid 10k iteration
for(i = 0; i < results.size(); i++){
}
Solution: don't iterate?
RealmResults<User> results = query.findAll();
//List<String> name = new ArrayList<>();
//for(i = 0; i < results.size(); i++){
// name.add(result.get(i).getName();
//}
return results;
// ...
String name = results.get(position).getName();

How to sort list view data which is backed with API Response and containing more then one field in each row

I want to sort data in ListView. Which contains title,description ,price at their respective position in each row. I want to implement sort functionality on title in alphabetical order. All field are stored in different array. After sorting each filed should according title. What to do? Please explain with detail example.
Create one Bean Class
Your array
array 1) title[]
array 2) description[]
for example DataBean
public class DataBean
{
String title,desc;
DataBean(String title,String desc)
{
this.title=title;
this.desc=desc;
}
}
Use this code to merge data
Create Vector;
ex: Vector vec = new Vector;
for(int i=0; i< yourArray.length; i++)
{
vec.add(title[i],description[i]);
}
Now you have vec of your date.
Just perform SORT on any field.
either title or desc.
You will get your sorted data.

For-loop not working the way i want it to

I have a extremely minor issue that I can't seem to figure out. I'm trying to extract data based on a type of value from an ArrayList> and place it into another ArrayList. The issue is that the for-loop only runs once, which in this case i need it to traverse the entire array and then place the data into the unSuppressedData arraylist.
Below is the for-loop:
for (int x = 0; x < suppressedStatus.length; x++) {
for (int i = 0; i < availData.size(); i++) {
Hashtable<String,String> checkAvail = availData.get(i);
String itemStatus = checkAvail.get("loanStatus");
if (unSuppressedData.contains(checkAvail) == false) {
if (!(itemStatus.equals(suppressedStatus[x]))) {
Log.d("Item Status", itemStatus);
Log.d("Suppressed Status", suppressedStatus[x]);
unSuppressedData.add(checkAvail);
//break;
}
}
}
}
suppressedStatus is a String array
availData is the arraylist i want to extract data from
unSuppressedData is the arraylist i want to place the data in
I believe that it only runs once is due to this line of code:
if (unSuppressedData.contains(checkAvail) == false) {
But i need to this line to check whether my unSuppressdData has the data, if no then will add the data from availData arraylist into unSuppressedData arraylist.
Could it be that i'm writing this piece of code wrongly? Appreciate any insights shed on this.
A good collection type for this sort of thing is the LinkedHashSet. Because it's a set, each element can only be added once. Being a hash, the contains test is quick. Being 'linked' the resulting set is iterated in insertion order.

can't get the text from an autocomplete

I have to create an app in android with a database.In that database I have a predefined list of products.
Now,the thing is that my ap has to offer to the user the posibility to introduce in that list some other products which are not in the list.
To this end, I've created an autocomplete text view in which I introduce a new product and I take the text fro autocomplete and I have to write it in the database
Now,my problem is that when I display the products that I've introduced in the database,the toast text that I use to display what I have in the database it shows me nothing next to "product......".
Now,that may be because when I try to get the text from the autocomplete I get nothing in return?
This is how I read from autocomplete:
mItem = (AutoCompleteTextView) findViewById(R.id.todo_edit_item);
String nou=mItem.getText().toString();
And then I compare nou(which is what I wrote in the autocomplete) with what I have predefnied in the list,so if it is a new product(which was not in the list already) the I add it in the database:
for(int i = 0; i < l; i++)
{
if (nou!=fruits[i])
t=true;
else t=false;
}
if (t==true)
{
db.insertTitle(nou);
fruits=db.getAllfromDB("Fruits","fruit");
l=l+1;
}
Anyone any ideas of what I'm doing wrong in here cause I can't figure out.I'lll be here for further details.Thank u in advance:)
You compare strings using != instead of using !nou.equals(fruits[i]). also you compare to all elements in array each time, since you so t is always the value of the comparison to the last element in the array whether a match was found or not.
It should be written like that:
t = true;
for(int i = 0; i < l; i++)
{
if (nou.equals(fruits[i]))
{
t=false;
break;
}
}
if (t==true)
{
db.insertTitle(nou);
fruits=db.getAllfromDB("Fruits","fruit");
l=l+1;
}

Categories

Resources