populating spinner based on the previous spinner selection in android - 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

Related

Android how to get clicked itemid from Listview and update another column value on this row

I am making small app. It has 2 listview on MainActivity.
DB is SQLLite and has tree cloumns id(int), person(text), status(text).
Firt listview will be show informations from DB with this query
select * from DB where status=B
And next ListView will show information where status=A.
lv1.status=b | lv2.status=a
Person 1 | Person 2
Person 3 | Person 4
When i click lv2 on item, value of clicked lv2 field 'status' must change to 'b'.
But I can not write right query for db.
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Thanks
Here is my code
lvB = (ListView)findViewById(R.id.lvB);
listClientB();
lvA = (ListView)findViewById(R.id.lvA);
listClientA();
lvA.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User)adapterView.getAdapter().getItem(i);
int id = user.get_id();
if (user.getStatus().contains("A")){
dbHelper.changeUser();
}
Toast.makeText(getApplicationContext(), id + "-NUMBER id", Toast.LENGTH_LONG).show();
Log.d(String.valueOf(user.get_id()), "-NUMBER id");
listClientA();
Log.d(user.getStatus(), "Pressed");
}
});
}
private void listClientA(){
list = dbHelper.allUsersA();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvA.setAdapter(klientStatusAdapter);
lvA.setTextFilterEnabled(true);
}
private void listClientB(){
list = dbHelper.allUsersB();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvB.setAdapter(klientStatusAdapter);
lvB.setTextFilterEnabled(true);
}
Here is from DB
public List<User> allUsersA(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'A'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public List<User> allUsersB(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'B'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Here is adapter
public class ClientStatusAdapter extends BaseAdapter{
LayoutInflater inflater;
Context context;
List<User> wordsList;
DbHelper dbHelper;
public ClientStatusAdapter(Context context1, List<User> wordsList) {
this.context = context1;
this.wordsList = wordsList;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dbHelper = new DbHelper(context);
}
#Override
public int getCount() {
return wordsList.size();
}
#Override
public Object getItem(int i) {
return wordsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.kliyent_status_adapter, null);
}
TextView txtIsmAdapter = (TextView)view.findViewById(R.id.txtIsmAdapter);
TextView txtOvqatAdapter = (TextView)view.findViewById(R.id.txtOvqatAdapter);
final User user = wordsList.get(i);
TextView txtCliyentNames = (TextView)view.findViewById(R.id.txtCliyentNames);
txtCliyentNames.setText(user.getClientName());
TextView txtCliyentOrderedFoood = (TextView)view.findViewById(R.id.txtCliyentOrderedFoood);
txtCliyentOrderedFoood.setText(user.getCleintOrderedFood());
TextView txtStatusAdapter = (TextView)view.findViewById(R.id.txtStatusAdapter);
txtStatusAdapter.setText(user.getStatus());
notifyDataSetChanged();
ImageView imgOn = (ImageView) view.findViewById(R.id.imgOn);
return view;
}
}
Here is entity User
public class User {
private int _id;
private String clientName;
private String cleintOrderedFood;
private String status = "A";
public User() {
}
public User(int _id, String clientName, String cleintOrderedFood) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
}
public User(int _id, String clientName, String cleintOrderedFood, String status) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
this.status = status;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCleintOrderedFood() {
return cleintOrderedFood;
}
public void setCleintOrderedFood(String cleintOrderedFood) {
this.cleintOrderedFood = cleintOrderedFood;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
If you look closely at the SQLiteDatabase.update() method, you will see it is declared as
int update (String table,
ContentValues values,
String whereClause,
String[] whereArgs)
Note the last two parameters. These are how you select which rows to update. For example, you can specify to only update rows with a given id:
public void changeUser(int userId){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
String whereClause = "_id = ?";
String where = new String[] {Integer.toString(userId)};
db.update(TABLE_ORDER, values, whereClause, where);
db.close();
}
Here I am assuming you use the conventional column name _id. Of course, you can change this to suit your needs if you have a different column name.
Note that you will now need to pass a parameter to changeUser(). However, you have not shown how nor where you currently call it, so I am unable to provide any advice how to change this.

How to set selection in spinner with SimpleAdapter?

I am populating spinner from below code and its working perfect. When user select any value from spinner then I am saving stateCodeId in sqlite. Now what I want that when user come again then I want to show the seleted value from ID which already saved in sqlite. How can I show value selected in spinner ?
public void fillStateData() {
try {
State_data = new ArrayList<Map<String, String>>();
State_data.clear();
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
int i = 0;
if (cursor_State.moveToFirst()) {
do {
Map<String, String> datanum = new HashMap<String, String>();
if (i == 0) {
datanum.put("nStateID", "0");
datanum.put("cStateName", "Select State");
State_data.add(datanum);
datanum = new HashMap<String, String>();
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
} else {
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
}
i += 1;
} while (cursor_State.moveToNext());
}
String[] fromwhere = {"nStateID", "cStateName"};
int[] viewswhere = {R.id.txtnStateID, R.id.txtcStateName};
StateAdapter = new SimpleAdapter(getActivity(), State_data, R.layout.state_list_template, fromwhere, viewswhere);
spnState.setAdapter(StateAdapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView stateId = (TextView) view.findViewById(R.id.txtnStateID);
stateCodeId = stateId.getText().toString();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Like this I am getting ID from sqlite.
Cursor c = db.rawQuery("SELECT nStateId from MemberMaster where nCustID ="+SesPMbrID+"", null);
c.moveToFirst();
String state = c.getString(0);
Use
spinner.setSelection(position);

transfer checked items in list-view to another list-view on button click in android

I have a listview with data using customAdapter.class now what i want is that to transfer checked items in listview to secondActivity on button click...
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<Model> mylist = new ArrayList<Model>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
// listView = new ArrayList<Model>();
mylist.add(String.valueOf(adapter.getItem(position)));
}
String[] output = new String[mylist.size()];
for (int i = 0; i < mylist.size(); i++) {
output[i] = (mylist.get(i));
}
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", output);
// b.putStringArrayList("SelectedItems: ",list);
// b.putString("selectedItems", String.valueOf(output));
intent.putExtras(b);
startActivity(intent);*/
}
});
and this is the second activity where i am getting that data in another listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Bundle b = getIntent().getExtras();
String[] result = b.getStringArray("selectedItems");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
lv.setAdapter(adapter);
}
The method you followed to send custom list to another activity will not work. In order to transfer your custom list between activities you need to create Parcelable List and send it through intent.
Android Intents does not support custom list.
Custom list can be passed in two ways, Serialization and Parcelable.
But Parcelable is more Efficient and Simple to implement.
Refer this link to send custom list between activities through Parcelable
This link will give you much better idea to implement Parcelable.
Updated Code: Change your Model Code like below.
public class Model implements Parcelable{
private String name;
private int selected;
public Model(String name){
this.name = name;
selected = 0;
}
public String getName(){
return name;
}
public int isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
/**
* Storing the Student data to Parcel object
**/
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(selected);
}
private Model (Parcel in){
this.name = in.readString();
this.selected = in.readInt();
}
public static final Parcelable.Creator<Model> CREATOR = new Parcelable.Creator<Model>() {
#Override
public Student createFromParcel(Parcel source) {
return new Student(source);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
}
Then in the MainActivity do this..
Intent next = new Intent(MainActivity , ResultActivity.class);
next.putParcelableArrayListExtra("model_data", (ArrayList<? extends Parcelable>) selectedItems);
startActivity(next);
In the ResultActivity do this.
ArrayList<Model> his = getIntent().getParcelableArrayListExtra("model_data");
Try the above code..
Good Luck..!!
i solve by saving checked items from listview to sqlite on button click. another button to open new activity and call selected items sqlite this way...
oncheckchange add and remove items in an arraylist and call this in onbutton click like this way...
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view = null;
Support support = (Support) this.getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.view_items, null);
view = new ViewHolder();
view.tvInfo = (TextView) convertView.findViewById(R.id.tvInfo);
view.cb = (CheckBox) convertView.findViewById(R.id.cb);
convertView.setTag(view);
view.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cb = (CheckBox) buttonView;
Support support = (Support) cb.getTag();
support.setSelected(cb.isChecked());
if (isChecked){
selList.add(support.status);
selID.add(support.id);
selType.add(support.type);
// Toast.makeText(CustomAdapter.this, "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}else {
selList.remove(support.status);
selID.remove(support.id);
selType.remove(support.type);
}
}
});
}else{
view = (ViewHolder) convertView.getTag();
view.cb = view.getCb();
view.tvInfo = view.getTvInfo();
}
view.cb.setTag(support);
support = list.get(position);
String id = support.getId();
String status = support.getStatus();
String type = support.getType();
view.cb.setChecked(support.isSelected());
// view.tvInfo.setText(id + "," + status + "," + type);
view.tvInfo.setText(status);
return convertView;
}
this is button coding to add to db
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.addSelected(adapter.selList, adapter.selID, adapter.selType);
and this is how to insert to sqlite..
public void addSelected(ArrayList<String> selList, ArrayList<String> selID, ArrayList<String> selType) {
int size = selID.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
// cv.put(KEY_ID, selID.get(i).toString());
cv.put(KEY_ID, selID.get(i));
cv.put(KEY_STATUS, selList.get(i));
cv.put(KEY_TYPE, selType.get(i));
Log.d("Added ",""+ cv);
db.insertOrThrow(TABLE_SELECTED, null, cv);
}
db.close();
}catch (Exception e){
Log.e("Problem", e + " ");
}
}
and get back from db like this
public ArrayList<String> getSelected() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> result = null;
try{
result = new ArrayList<String>();
// String query = "SELECT * FROM " + TABLE_SELECTED;
String query = "SELECT " + KEY_ID + " FROM " + TABLE_SELECTED;
Cursor c = db.rawQuery(query, null);
if (!c.isLast()){
if (c.moveToFirst()){
do{
String sel_name = c.getString(c.getColumnIndex("_id"));
result.add(sel_name);
Log.d("Added ", sel_name);
}while (c.moveToNext());
}
}
c.close();
db.close();
}catch (Exception e){
Log.e("Nothing is to show", e + " ");
}
return result;
}

Need to get the Id of a selected item in a spinner from sqlite

im a newbie to android and i have this problem here hope you guys can help me with this :)
anyways, i want to get the id of a selected item in the spinner from sqlite database so that i can save it to another table later on.
here's my code:
in my DB.java :
public List<String> getSemesterList() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SEMESTER;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(1)));
} while (c.moveToNext());
}
return List;
}
public String getSemesterId() {
String[] columns = new String[] { KEY_SEMESTER_ID, KEY_SEMESTER };
Cursor c = ourDatabase.query(TABLE_SEMESTER, columns, null, null, null, null, null, null);
int id = c.getColumnIndex(KEY_SEMESTER_ID);
String semId = "";
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
semId = semId + c.getInt(id) + " "
+ "\n";
}
return semId ;
}
and in my createSYAttended.class
// TODO Auto-generated method stub
DB entry = new DB(this);
entry.open();
final List<String> all = entry.getSemesterList();
if(all.size()>0) // check if list contains items.
{
sqlSem = (Spinner) findViewById(R.id.sprSemester);
arrayAdapter = new ArrayAdapter<String>(CreateSyAttended.this,android.R.layout.simple_spinner_dropdown_item, all);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sqlSem.setAdapter(arrayAdapter);
entry.close();
sqlSem.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
} }
use a mapping for the index of your List<String> all = entry.getSemesterList(); to the spinner item
so when you get below callback
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
you can then use the position you get in the callback to map to the item in the semesterList all

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