I'm having problems with setting multiple choice selection in ListView. My ListView has contacts' names which are retrieved from the android phone.
I've followed examples on setting multiple choice but it didn't work out.
I've tried typing
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contacts_list, c, columns, views);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
this.setListAdapter(adapter);
but I don't see the checkbox in the ListView.
And I've replaced R.layout.contacts_list with android.R.layout.simple_list_item_multiple_choice and it showed checkboxes but no names from the android phone's contacts.
Here are my codes:
contacts_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/light_goldenrod"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stackFromBottom="false"
android:transcriptMode="normal"
android:choiceMode="multipleChoice" >
</ListView>
<TextView
android:textColor="#color/dark_purple"
android:id="#+id/contactName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
ContactsList.java
public class ContactsList extends ListActivity
{
final Context context = this;
Cursor cursor;
String[] buddiesList =
{"Kanak Priya",
"Joanne Liew",
"Michelle Lam",
"Teo Kin Hua",
"Melissa Haiting",
"David Yeo",
"Natasha Akhbar",
"Gillian Gan",
"Sonia",
"Ms Long",
"Joan Tang",
"Stephanie",
"Nur Ashiqin"
};
BuddyDBAdapter buddyDB = new BuddyDBAdapter(this);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
ListView list = getListView();
setListAdapter(new ArrayAdapter<String> (this, R.layout.contacts_list, R.id.contactName, buddiesList));
Uri allContacts = Uri.parse("content://contacts/people");
Cursor c = managedQuery(allContacts, null, null, null, null);
String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int[] views = new int[] {R.id.contactName};
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contacts_list, c, columns, views);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
this.setListAdapter(adapter);
/*if(cursor.getCount()<0)
{
Intent displayIntent = new Intent(Intent.ACTION_VIEW);
displayIntent.setData(Uri.parse("content://contacts/people"));
startActivity(displayIntent);
displayIntent = new Intent(Intent.ACTION_VIEW);
//displayIntent.setData(Uri.parse("content://contacts/people/"+id));
startActivity(displayIntent);
}
else
{
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("ALERT!");
alertDialog.setMessage("NO Name is Found! D:");
alertDialog.setIcon(R.drawable.warning);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent backIntent = new Intent(context, ContactsList.class);
startActivity(backIntent);
}
});
alertDialog.show();
}*/
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
buddyDB.open();
long name_id;
super.onListItemClick(l, v, position, id);
Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
TextView contactName = (TextView) v.findViewById(R.id.contactName);
String NameValue = contactName.getText().toString();
name_id = buddyDB.insertNames(NameValue);
Toast.makeText(getBaseContext(),
"Selected: " + buddiesList[position], Toast.LENGTH_SHORT).show();
buddyDB.close();
Oh by the way, the
String[] buddiesList =
{"Kanak Priya",
"Joanne Liew",
"Michelle Lam",
"Teo Kin Hua",
"Melissa Haiting",
"David Yeo",
"Natasha Akhbar",
"Gillian Gan",
"Sonia",
"Ms Long",
"Joan Tang",
"Stephanie",
"Nur Ashiqin"
};
is for my Toast message.
I really need help with this. Any help will be appreciated. Examples will be greatly appreciated too.
Thanks
You may have two choices:
1 - Use default layout from Android resources (simple_list_item_multiple_choice)
you may replace this code:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.contacts_list, c, columns, views);
to:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, c, columns, new int {android.R.id.text1});
2 - Create your new row layout contains your defined checkbox and handle it by your own.
contact_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/light_goldenrod"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stackFromBottom="false"
android:transcriptMode="normal"
android:choiceMode="multipleChoice" >
</ListView>
</LinearLayout>
contact_entry.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#color/dark_purple"
android:id="#+id/contactName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/contactCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:checked="false" />
</LinearLayout>
Add custom cursor adapter like this:
public class YourCursorAdapter extends CursorAdapter {
private Context mContext;
private Cursor mCurser;
public YourCursorAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, ContentResolver co) {
super(context, c);
mCurser = c;
mContext = context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.contact_entry, parent, false);
bindView(v, mContext, cursor);
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView contactName= (TextView)view.findViewById(R.id.contactName);
contactName.setText(cursor.getString((mCurser
.getColumnIndexOrThrow(Contacts.Phones.DISPLAY_NAME))));
CheckBox contactCheckbox = (TextView)view.findViewById(R.id.contactCheckbox);
contactCheckbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Checkbox checkBox = (Checkbox) v.findViewById(R.id.contactCheckbox)
if (checkBox.isChecked())
checkBox.setChecked(false);
else
checkBox.setChecked(true);
}
});
}
in your ListActivity:
YourCursorAdapter adapter = new YourCursorAdapter(this,
null, c, null, null,null);
this.setListAdapter(adapter);
Related
The codes below helped me to retrieve all contacts into a listview in
an activity, however i wanted to get the selected row of contact from
the user to pass it into the intent but im not sure how to do it.
Example: User selected Suzanne's contact, i want to be able to save "Suzanne" name and number in a string and pass to a
intent
public class SendWhoosh_SelectContact extends ListActivity
{
private static final String TAG = "SendWhoosh";
ListView listView;
Cursor cursor;
#Override
public long getSelectedItemId()
{
// TODO Auto-generated method stub
return super.getSelectedItemId();
}
#Override
public int getSelectedItemPosition()
{
// TODO Auto-generated method stub
return super.getSelectedItemPosition();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_whoosh_select_contact);
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1, android.R.id.text2};
SimpleCursorAdapter listadapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to);
setListAdapter(listadapter);
listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String phone = ContactsContract.CommonDataKinds.Phone.NUMBER;
Log.d(TAG, "SendWhoosh: phone " + phone);
Intent intent = new Intent(SendWhoosh_SelectContact.this, EnterWhooshAmount.class);;
intent.putExtra("Name", name);
intent.putExtra("Number", phone);
startActivity(intent);
}
});
}
----------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/whooshbg"
android:id="#+id/activitywhoosh_screenarea"
tools:context=".SendWhoosh_SelectContact">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/li1">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/back"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:layout_marginTop="15dp"
android:textColor="#color/white"
android:text="Whoosh to "/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</RelativeLayout>
Set your onClickListener() and launch your intent as below;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
launchAnotherActivity(position);
}
});
}
private void launchAnotherActivity(int position) {
Intent intent = new Intent(this, EnterWhooshAmount.class);
intent.putExtra("The_Position", position);
startActivity(intent);
}
When you get to EnterWhooshAmount class, you will get the intent and retrieve the position clicked and with this position, you can retrieve the name etc. You can get the intent in EnterWhooshAmount class as below;
Intent i = getIntent();
if (i != null){
int position = i.getIntExtra("The_Position", -1);
}
So, position is the integer you are looking for, hence, you can retrieve name etc with in this position where you saved it
listitem onclick listener changes this code get click item name and number.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = ((TwoLineListItem) view).getText1().getText().toString();
String number = ((TwoLineListItem) view).getText2().getText().toString();
Log.d(TAG, "SendWhoosh: phone " + name);
Intent intent = new Intent(SendWhoosh_SelectContact.this, EnterWhooshAmount.class);;
intent.putExtra("Name", name);
intent.putExtra("Number", number);
startActivity(intent);
}
});
Basically I have listview in my fragment layout. And another layout called item_todo.xml which contains my button.
The onClick() wasn't working while clicking the delete_task button in my layout.
It would be great if you could help me out !
Here is my Class ToDoFragment
public class ToDoFragment extends Fragment {
private static final String TAG = "MainActivity";
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
Button myButton;
FloatingActionButton btnadd;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mHelper = new TaskDbHelper(getActivity());
mTaskListView = (ListView) view.findViewById(R.id.list_todo);
//Floating action button
btnadd = (FloatingActionButton) view.findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText taskEditText = new EditText(getActivity());
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
});
updateUI();
return view;
}
#Override
public void onActivityCreated(Bundle saved){
super.onActivityCreated(saved);
final LayoutInflater factory = getActivity().getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.item_todo, null);
myButton = (Button) textEntryView.findViewById(R.id.task_delete);
myButton.setOnClickListener(new View.OnClickListener() {
// OnClick() Not Working !!
#Override
public void onClick(View view) {
deleteTask(view);
}
});
}
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE,
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{task});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(getActivity(),
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}}
Fragment_two XML
<ListView
android:id="#+id/list_todo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:id="#+id/btnadd"
android:layout_height="50dp"
app:fabSize="normal"
android:clickable="true"
android:src="#drawable/red"
android:scaleType="center"
/>
</LinearLayout>
</RelativeLayout>
item_todo XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical">
<TextView
android:id="#+id/task_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Hello"
android:textSize="20sp" />
<Button
android:id="#+id/task_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="Done" />
</RelativeLayout>
You inflate a new View in your onActivityCreated But you never used that view !!! myButton refer to a button which its view has not been used !
Edit :
There are lots of ways you can reach your goal:
Interfaces
You can initialize an interface and pass it to fragment, so whenever something happen in your activity (button click for example), you will understand
BroadcastReceivers
You can register local broadcast receivers in your fragment and when user click on the button, you send that broadcast, so fragment will understand
i suggest the second one and using EVENTBUS library
I have search a lot of questions here and already implemented every answer i get from here, but no one has solved this problem. I have 2 buttons in a row of my custom listview and i want to perform on click on them. Here is my custom adapter and xml code.
EDIT
CartAadpter.java
public class CartAdapter extends ArrayAdapter<CartItemListData> {
Context context;
int layoutResourceId;
ArrayList<CartItemListData> data = new ArrayList<CartItemListData>();
LayoutInflater mInflater;
CartItemListData listData;
CartDatabaseHelper db;
int i;
public CartAdapter(Context context, ArrayList<CartItemListData> data) {
super(context, R.layout.cart_listitems, data);
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.data = data;
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.cart_listitems, parent,
false);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.cart_item_id);
holder.text1 = (TextView) convertView
.findViewById(R.id.cart_item_boxes);
holder.edit = (Button) convertView.findViewById(R.id.editdata);
holder.delete = (Button) convertView.findViewById(R.id.deletedata);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
listData = data.get(position);
// Button's Tag
holder.edit.setTag(data.get(position).getId());
holder.delete.setTag(data.get(position).getId());
// SetText to Textview
holder.text.setText(data.get(position).getTilesId());
holder.text1.setText(String.valueOf(listData.getNumberOfBox()));
Log.e("Database Data ID: ", listData.getId() + " " + position);
holder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
i = data.get(position).getId();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Edit Box");
builder.setMessage("Please Enter Number of Box.");
final EditText editText = new EditText(context);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
editText.setLayoutParams(lp);
builder.setView(editText);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
if (editText.getText().toString() == null
&& editText.getText().length() == 0) {
Toast.makeText(
context,
"To delete Data use \"delete button\"",
Toast.LENGTH_LONG).show();
} else {
int data = Integer.parseInt(editText
.getText().toString());
if (data <= 0) {
Toast.makeText(
context,
"To delete Item Please use delete button",
Toast.LENGTH_LONG).show();
} else {
Log.e("Edited", "Yes");
CartDatabaseHelper cartDatabaseHelper = new CartDatabaseHelper(
context);
cartDatabaseHelper
.updateCart(new CartItemListData(
i, holder.text
.getText()
.toString(),
data));
CartAdapter.this.data.clear();
CartAdapter.this.data.add(listData);
notifyDataSetChanged();
}
}
}
});
builder.create().show();
}
});
holder.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Deleted", "Yes");
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete!!");
builder.setMessage("Deleting Item from List!!!");
builder.setIcon(R.drawable.ic_alerts_and_states_warning);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
db = new CartDatabaseHelper(context);
db.delete_cartitem(data.get(position).getId());
data.remove(position);
notifyDataSetChanged();
}
});
builder.setNegativeButton("No", null);
builder.create().show();
}
});
return convertView;
}
static class ViewHolder {
TextView text, text1;
Button edit, delete;
}
}
cartlist_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/cart_item_id"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_marginLeft="2dp"
android:layout_weight="2"
android:background="#drawable/cart_list_text_background"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="22sp" />
<TextView
android:id="#+id/cart_item_boxes"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/cart_list_text_background"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="22sp" />
<Button
android:id="#+id/editdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/edit"
android:focusable="false" // Here I have checked it with true value too
android:focusableInTouchMode="false" />
<Button
android:id="#+id/deletedata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/ic_delete"
android:focusable="false"
android:focusableInTouchMode="false" />
MylistView:
<ListView
android:id="#+id/lvExp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:cacheColorHint="#FFFFFF"
android:childDivider="#f8dfdb"
android:choiceMode="singleChoice"
android:clipChildren="true"
android:clipToPadding="true"
android:divider="#ff2200"
android:dividerHeight="3dp"
android:drawSelectorOnTop="true"
android:fastScrollEnabled="true"
android:focusable="false"
android:footerDividersEnabled="true"
android:hapticFeedbackEnabled="true"
android:headerDividersEnabled="true"
android:scrollingCache="true"
android:soundEffectsEnabled="true"
android:textFilterEnabled="false"
android:transcriptMode="normal"
android:translationX="10dp" />
Can anyone tell me where did i make mistake? My work is about to finish and app is almost ready but i am stuck in this problem. I will be thankfull to any type of suggestion or help.
I am not sure,but Try holder.edit.setOnClickListener(new View.OnClickListener())
instead of holder.edit.setOnClickListener(new OnClickListener()).
try this
add this cartlist_row.xml in parent Linearlayout
android:clickable="false"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
for Button add this
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
and AlertDialog.Builder builder is not working , you never used show().. Please Cross check .. Use
AlertDialog alert = builder.create(); alert.show();
I test my application on debug and crash on this line:
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
with this error:
System services not available to Activities before onCreate()
I solved this error whit this code (change this with context):
listAdapter = new ArrayAdapter(promptsView.getContext(), R.layout.cd_edittext_for_listview, planetList);
And change on XML file "EditView" with "EditText"!*
I have this layout for the items "editText_for_listview.xml":
<EditView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowEditView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp">
</EditView>
And my main layout "items_listview.xml"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mylistview"
android:layout_gravity="center" />
</LinearLayout>
The code is this:
public void _ShowItems(String sTitle,android.content.Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(sTitle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
final View promptsView = inflater.inflate(R.layout.items_listview, null);
ListView mainListView ;
ArrayAdapter<String> listAdapter ;
mainListView = (ListView) promptsView.findViewById( R.id.editText_for_listview );
String[] planets = new String[] { "Test1", "Test2", "Test3" };
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
builder.setView(promptsView)
.setPositiveButton("One", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Two", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
Can you help me?
Where I wrong?
Thanks
Obviously you are trying to use the Activity Context prior to the Activity's onCreate() method being called. Try moving your call to _ShowItems() to onResume() method.
Could you show up more code of your activity. You could just be calling the method in a spot where the context isn't initialized but something else could be going on that will be revealed once we have a better look at the activity.
I would have made this a comment but I don't have the reputation to do so.
I am trying to implement a highscores activity, and i`m trying to use a ListView.
But there is a problem: list view shows me only an element what was added by .addHeaderView() method, but the adapter elements seem to be invisible.
Even though adapter.getCount() returns correct number of elements, they are somehow invisible.
Please help, I'm pulling my hair out here.
My Activity layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:keepScreenOn="true" >
<ListView
android:id="#+id/scores_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
My ListView row layout:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/name"
android:layout_width="match_parent"
android:gravity="center_vertical"
android:paddingLeft="5dip"
/>
My activity code:
public class ScoresActivity extends Activity {
private ScoresAdapter adapter;
private ListView scoresList;
private Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
scoresList = (ListView)findViewById(R.id.scores_layout);
SQLiteDatabase dataBase = ((MyApplication) getApplication()).getDataBase();
cursor = dataBase.query(ScoresDBHelper.SCORES_TABLE_NAME,null,null,null,null,null,null);
adapter = new ScoresAdapter(this, cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
scoresList.addHeaderView(getLayoutInflater().inflate(R.layout.scores_list_row, null));
scoresList.setAdapter(adapter);
Toast.makeText(this, String.valueOf(adapter.getCount()), Toast.LENGTH_LONG).show();
}
}
My adapter code:
class ScoresAdapter extends CursorAdapter{
LayoutInflater inflater;
public ScoresAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textViewName = (TextView) view.findViewById(R.id.name);
textViewName.setText(cursor.getString(cursor.getColumnIndex("name")));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.scores_list_row, null);
}
}
I was calling
cursor.close();
before onDestroy() method.
You need to add
android:layout_height ="wrap_content"
in your row layout's TextView.