Contacts adding in Arraylist for ListView error - android

Hi in my project i have to fetch a contacts phone number and the name from the phone.I can get call the phone number and name but when i add it to the ArrayList<HashMap<String, String>>i'm getting the only the last value i don't know why. but when i log it i'm getting all the value can u guys help me where did i go wrong
public class Contacts extends Activity {
Button btnGetContacts;
int z = 1;
String namereview = null;
public String phoneNumber1 = "", phoneNumber, name1, url,urljoingroup;
ListView listSliding;
Button slideHandleButton;
HashMap<String, String> map1;
ListContactAdaptor allContactAdapter;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> resultp = new HashMap<String, String>();
String name;
String message = null;
String sGetContactUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getcontactlist_main);
listSliding = (ListView) findViewById(R.id.GetContacts_Listview);
customer_contact();
}
#SuppressLint("NewApi")
public void customer_contact() {
int timescount = 1, y = 1;
map1 = new HashMap<String, String>();
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.v("Name", name);
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// phoneNumber = phoneNumber.replaceAll("[^\\d.]", "");
map1.put("NAME", phoneNumber);
map1.put("COMMAND", name);
Log.i("name", "name : " + name);
Log.i("count", "count :" + z);
Log.i("pnone", "phone no: " + phoneNumber);
arraylist.add(map1);
Log.i("arraylist", arraylist+"");
}
phones.close();
allContactAdapter = new ListContactAdaptor(XmlActivity.this,
arraylist);
Log.v("ADAPTER", allContactAdapter + "");
// Binds the Adapter to the ListView
listSliding.setAdapter(allContactAdapter);
}
class ListContactAdaptor extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
// public static String CategoryHeading;
public ListContactAdaptor(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
Log.i("data", data + "");
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
// Declare Variables
TextView name, command;
Button joinme;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.getcontactlist_view,
parent, false);
// Get the position from the results
resultp = new HashMap<String, String>();
resultp = data.get(position);
name = (TextView) itemView.findViewById(R.id.name);
command = (TextView) itemView.findViewById(R.id.commamd);
joinme= (Button) itemView.findViewById(R.id.getImage);
name.setText(resultp.get("NAME"));
Log.v("GET NAME", resultp.get("NAME"));
if (resultp.get("COMMAND").equals("")) {
command.setText("No Group");
} else {
command.setText(resultp.get("COMMAND"));
}
Log.v("GET COMMAND", resultp.get("COMMAND"));
return itemView;
}
}
}

Put this in while loop
map1 = new HashMap<String, String>();
like
while (phones.moveToNext())
{
map1 = new HashMap<String, String>();
.
.
}

Related

java.lang.String cannot be cast to java.util.HashMap

When i run the following program:
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outaccountinfo);
ListView lv = (ListView) findViewById(R.id.lvoutinfo);
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
DBOpen open = new DBOpen(Outaccountinfo.this);
SQLiteDatabase db = open.getWritableDatabase();
Cursor cursor = db.query("outaccount", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String str_id = cursor.getString(cursor.getColumnIndex("id"));
String str_money = cursor.getString(cursor.getColumnIndex("outmoney"));
String str_time = cursor.getString(cursor.getColumnIndex("time"));
String str_type = cursor.getString(cursor.getColumnIndex("type"));
String str_mark = cursor.getString(cursor.getColumnIndex("mark"));
map.put("id", str_id);
map.put("outmoney", str_money);
map.put("time", str_time);
map.put("type", str_type);
map.put("mark", str_mark);
AL.add(map);
} while (cursor.moveToNext());
}
}
String[] str = new String[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
str[i] = AL.get(i).get("id").toString() + "|" + " " + "money:" + String.valueOf(AL.get(i).get("outmoney"))
+ " " + "time:" + AL.get(i).get("time").toString() + " " + "type:" + AL.get(i).get("type").toString()
+ " " + "mark:" + AL.get(i).get("mark").toString();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
str);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> map = (HashMap<String, String>) parent.getItemAtPosition(position);
Toast.makeText(Outaccountinfo.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
}
I receive the following error:
java.lang.String cannot be cast to java.util.HashMap
Who can help me to achieve the purpose without changing the purpose of the program?
Thanks!
You are using ArrayAdapter<String> Means that you pass your adapter object of Strings.
Now, when you clicked on your item and asked for parent.getItemAtPosition(position); you get an Object.
If you will go inside this function you can see that the Object that you get is by position and by the type you sent to the Adapter (String).
So, when you try to cast that String to (HashMap<String, String>) you get the exception.
Try to do something like that after you clicked:
HashMap<String, String> map = new HashMap<String, String>(); // Parameter in outside the click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
map.put("someKey", parent.getItemAtPosition(position));
Toast.makeText(Outaccountinfo.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
*****Can you try this code It might be helpful.*****
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.lvoutinfo);
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = openOrCreateDatabase("Account",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS outaccount(id text,outmoney text,time text,type text,mark text);");
db.execSQL("INSERT INTO outaccount VALUES('1','100','10','saving','80');");
Cursor cursor = db.query("outaccount", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String str_id = cursor.getString(cursor.getColumnIndex("id"));
String str_money = cursor.getString(cursor.getColumnIndex("outmoney"));
String str_time = cursor.getString(cursor.getColumnIndex("time"));
String str_type = cursor.getString(cursor.getColumnIndex("type"));
String str_mark = cursor.getString(cursor.getColumnIndex("mark"));
map.put("id", str_id);
map.put("outmoney", str_money);
map.put("time", str_time);
map.put("type", str_type);
map.put("mark", str_mark);
AL.add(map);
} while (cursor.moveToNext());
}
}
String[] str = new String[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
str[i] = AL.get(i).get("id").toString() + "|" + " " + "money:" + String.valueOf(AL.get(i).get("outmoney"))
+ " " + "time:" + AL.get(i).get("time").toString() + " " + "type:" + AL.get(i).get("type").toString()
+ " " + "mark:" + AL.get(i).get("mark").toString();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
str);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> map = (HashMap<String, String>) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
}
}

hashmap working in simpleadapter but not working in custom array adapter

Hashmap for the code below is working for simpleadapter array but not for custom array adapter .Why ? and how do I fix it ? Please Help.Unable to resolve .Tried everything.
I am using lazyLoading class to load images.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> o = (HashMap<String, String>) list.getItemAtPosition(position);
Toast.makeText(CustomizedListView.this, "ID '" + o.get("KEY_TITLE") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
The entire code which is crashing at onclick shown above :
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "https://itunes.apple.com/us/rss/topalbums/limit=20/json";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
LazyAdapter adapter;
HashMap<String, String> map;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL(URL);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray arr3 = e1.getJSONArray("im:image");
JSONObject arr8 = e1.getJSONObject("im:name");
JSONObject arr10 = e1.getJSONObject("im:artist");
JSONObject e12 = arr3.getJSONObject(0);
// creating new HashMap
map = new HashMap<String, String>();
map.put(KEY_THUMB_URL, e12.getString("label"));
map.put(KEY_ARTIST, arr8.getString("label"));
map.put(KEY_TITLE, arr10.getString("label"));
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
// Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> o= (HashMap<String, String>) list.getItemAtPosition(position);
Toast.makeText(CustomizedListView.this, "ID '" + o.get("title") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
This Code below works perfectly:
public class Main extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
LogCAT:
threadid=1: thread exiting with uncaught exception (group=0x40ab0228)
FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap
at com.example.androidhive.CustomizedListView$1.onItemClick(CustomizedListView.java:94)
at android.widget.AdapterView.performItemClick(AdapterView.java:292)
at android.widget.AbsListView.performItemClick(AbsListView.java:1077)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2533)
at android.widget.AbsListView$1.run(AbsListView.java:3198)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data=new ArrayList<HashMap<String, String>>();
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public static HashMap<String, String> song;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(CustomizedListView.KEY_TITLE));
artist.setText(song.get(CustomizedListView.KEY_ARTIST));
duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
return vi;
}
}
In you custom Adapter you are returning position instead of Item
public Object getItem(int position) {
return position;
}
Try use this
public Object getItem(int position) {
return data.get(position);
}
This will fix your problem

The method get(String) is undefined for the type String error in adding the codes to the filter class of adapter in android

For Finding the key items fromt he listview i had not used filter in the adapter, but now by following this link aded the filter but in this line String playerName=songsList.get(i).get("title").toString(); I am getting the error
The method get(String) is undefined for the type String
and also in searchResults.add(songsList.get(i)); as
The method add(HashMap<String,String>) in the type ArrayList<HashMap<String,String>> is not applicable for the arguments (String)
Here's is my entire code
public class Home extends ListActivity {
//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;
//For test data :-)
Calendar d = Calendar.getInstance();
ArrayList<String> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://india.abc.net/ads/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(Home.this, Singlemenuitem.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
startActivity(in);
}
});
and the adapter class is
public class LazyAdapter extends BaseAdapter implements Filterable{
TextView title;
private Activity activity;
// private TextWatcher textWatcher;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
final EditText searchBox=(EditText) findViewById(R.id.search);
ArrayList<HashMap<String, String>> searchResults;
ArrayList<String> songsList;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
private EditText findViewById(int search) {
// TODO Auto-generated method stub
return null;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_home, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView date = (TextView)vi.findViewById(R.id.date); // artist name
TextView content = (TextView)vi.findViewById(R.id.content); // duration
TextView name = (TextView)vi.findViewById(R.id.name);
// duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(Home.KEY_TITLE));
date.setText(song.get(Home.KEY_DATE));
content.setText(song.get(Home.KEY_CONTENT));
name.setText(song.get(Home.KEY_NAME));
imageLoader.DisplayImage(song.get(Home.KEY_URL), thumb_image);
return vi;
}
public void add(String string) {
// TODO Auto-generated method stub
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence data,FilterResults searchResults) {
songsList = (ArrayList<String>) searchResults.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence playerName) {
// TODO Auto-generated method stub
return null;
}
};
String searchString=searchBox.getText().toString();
int textLength=searchString.length();
//clear the initial data set
searchResults.clear();
for(int i=0;i<songsList.size();i++)
{
String playerName=songsList.get(i).get("title").toString();
if(textLength<=playerName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
searchResults.add(songsList.get(i));
}
}
return filter;
}
}
ArrayList<String> songsList;
so songsList is an ArrayList of Strings... if you do songsList.get(i) you'll have a String. The String object has not a "get" method, sou you cannot go further with
songsList.get(i).get("title").toString().
The same thing happens here:
searchResults=new ArrayList<HashMap<String, String>>
so if you call searchResults.add you have to pass a hashmap, not a String.
Please check your type definitions again and it will work.
songsList is a list of strings so you cannot do a get() on its item

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);
}
};
}

Save data from Json object to Database (SQLite)

I am newbie in Android, so I can not estimate how do I save data in database(SQLite) that were got from httprequest through Json.
Here is my code:
final ArrayList<HashMap<String, String>> mylist4 = new ArrayList<HashMap<String, String>>();
try{
JSONObject jObj = new JSONObject(rfiItems);
JSONArray data4 = jObj.getJSONArray("data");
//data4 = json4.getJSONArray("data");
//Toast.makeText(getApplicationContext(), data4.toString(), Toast.LENGTH_LONG).show();
for(int i=0;i<data4.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = data4.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("rfi_data1", "" + e.getString("item_type"));
map.put("rfi_data2", "" + e.getString("change_number"));
map.put("rfi_data3", "" + e.getString("to_vendor"));
map.put("rfi_data4", "" + e.getString("status"));
map.put("rfi_data5", "" + e.getString("title"));
map.put("rfi_data6", "" + e.getString("change_date"));
map.put("rfi_data7", "" + e.getString("responded_date"));
mylist4.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter4 = new SimpleAdapter(this, mylist4 , R.layout.item_list4,
new String[] { "rfi_data1", "rfi_data2","rfi_data3", "rfi_data4","rfi_data5","rfi_data6","rfi_data7"},
new int[] { R.id.rfi_item_type, R.id.rfi_change_no,R.id.rfi_to_vendor,R.id.rfi_status,R.id.rfi_title,R.id.rfi_change_date,R.id.rfi_responded_date });
setListAdapter(adapter4);
Any help will really be appreciated. THANKS
DataBean.java class create for getter and setter method
public class DataBean {
private String item_type = null;
private String change_number = null;
public String getItem_type() {
return item_type;
}
public void setItem_type(String itemType) {
item_type = itemType;
}
public String getChange_number() {
return change_number;
}
public void setChange_number(String changeNumber) {
change_number = changeNumber;
}
}
in your Activity class..set value in object and insert into database
private DatabaseHelper mDbHelper;
DataBean dataBean;
private Cursor mNotesCursor;
private NewsCursorAdapter adapter = null;
mDbHelper = new DatabaseHelper(this);
ArrayList<DataBean> liststck = new ArrayList<DataBean>();
for(int i=0;i<data4.length();i++){
JSONObject e = data4.getJSONObject(i);
dataBean = new DataBean();
dataBean.setChange_number(e.getString("eqid"));
dataBean.setItem_type(e.getString("magnitude"));
liststck.add(dataBean);
}
mDbHelper.deleteRecords();
for (DataBean dataBean : liststck) {
mDbHelper.insertdata(dataBean);
}
mNotesCursor = mDbHelper.retrievedata();
startManagingCursor(mNotesCursor);
adapter.changeCursor(mNotesCursor);
adapter.notifyDataSetChanged();
you must create NCursorAdapter class for dispay result(like custom listview).
here data.xml file is your custom layout. which content two textview.... "key_no" and "key_item" your database table column name...
public class NCursorAdapter extends CursorAdapter {
private Cursor mCursor;
private Context mContext;
private final LayoutInflater mInflater;
public NCursorAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(cursor.getString(cursor.getColumnIndex("key_no")));
TextView date = (TextView) view.findViewById(R.id.date);
date.setText(cursor.getString(cursor.getColumnIndex("key_item")));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
final View view = mInflater.inflate(R.layout.data, parent, false);
return view;
}
}
in your database class insert data and retrieve data
public Long insertdata(DataBean dataBean) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NO, dataBean.getChange_number());
contentValues.put(KEY_ITEM, dataBean.getItem_type());
return sqliteDatabase.insert(DATABASE_TABLE, null, contentValues);
}
public Cursor retrievedata() {
return sqliteDatabase.query(DATABASE_TABLE, new String[] { KEY_ROWID,KEY_NO, KEY_ITEM }, null,null);
}
I hope it is useful for your application.

Categories

Resources