Sorting names in a list alphabetically? - android

Can you please help me for sorting a list alphabetically
My code
emailList.add(contact.getUserName());
String[] emails = new String[emailList.size()];
emailList.toArray(emails);
namesList.add(name);
Collections.sort(emailList, new Comparator() {
public int compare(Object o1, Object o2) {
String name1 = (String) o1;
String name2 = (String) o2;
return name1.compareToIgnoreCase(name2);
}
});
System.out.println("namesList.toString() = " + namesList.toString());

You don't need to create a new comparator. Just call Collections.sort(emailList);.
UPDATE:
Collections.sort(emailList, new Comparator<String>()
{
#Override
public int compare(String text1, String text2)
{
return text1.compareToIgnoreCase(text2);
}
});

Related

Android Volley Array in JSON

I have this kind of JSON response
{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}
And I am able to parse country, country_id, and currency without a problem, problem starts with the product list when I am trying to parse it! below the code
try {
boolean error = response.getBoolean("error");
if (!error){
String country = response.getString("country");
int country_id = response.getInt("country_id");
String currency = response.getString("currency");
List<Tarif> tarifs = new
Gson().fromJson(response.getJSONArray("product_list").toString(), new
TypeToken<List<Tarif>>(){}.getType());
new DtoneTarifs(country, country_id, currency, tarifs);
}
}
And here is my Tarif and Other Class
public class Tarifs {
public String country;
public int country_id;
public String currency;
public List<Tarif> tarifList;
public Tarifs (String country, int country_id, String currency, List<Tarif> tarif){
this.country = country;
this.country_id = country_id;
this.currency = currency;
this.tarifList = tarif;
}
}
I want to fill the product_list in Tarif class where only one parameter accept and show them in recycler_view
{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}
You can see that product_list is JSON Array of string values. But you are converting it into list of Tarif type. It should be converted into list of string type.
Either set values of Tarif as custom objects to JSON Array or change your list type to string.
It should be like this:
try {
boolean error = response.getBoolean("error");
if (!error){
String country = response.getString("country");
int country_id = response.getInt("country_id");
String currency = response.getString("currency");
List<String> tarifs = new
Gson().fromJson(response.getJSONArray("product_list").toString(), new
TypeToken<List<String>>(){}.getType());
Tarifs result = new Tarifs(country, country_id, currency, tarifs);
}
}
Tarifs Class
public class Tarifs {
public String country;
public int country_id;
public String currency;
public List<String> tarifList;
public Tarifs (String country, int country_id, String currency, List<String> tarif){
this.country = country;
this.country_id = country_id;
this.currency = currency;
this.tarifList = tarif;
}
}
Here you go!

New to Android Studio: How to add custom text into ListView/ListAdapter results?

I have a silly question here. I am also new to these, please show some codes if possible.
Android Studio: How to append a custom text into ListView/ListAdapter?
I would like to add the extra text before my raw Stock ID.
Example: Product ID: 1,
Product ID: 2
raw Stock ID is obtained from a Database server using php sql.
I tried use this following line to do this but there is some problem because I'm going to reference Config.TAG_ID in my onItemClick function to pass it to the next activity.
//employees.put(Config.TAG_ID, "ID: " + id);
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewStock.class);
HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
String empId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.STOCK_ID, empId);
startActivity(intent);
}
Function that shows my stock list
private void showEmployee() {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String name = jo.getString(Config.TAG_NAME);
String price = jo.getString(Config.TAG_PRICE);
HashMap<String, String> employees = new HashMap<>();
employees.put(Config.TAG_ID, id);
//employees.put(Config.TAG_ID2, "ID: " + id);
employees.put(Config.TAG_NAME, "Product name: " + name);
employees.put(Config.TAG_PRICE, "Price: ($)" + price);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ViewAllStock.this, list, R.layout.list_item,
new String[]{ Config.TAG_ID, Config.TAG_NAME, Config.TAG_PRICE},
new int[]{ R.id.id, R.id.name, R.id.price});
listView.setAdapter(adapter);
}
EDITED: Error picture for GreyWolf's answers:
You can use SimpleAdapter's setViewBinder() method to provide a binder that will translate the data into text fields to set in your view.
Setup your data as follows:
HashMap<String, String> employees = new HashMap<>();
employees.put(Config.TAG_ID, id);
employees.put(Config.TAG_NAME, name);
employees.put(Config.TAG_PRICE, price);
list.add(employees);
And your adapter as follows:
SimpleAdapter adapter = new SimpleAdapter(
ViewAllStock.this, list, R.layout.list_item,
new String[]{ Config.TAG_ID, Config.TAG_NAME, Config.TAG_PRICE},
new int[]{ R.id.id, R.id.name, R.id.price});
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if (view.getId() == R.id.id) {
TextView v = (TextView) view;
v.setText("Product ID: " + textRepresentation);
return true;
} else if (view.getId() == R.id.name) {
TextView v = (TextView) view;
v.setText("Product Name: " + textRepresentation);
return true;
} else if (view.getId() == R.id.price) {
TextView v = (TextView) view;
v.setText("Price: ($)" + textRepresentation);
return true;
}
return false;
}
});
listView.setAdapter(adapter);
Now the data values remain pure and can be passed unaltered in your activity intent.
employees.put(Config.TAG_ID, "Product ID"+id);
public class ProductPogo {
String id;
String productName;
String price;
public String getId() {
return id;
}
public String setId(String id) {
this.id = id;
return id;
}
public String getProductName() {
return productName;
}
public String setProductName(String productName) {
this.productName = productName;
return productName;
}
public String getPrice() {
return price;
}
public String setPrice(String price) {
this.price = price;
return price;
}
}
//in your doInBackground
JSONObject productJsonObject = myPriceJsonArray.getJSONObject(p);
id =productPogo.setId("Product ID"+productJsonObject.getString("id"));
productName = productPogo.setProductName(productJsonObject.getString("productName"));
= productPogo.setPrice(productJsonObject.getString("price"));
yourArraylist.add(productPogo);
//InOnItemClickListner
Bundle bundle=new Bundle();
bundle.putString("product_id", yourArraylist.get(position).getId());

populating spinner based on the previous spinner selection in android

Am not familiar with android development,and i came across a situation to cascade a dropdown based on the first spinner selection.i.e.,consider for an example in 1st spinner all states data are loaded from web service using db helper class while selecting the state name in the 1st spinner i need to populate the 2nd spinner based on the 1st spinner selected item's id(stateid not that spinner's selected item id) from db which means i need to select the stateid from the selected state and want to filter the districts based on the states.
State table creation:
CREATE TABLE States( StateID INTEGER , StateName VARCHAR) District table creation: CREATE TABLE Branches(_ID INTEGER PRIMAY KEY,DistrictName VARCHAR,StateID INTEGER)
In this I have used to load data for states by using arraylist and on spinner1.setOnItemSelectedListener function loaded the district values but the values are loading as per the position of the items in the states spinner instead of that i need to filter based on the stateid in the branch table.
This is the code for getting all states:
public ArrayList<HashMap<String, String>> getStatesData() {
ArrayList aList = new ArrayList();
try {
Log.e("getStatesData", "Started");
String selectQuery = "SELECT * FROM States";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("StateID",
cursor.getString(cursor.getColumnIndex("StateID")));
map.put("StateName", cursor.getString(cursor
.getColumnIndex("StateName")));
aList.add(map);
} while (cursor.moveToNext());
}
cursor.close();
return aList;
} catch (Exception e) {
e.printStackTrace();
Log.e("getStatesData", "Ended");
return aList;
}
}
spinner1.setonitemselectedlistner event:
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapt, View v,
int pos, long id) {
// TODO Auto-generated method stub
long spinstate=spinner_state.getSelectedItemId();
branch_values=sDBController.getStateselectidData(spinstate);
branch_name_ary.clear();
for (int i = 0; i < branch_values.size(); i++) {
String name=branch_values.get(i).get("DistrictName");
String id=branch_values.get(i).get("StateID");
branch_name_ary.add(name);
Log.e("branchesbystates", branch_name_ary.toString());
}
ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, branch_name_ary);
spinnerArrayAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_district.setAdapter(spinnerArrayAdapter1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Please suggest some solution to get the districts based on the stateid which may help to get an idea solve the issue.
Thanks in advance.
if i were you, i would create a State like so
public class State {
private String id;
private String name;
public State(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
and the getStatesDate method would be like this:
public List<State> getStatesData()
{
List<State> states = new LinkedList<State>();
try {
Log.e("getStatesData", "Started");
String selectQuery = "SELECT * FROM States";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String stateId = cursor.getString(cursor.getColumnIndex("StateID"));
String stateName = cursor.getString(cursor.getColumnIndex("StateName"));
states.add(new State(stateId, stateName));
} while (cursor.moveToNext());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("getStatesData", "Ended");
}
return states;
}
and the spinner1 onClicklistener will also be like this:
spinner1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
State state = (State) spinner1.getSelectedItem();
String stateId = state.getId();
String stateName = state.getName();
//you are very assured that the id matches the name selected and you can proceed from there
}
});
I hope it helps. Cheers
Best option is yo use "switch case" like this:
int spinner = 0;
String bereichlink ="";
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
int spinnerId = getView(position, v, parent).getId();
searchstring = sstr.getText().toString();
switch (parent.getId()) {
case R.id.REditText:
if (position > 0) {
spinner = position;
Link = links[position];
spinner2 = (Spinner) findViewById(R.id.sp_bereich);
adapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, Constants.bereich[position - 1]);
spinner2.setAdapter(adapter2);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
new FetchFeedTask().execute((Void) null);
spinner2.setSelection(0);
}
break;
case R.id.sp_bereich:
if (position >= 0) {
bereichlink = Constants.bereich[spinner-1][position];
new FetchFeedTask().execute((Void) null);
}
bereichlink = "";
break;
}
if ((spinner > 0) && (position > 0)) {
...
}
with "Links" and "Bereich" as const enum typs arrays

Android: nullPointerException when using Parcelable interface in class with ArrayList<customObject>

I am trying to make the class called Music use parcelable so I can access an instance of Music in two different activities. I don't want to use serializable for speed purposes. I keep getting a nullPointerException when I try to pass it using:
Intent in = getIntent();
thisInstance = (Music) in.getExtras().get("MusicInstance");
Music Class: (the ArrayList is at the top and parcelable classes at the bottom)
public class Music implements Parcelable{
private static ArrayList<genericSongClass> songs = new ArrayList<genericSongClass>();
Cursor cursor;
static Context context;
public Music(Context context){
this.context = context;
}
public Music(Parcel in){
in.readTypedList(songs, genericSongClass.CREATOR);
}
public void BindAllSongs() {
/** Making custom drawable */
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String[] projection = new String[] {
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
try {
// the uri of the table that we want to query
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
// query the db
cursor = context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
songs = new ArrayList<genericSongClass>(cursor.getCount());
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
genericSongClass GSC = new genericSongClass();
GSC.songTitle = cursor.getString(0);
GSC.songArtist = cursor.getString(1);
GSC.songData = cursor.getString(2);
GSC.songAlbum = cursor.getString(3);
songs.add(GSC);
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static Object[] toArray(ArrayList<Object> list){
Object[] toReturn = new Object[list.size()];
for (int i = 0; i < list.size(); i++){
toReturn[i] = list.get(i);
}
return toReturn;
}
public ArrayList<String> getArtists(){
ArrayList<String> artists = new ArrayList<String>();
for(genericSongClass gsc: songs){
if(!artists.contains(gsc.songArtist)){
artists.add(gsc.songArtist);
}
}
Alphabetize forArtists = new Alphabetize(artists);
return forArtists.getSortedArrayList();
}
public ArrayList<String> getAlbums(String artist){
ArrayList<String> albums = new ArrayList<String>();
for(genericSongClass gsc: songs){
if(gsc.songArtist == artist){
albums.add(gsc.songAlbum);
}
}
Alphabetize forAlbums = new Alphabetize(albums);
return forAlbums.getSortedArrayList();
}
//--- Parcel ------------------------------------------------
public static final Parcelable.Creator<Music> CREATOR = new Parcelable.Creator<Music>() {
public Music createFromParcel(Parcel in) {
return new Music(in);
}
#Override
public Music[] newArray(int size) {
return new Music[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(songs);
}
}
genericSongClass:
public class genericSongClass implements Parcelable {
String songTitle = "";
String songArtist = "";
String songData = "";
String songAlbum = "";
public genericSongClass(){};
private genericSongClass(Parcel in){
songTitle = in.readString();
songArtist = in.readString();
songData = in.readString();
songAlbum = in.readString();
}
public static final Parcelable.Creator<genericSongClass> CREATOR = new Parcelable.Creator<genericSongClass>() {
#Override
public genericSongClass createFromParcel(Parcel source) {
return new genericSongClass(source);
}
#Override
public genericSongClass[] newArray(int size) {
return new genericSongClass[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(songTitle);
dest.writeString(songArtist);
dest.writeString(songData);
dest.writeString(songAlbum);
}
}
Why am I getting the nullpointer and how do I remedy the situation?
This is my first time using Parcelable, so any help/advice is more than welcome. Thanks in advance!
initialize your list into constructor.use following code please.
public Music(Parcel in){
songs = new ArrayList<genericSongClass>();
in.readTypedList(songs, genericSongClass.CREATOR);
}
and get with this code:
thisInstance = getIntent().getParcelableExtra("MusicInstance");
and make sure you initialize thisInstance.
getParcelableArrayListExtra , getParcelableExtra
as well as
putParcelableArrayListExtra , putExtra(String name, Parcelable value)
are used to pass Parcelable's through intents.

How to sorting listview array with menu item in android

I have code to get phone contact from server in android , I use menu item to make it , this is my code
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
int row = cursor.getCount();
friend_item = new MenuItem [row];
//int i=0;
while(cursor.moveToNext()){
nama = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// friend_item[i] = new MenuItem(nama,phone);
//i++;
}
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Log.d("", "" + cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneList.add(phone);
cursor.moveToNext();
}
cursor.close();
String [] phonearray = (String[]) phoneList.toArray(new String[phoneList.size()]);
// friendarray();
String friends=phonearray[0]+"";
for(int a=1; a<phonearray.length; a++){
friends = friends + ","+ phonearray[a];
}
Log.d("" , "" + friends);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("phone", mPhoneNumber));
params.add(new BasicNameValuePair("friend", friends));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(Constants.url_phone_contact, "POST", params);
// Check your log cat for JSON reponse
Log.d("All Friend: ", json.toString());
try {
friend = json.getJSONArray("friend");
friend_item = new MenuItem[friend.length()];
// looping through All Products
for (int a = 0; a < friend.length(); a++) {
JSONObject c = friend.getJSONObject(a);
//Storing each json item in variable
phone_friend= c.getString("phone");
id_friend = c.getString("id_ref");
Log.e("id_user", id_friend);
namaFriend = getName(phone_friend);
if(phone_friend == null){
Toast.makeText(getApplicationContext(), "contact not found", Toast.LENGTH_LONG).show();
}else{
friend_item[a] = new MenuItem(namaFriend, phone_friend);
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
//map1.put("phone", mPhoneNumber);
map1.put("id_ref", id_friend);
map1.put("nama_friend", namaFriend);
// adding HashList to ArrayList
friendList.add(map1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//i++;*/
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if(friend_item != null && friend_item.length > 0){
mainlist.setAdapter(new ListMenuAdapter(friend_item));
} else
Toast.makeText(getApplicationContext(), "You don't have friend using Shoop! yet, please invite them :)", Toast.LENGTH_LONG).show();
}
}
to get name from android device , I use this code
private String getName(String number) {
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor c = getContentResolver().query(contactUri, projection, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +" ASC");
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
this List menu adapter
private class ListMenuAdapter extends BaseAdapter{
private MenuItem [] item;
protected ListMenuAdapter(MenuItem... item){
this.item = item;
}
public int getCount() {
return item.length;
}
public Object getItem(int pos) {
return item[pos];
}
public long getItemId(int position) {
return position;
}
public ViewGroup getViewGroup(int position, View view, ViewGroup parent){
if(view instanceof ViewGroup){
return (ViewGroup) view;
}
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
ViewGroup viewgroup = (ViewGroup)inflater.inflate(R.layout.custom_content_friend, null);
return viewgroup;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup group = getViewGroup(position, convertView, parent);
MenuItem menu = item[position];
TextView name = (TextView) group.findViewById(R.id.content_friend_myname);
TextView phone = (TextView) group.findViewById(R.id.content_friend_desc);
if(menu.my_name == null || menu.phone == null){
Toast.makeText(getApplicationContext(), "Contact not found", Toast.LENGTH_LONG).show();
}else{
name.setText(menu.my_name);
phone.setText(menu.phone);
}
return group;
}
}
private class MenuItem{
private String my_name, phone;
protected MenuItem(String my_name, String phone){
this.my_name = my_name;
this.phone= phone;
}
}
and now , I want to get List view that contain name and phone with sorting ascending by name , How to do that?? thanks for ur advice
- First use an ArrayList instead of Array to store the data which will further being used by the Adapter.
- Use java.util.Comparator<T> to sort the name and phone (ie. contacts) according to the name.
- Use Collections.sort(List<?> l , Comparator c) to invoke the sorting.
- And also call notifyDataSetChanged() on the Adapter after setting the ListView with the adapter.
Eg:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Car {
private String name;
private String brand;
private double cost;
public Car(String name, String brand, double cost) {
this.name = name;
this.brand = brand;
this.cost = cost;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public String toString() {
return getName();
}
}
public class Hog {
ArrayList<Car> cars = new ArrayList<Car>();
public void setIt() {
cars.add(new Car("Padmini", "Fiat", 100008.00));
cars.add(new Car("XYlo", "Mahindra", 100000.00));
cars.add(new Car("Swift", "Maruti", 200000.00));
}
public void sortIt() {
Collections.sort(cars, new NameComparator());
System.out.println(cars);
Collections.sort(cars, new BrandComparator());
System.out.println(cars);
Collections.sort(cars, new CostComparator());
System.out.println(cars);
}
class NameComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
return c1.getName().compareTo(c2.getName());
}
}
class BrandComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
return c1.getBrand().compareTo(c2.getBrand());
}
}
class CostComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
return new Double(c1.getCost()).compareTo(new Double(c2.getCost()));
}
}
public static void main(String[] args) {
Hog h = new Hog();
h.setIt();
h.sortIt();
}
}
In your activity class write this:
public class MyActivity extends Activity {
....
private ListView listView01;
private ArrayList<MenuItem> list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
listView01 = (ListView)findViewById(R.id.listView1);
list=new ArrayList<MyActivity.MenuItem>();
// code to fill your ArrayList
Collections.sort(list, myComparator);
listView01.setAdapter(new ListMenuAdapter());
}
Comparator<MenuItem> myComparator = new Comparator<MenuItem>()
{
public int compare(MenuItem arg0,MenuItem arg1)
{
return arg0.my_name.compareTo(arg1.my_name);
}
};
}

Categories

Resources