I created a Custom ListView using BaseAdapter now I want to populate this Listview with Contact Name and Number from Phone book..I am trying this..
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Rabtaye extends Activity {
ListView msgList;
ArrayList<MessageDetails> details;
AdapterView.AdapterContextMenuInfo info;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
msgList = (ListView) findViewById(R.id.MessageList);
details = new ArrayList<MessageDetails>();
MessageDetails Detail = new MessageDetails();
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
startManagingCursor(cursor);
String info[] = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID };
for(String a:info){
Detail.setName(a);
}
Detail.setNumber("0313");
details.add(Detail);
// int to[] = { R.id.name, R.id.number };
// ListAdapter cursada = new SimpleCursorAdapter(this,
// android.R.layout.simple_expandable_list_item_2, cursor, info,
// to);
msgList.setAdapter(new CustomAdapter(details, this));
msgList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView s = (TextView) arg1.findViewById(R.id.name);
String abc = s.getText().toString();
Toast.makeText(Rabtaye.this, abc, Toast.LENGTH_LONG).show();
}
});
}
}
I used different ways, but I am not able to populate ListView with Contact Name or Number. In this code I have to statically add name and number...I am quite confuse here..little help would be greatly appreciated. Thanks in Advance. I am newbie so please go easy on me..:)
Hmmm. You're on the right track, but I think you're wandering a bit.
A ListView is a view object, not a BaseAdapter. As far as I can tell from your code, you don't need a custom adapter for your ListView.
What you should do is bind a regular CursorAdapter to your ListView, load the Contacts data you want from the Contacts Provider using a CursorLoader, then move the resulting Cursor to the CursorAdapter.
You can find the instructions for doing this in this Android training class:
Loading Data in the Background.
What do you want in your custom ListView that you can't get from ListView itself?
If you're putting more than just a single list of items into a ListView (it looks like you're doing name, number, etc.) you have to create your own custom adapter. Extend the BaseAdapter class either in your activity, or in a new class. Then you'll have to override the getView() method. This is what is called every time a new item gets inflated.
You pass your ArrayList into the BaseAdapter when you create it. The getView() method of the adapter is where you code your logic to take the data and present it as a list item. You'll have to define a new XML file as a layout for each list item that contains your TextViews and whatnot for your different children in each list item, and that's what you populate with your data.
There are a bunch of examples all over if you search for "baseadapter". Here's one that gives a pretty good intro.
Related
I am doing an application in android. The application saves a quote or an expression in a textfield. The user has the opportunity to change this text. But I wanted that when the quote is appeared in the TextView, it is not appeared at all. I wanted only the first 5 characters of the quote to be appeared. I try to do this using the substring, but when I open the TextView nothing appears. The TextView is empty. What can I do?
Can anyone help me , please.
Thanks in advance.
This is the line where I use substring:
ListAdapter adapter = new SimpleAdapter( Quote.this,quoteList, R.layout.quote_entry, new String[] { "quoteId", "textQuote".substring(0, 4)}, new int[] {R.id.quoteId, R.id.textQuote});
And here is the entire class
package com.example.prova1;
/**This class is the page of quotes*/
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import com.example.prova1.Database;
import com.example.prova1.EditQuote;
import com.example.prova1.AddQuote;
import com.example.prova1.R;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter;
import android.widget.ListView;
public class Quote extends ListActivity {
Intent intent;
TextView quoteId;
Database quotedatabase = new Database(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quote_main);//define that the interface used is quote_main
//Store data from database in an array list
ArrayList<HashMap<String, String>> quoteList = quotedatabase.getAllItems();
//Check if there are quotes to display
if(quoteList.size()!=0) {
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
quoteId = (TextView) view.findViewById(R.id.quoteId);
String itemIdValue = quoteId.getText().toString();
Intent theIndent = new Intent(getApplication(),ShowQuote.class);
theIndent.putExtra("quoteId", itemIdValue);
finish();
startActivity(theIndent);
}
});
// Here we use ListAdapter as a bridge between ListView and the data of ListView
ListAdapter adapter = new SimpleAdapter(
Quote.this,quoteList,
R.layout.quote_entry,
new String[] {
"quoteId",
"textQuote".substring(0, 4)
},
new int[] {
R.id.quoteId,
R.id.textQuote}
);
setListAdapter(adapter);
}
}
}
I don't have the SDK installed at the moment to test your code, but I do have a couple suggestions.
First: Try the code without the substring, and see if that works.
Second: If that works, then move the substring operation to the line before and pass in the result to the SimpleAdapter.
I say this because I have the feeling that the substring is not actually your problem. And this is just a good way to test that.
I'd also check your layout "R.layout.quote_entry" and make sure there isn't anything weird going on with that. Such as you having "R.id.textQuote" actually being 'gone' and another TextView being visibly shown, etc. I had this problem once. I had two EditText fields, and only one of them was being shown, so the Activity looked right, but wasn't behaving properly.
I am trying to understand where to save the selected list view items from this code. With a dialog box you have an "ok/cancel" button option, is this possible with lists? Ideally I will be storing data from four different lists into a database on submit. In the below picture I would like to save the first three items into a database, or even an array just to start.
package com.example.lifebyfourlists;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity{
String [] seven = {
"Dark Leafy Greens" ,
"Nuts",
"Carrots",
"Green Tea",
"Whole Grains",
"Fruits"};
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, seven));
}
public void onListItemClick(ListView parent, View v, int position, long id){
Toast.makeText(this, "You have selected " + seven[position], Toast.LENGTH_SHORT).show();
}
}
I am trying to understand where to save the selected list view items from this code. With a dialog box you have an "ok/cancel" button option, is this possible with lists?
You can use getCheckedItemIds() or you can write a custom Adapter to track the selected rows.
I've setup a footer to my list view, next I'm setting up an onclicklistener to it that will play a sound and then go to my next activity but having trouble getting the onclicklistener working for the footer. I've successful done it to other activites but this one is giving me trouble I'm hoping to post the code and someone can explain what I'm doing wrong. I've tried every fix I've found online but nothing seems to work.
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class editpage extends ListActivity {
//editCount still unused at time but will grab data inputted into edittext fields
int editCount;
private dbadapter mydbhelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_list);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
private void fillData() {
Cursor e = mydbhelper.getUserWord();
startManagingCursor(e);
// Create an array to specify the fields we want to display in the list
String[] from = new String[] {dbadapter.KEY_USERWORD,};
// an array of the views that we want to bind those fields to
int[] to = new int[] {R.id.textType,};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter editadapter =
new SimpleCursorAdapter(this, R.layout.edit_row, e, from, to);
ListView list = getListView();
View footer = getLayoutInflater().inflate(R.layout.footer_layout, list, false);
list.addFooterView(footer);
setListAdapter(editadapter);
//still not used, need to get onclicklistener working since this will be used to send data to next activity
editCount = e.getCount();
}
public void onClick(View footer){
final MediaPlayer editClickSound = MediaPlayer.create(this, R.raw.button50);
editClickSound.start();
};
//This should not be needed since clicking on items in list view will not have a function but read someone to put my footer onclick in here but didn't work for me
#Override
protected void onListItemClick(ListView list, View v, int position, long id)
{
super.onListItemClick(list, v, position, id);
//final Intent intent = new Intent(this, title.class);
//startActivityForResult(intent, position);
}
TY in advance, btw if I take out the onclicklistener my page displays with the footer but can't move forward with program without getting this step fixed
if you're defining the button in XML, add android:onClick="onClick" to it
I want to make a dynamic list view which gets the user credentials when I login for the first time and displays it in a list the next time I start the app. I know how to send the username from one intent to another. i haven't focused on the SQLite part yet, will do that later. I'm facing problems in creating the dynamic list view.
Found one very useful thread - Dynamically add elements to a listView Android
he used a button on the screen and called the method onClick to populate the list. Can i do it without the button? I want it to automatically happen once i am able to login.
how can i use the statements in my code?
listItems.add(value);
adapter.notifyDataSetChanged();
here value is the username i am getting from some other intent.
please help. thanks!
For this Just use the example given below:
For Instance you are Adding Some Strings into your List
So Create a ListArray like this
ArrayList<String> listItems = new ArrayList<String>();
now whenever you want to add certain string into list just do this thing
EditText editText = (EditText) findViewById(R.id.edit);
listItems.add("my string"); OR
listItems.add(editText.getText.toString()); //incase if you are getting string value from editText and adding it into the list
Use this Xml inside your linear layout in main.xml
<EditText android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now when you have added one item dynamically then call this
adapter.notifyDataSetChanged();
The above will update your list and display the upadted list.
For more info about this see the following links:
http://www.androidpeople.com/android-custom-listview-tutorial-part-1
http://www.androidpeople.com/android-custom-listview-tutorial-part-2
http://www.androidpeople.com/android-custom-dynamic-listview-%E2%80%93part3
In these tutorials you can replace String[] with ArrayList as given at the top of the answer ook and when you want to add any item just simply use the second code snippet.
Thanks
sHaH
The best way to do this will be to use ArrayAdapter. When modifying the adapter it automatically refresh itself so you don't have to call notifyDataSetChanged.
You can try out this code to add elements dynamically to list view.
You can do it with out button click also.
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
//step2 : create all the variables.
EditText et;
Button b;
ListView lv;
ArrayList<string> al;
ArrayAdapter<string> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//step3 : intitalize all the variables.
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
lv = (ListView) findViewById(R.id.listView1);
al = new ArrayList<string>();//initialize array list
aa = new ArrayAdapter<string>(this,
android.R.layout.simple_list_item_1,
al);//step4 : establish communication bw arraylist and adapter
//step5 : establish communication bw adapter and dest (listview)
lv.setAdapter(aa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent,
View v, int arg2,
long arg3) {
String item = al.get(arg2);
Toast.makeText(getApplicationContext(), item, 0).show();
}
});
//step6 : button click logic
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//step i: take text from et and add to arraylist
String item = et.getText().toString();
al.add(0, item);
//step ii: notify to adapter
aa.notifyDataSetChanged();
//step iii: clr edit text
et.setText("");
}
});
}
}
For complete code check this list view example
I'm looking to be able to open up a new view or activity when I click on an item in my ListView.
Currently I have a list of restaurants, and when i click on a particular restaurant I want it to open up another screen that will show its address, google map etc.
What I need help with is knowing how to set click events on the items in the list.
At the moment I dont have a database of the items, they're just Strings.
Can someone help me with getting me to this stage?
Thanks alot.
package com.example.androidrestaurant;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.ListActivity;
public class Dundrum extends ListActivity {
TextView selection;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, DUNDRUM));
getListView().setTextFilterEnabled(true);
}
static final String[] DUNDRUM = new String[] {
"Ananda",
"Brambles Cafe", "Brannigans", "Buona Sera",
"Cafe Mao", "Cafe Mimo",
"Dante", "Douglas & Kaldi Terrace Cafe",
"Eddie Rockets",
"Frango's World Cuisine",
"Nando's",
"Overends Restaurant # Airfield House",
"Pizza Hut",
"Roly Saul",
"Siam Thai","Smokey Joes","Sohag Tandoori",
"TGI Friday","The Rockfield Lounge", "Winters Bar" };
};
You need to do like this :
// Store your listview into local variable
ListView lv = getListView();
lv.setTextFilterEnabled(true);
// Bind onclick event handler
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Put in your code here, what you wanted trigger :)
}
});
If you are using the ListView in a ListActivity, override onListItemClick(). Otherwise, use setOnItemClickListener() with the ListView. In either case, you are given a position that is the index into your array.
See here for an sample project.