I just want to know how to, if a Hashmap is already on the list add 1 to quantity, if it is not then add it to list. This is what I've done that just add eventhough the item is already on list.
list = new ArrayList<HashMap<String, String>>();
Cursor c = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + txtCode.getText().toString(), null); //search database
if (c.moveToFirst()){ //if successful
txtDesc.setText(c.getString(1)); //get desc
txtPrice.setText(c.getString(2)); // get price # database
HashMap<String, String> map = new HashMap<String, String>();
map.put("desc", c.getString(1));
map.put("price", c.getString(2));
map.put("quantity","1");
list.add(map);
adapter.notifyDataSetChanged();
From your last comment, I think I see what you're trying to do. Firstly, I would create a small class holding the information about your items, to make it a bit easier to work with (I've only implemented the necessary setters, you'll probably want some getters (and other functions) as well):
public class MyItem
{
String description;
float price;
int quantity;
public void setDescription(String description)
{
this.description = description;
}
public void setPrice(float price)
{
this.price = price;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public void increaseQuantity()
{
this.quantity++;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyItem other = (MyItem) obj;
if (description == null)
{
if (other.description != null)
return false;
}
else if (!description.equals(other.description))
return false;
return true;
}
}
I have implement the equals method (and it is common to then also implement the hash method) to easily be able to check if an item exists in the list (for simplicity, I assume that the description uniquely identifies an item, you should change this as needed). You can then continue with your processing like this:
public void queryForItem(String itemCode)
{
Cursor cursor = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + itemCode, null);
if (cursor.moveToFirst())
{
processCursor(cursor);
}
cursor.close();
}
private void processCursor(Cursor c)
{
MyItem newItem = new MyItem();
newItem.setDescription(c.getString(1));
newItem.setPrice(c.getFloat(2));
newItem.setQuantity(1);
// assuming that items (ArrayList<MyItem>) is defined and initialized earlier in the code
int existingItemIndex = items.indexOf(newItem);
if (existingItemIndex >= 0)
{
items.get(existingItemIndex).increaseQuantity();
}
else
{
items.add(newItem);
}
adapter.notifyDataSetChanged();
}
I haven't tested this in any way, but I thing it should do what you want. Hope you're able to see the logic in it :)
I came up with this solution, however if an item exist it only update the quantity 2 times on 3rd try It creates new list item with same desc, price but 1 quantity.
Cursor c = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + txtCode.getText().toString(), null); //search database
if (c.moveToFirst()){ //if successful
txtDesc.setText(c.getString(1)); //get desc
txtPrice.setText(c.getString(2)); // get price # database
HashMap<String, String> map = new HashMap<String, String>();
map.put("desc", c.getString(1));
map.put("price", c.getString(2));
if(list.isEmpty()){
map.put("quantity","1");
list.add(map);
adapter.notifyDataSetChanged();
}
else{
if(list.contains(map)){
int loc = list.indexOf(map);
Object o = list.get(loc);
#SuppressWarnings("unchecked")
HashMap<String, String> map2 = (HashMap<String, String>)o;
String b = (String) map2.get("quantity");
int quantity = Integer.parseInt(b) + 1;
map2.put("quantity", Integer.toString(quantity));
adapter.notifyDataSetChanged();
}
else{
map.put("quantity","1");
list.add(map);
adapter.notifyDataSetChanged();
}
Related
I have three tables in mySQL namely user, restaurants, cartlist.
here user table is for saving the user details.
restaurant table is for saving the meal details, price and quantity.
cartlist is to add the restaurant details.
Now when the specific user login to the app, I want the cartlist items of specific user added to the list. but Im getting the details of whole users who added items to the cart.
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String selectQuery = "SELECT * FROM restaurants";
SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
ProductModel productModel = new ProductModel();
productModel.setID(Integer.parseInt(cursor.getString(0)));
productModel.setName(cursor.getString(1));
productModel.setMealname(cursor.getString(2));
productModel.setMealprice(cursor.getString(3));
productModel.setMealqty(cursor.getString(4));
products.add(productModel);
} while (cursor.moveToNext());
}
cursor.close();
DatabaseManager.getInstance().closeDatabase();
adapter = new ProductAdapter(ProductList.this, R.layout.activity_cartlistview, products);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
Carttable:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
lv_checkout = findViewById(R.id.lv_checkout);
tv_totalamount = findViewById(R.id.tv_totalamount);
btn_checkouttopayment = findViewById(R.id.btn_checkouttopayment);
String selectQuery = "SELECT * FROM carttable";
SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
ProductModel productModel = new ProductModel();
productModel.setID(Integer.parseInt(cursor.getString(0)));
productModel.setName(cursor.getString(1));
productModel.setMealname(cursor.getString(2));
productModel.setMealprice(cursor.getString(3));
productModel.setMealqty(cursor.getString(4));
productModel.setMealtotal((Double.parseDouble(cursor.getString(3)) * Double.parseDouble(cursor.getString(4)) + ""));
products.add(productModel);
} while (cursor.moveToNext());
}
double totalPrices = 0;
for (int i = 0; i < products.size(); i++) {
totalPrices += Double.parseDouble(products.get(i).getMealtotal());
}
tv_totalamount.setText("Total Amount to be Paid : " + totalPrices + "");
cursor.close();
DatabaseManager.getInstance().closeDatabase();
adapter = new ProductAdapter(this, R.layout.activity_cartlistview, products);
lv_checkout.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
what are the changed to be done to the query? Let me knw guys.TIA!
It's because The query you are running is going to the Restaurant table and getting all the Records from It. From what I can understand, Cartlist the name of table in which a user will input the details of a particular restaurant. So Right now, you are calling all the records from Restaurant table which will give you the list regardless of who added it.
You might want to change the query to something like
SELECT restaurant_name FROM cartlist WHERE userName = selected_User;
Now you have the restaurant name. Save these and use it on query.
SELECT * FROM restaurants WHERE restaurantsName = selected_restaurant_name;
do {
ProductModel productModel = new ProductModel();
productModel.setID(Integer.parseInt(cursor.getString(0)));
productModel.setName(cursor.getString(1));
productModel.setMealname(cursor.getString(2));
productModel.setMealprice(cursor.getString(3));
productModel.setMealqty(cursor.getString(4));
productModel.setMealtotal((Double.parseDouble(cursor.getString(3)) * Double.parseDouble(cursor.getString(4)) + ""));
products.add(productModel);
}
Add a constructor to your model class and inject in. Saves a few lines of code/readability.
do {
products.add( new ProductModel(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
}
The line: productModel.setMealtotal((Double.parseDouble(cursor.getString(3)) * Double.parseDouble(cursor.getString(4)) + ""));
seems to contain a simple relationship where the "Meal total = mean quantity * meal price" which could be done in the constructor as well...it is a constant algorithm and part of the model.
Here is the model (I have added #Data using lombok which makes all the getters and setters when being compiled)
import lombok.Data;
#Data
public class ProductModel {
private int id;
private String name;
private String mealName;
private int mealPrice;
private int mealQuantity;
private int mealTotal;
//Constructor...i.e. "new ProductModel(field1,field2...)"
public ProductModel(int id, String name, String mealName, int mealPrice, int mealQuantity) {
this.id = id;
this.name = name;
this.mealName = mealName;
this.mealPrice = mealPrice;
this.mealQuantity = mealQuantity;
this.mealTotal = mealPrice * mealQuantity;
}
}
I'm developing an Android Auto like app, where I want to show the call log using recyclerview and cards.
This is working fine, but the call log is showing all the logs. Lets say that if I have received 3 calls from Peter, I don't want to see 3 entries showing this, with one entry enought. This will be like doing something like "most recent contacts" or something like that.
When using the recyclerview and cards, I've created 3 classes to hold the contacts info: The custom adapter, the contact info, and the custom view holder.
This is the ContactInfo class:
public class ContactInfo {
public int id;
public String name;
public String type;
public static final String ID_PREFIX = "ID_";
public static final String NAME_PREFIX = "Name_";
public static final String TYPE_PREFIX = "Type_";
}
Then, in the fragment where I show the call log, this is what I do to display the logs:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.phone_layout, container, false);
...
ContactAdapter contactAdapter = new ContactAdapter(DisplayCallLog());
...
return view;
}
private ArrayList<ContactInfo> DisplayCallLog() {
ArrayList<ContactInfo> data = new ArrayList<ContactInfo>();
int contactID = 0;
String contactNumber = null;
int logType = 0;
String contactName = null;
String contactType = null;
ContactInfo cI;
int resultLimit = 0;
//Check access to Call Log
if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
//Get phone numbers from call log
Cursor cursorCallLog = getActivity().getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
while (cursorCallLog.moveToNext() && resultLimit<6) {
contactNumber = cursorCallLog.getString(cursorCallLog.getColumnIndex(CallLog.Calls.NUMBER));
//We also get the call type: Incoming, Outgoing, missed
logType = cursorCallLog.getInt(cursorCallLog.getColumnIndex(CallLog.Calls.TYPE));
resultLimit++;
//With the phone number we search the ID
String number = Uri.encode(contactNumber);
Cursor cursorContactLookup = getActivity().getContentResolver().query(
Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
number),
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
while (cursorContactLookup.moveToNext()) {
contactID = cursorContactLookup
.getInt(cursorContactLookup
.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
//Get the contact name and phone type
Cursor cursorContactDetails = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.TYPE,
},
ContactsContract.Data.CONTACT_ID + "=?",
new String[] {String.valueOf(contactID)}, null);
while (cursorContactDetails.moveToNext()) {
contactName = cursorContactDetails
.getString(cursorContactDetails
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int type = cursorContactDetails
.getInt(cursorContactDetails
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.TYPE));
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contactType = "Home";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contactType = "Work";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
contactType = "Mobile";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
contactType = "Other";
break;
}
//Call contactinfo class and save into list
cI = new ContactInfo();
cI.id = contactID;
cI.name = contactName;
cI.type = contactType;
//cI.logType = logType;
//HERE: CHECK IF LIST DOES NOT CONTAIN CURRENT CONTACT
if (!data.contains(cI)) {
data.add(cI);
}
}
cursorContactDetails.close();
}
cursorContactLookup.close();
}
cursorCallLog.close();
}
return data;
}
The problem I'm having is that cI shows a string like this:
I/CONTACT_INFO: com.example_infodash.phone.ContactInfo#41c9e198
Where the last numbers are allways diferent even if the contact saved is the same. So it never finds the same contact in the list, even if is duplicated.
So my question is, how could I check if the contact saved is already in the list? I guess that the trouble in this case is because of the use of a custom class like ContactInfo.
The problem I'm having is that cI shows a string like this:
I/CONTACT_INFO: com.example_infodash.phone.ContactInfo#41c9e198
Solution for this problem: Override toString method in ContactInfo
public class ContactInfo {
public int id;
public String name;
public String type;
public static final String ID_PREFIX = "ID_";
public static final String NAME_PREFIX = "Name_";
public static final String TYPE_PREFIX = "Type_";
#Override
public String toString() {
return "{name: " + name + ", type: " + type + "}";
}
}
For ArrayList 'contains' problem, you have to override equals() in ContactInfo. Like this:
public class ContactModel {
public String name;
public String phone;
public ContactModel(String name, String phone) {
this.name = name;
this.phone = phone;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContactModel that = (ContactModel) o;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return phone != null ? phone.equals(that.phone) : that.phone == null;
}
}
If you are in Android Studio you can create it automatically. Go to ContactInfo class, right click in it, choose:
Generate... -> equals() and hashCode()
Your equals() method:
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContactInfo that = (ContactInfo) o;
if (that.name.equals(name) && that.id == id) return true;
else return false;
}
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());
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
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);
}
};
}