Listview Click doesn't fire - android

I have a listview, whick get its data from a SQLite db. I would like to let user change value of field by click on items. But with following code, the click event is not fired. Could some one help on it? Thanks!
public class BDXDeviceActivity extends Activity {
private DeviceListControl deviceListControl;
private ListView listViewDevice;
private DeviceListAdapter2 deviceListAdapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// using a custom layout, otherwise a system default of List
setContentView(R.layout.activity_device_list);
listViewDevice = (ListView) findViewById(R.id.listViewDevice);
deviceListControl = new DeviceListControl(this);
// setListAdapter(new DeviceListAdapter2(this, deviceListControl.getDevices()));
deviceListAdapter2 = new DeviceListAdapter2(this, deviceListControl.getDevices());
listViewDevice.setAdapter(deviceListAdapter2);
listViewDevice.setClickable(true);
listViewDevice.setOnItemClickListener(onItemClickListener);
}
AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), "clicked", Toast.LENGTH_SHORT).show();
DeviceName deviceName = (DeviceName) listViewDevice.getAdapter().getItem(position);
deviceListControl.deleteDevice(deviceName.getId());
// after delete, reread the list adapter and get names list via namechange
deviceListAdapter2 = new DeviceListAdapter2(getBaseContext(), deviceListControl.getDevices());
listViewDevice.setAdapter(deviceListAdapter2);
// Display success information
Toast.makeText(getApplicationContext(), "Deleted!", Toast.LENGTH_LONG).show();
}
};
... layout file
<EditText
android:id="#+id/txtSearchDevice"
android:layout_width="200dp"
android:layout_height="30dp"
android:background="#f7f5b1a3"
android:focusable="false"
/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/btnSearchDevice"
android:textColor="#ff151515"
android:background="#android:drawable/ic_menu_search"
android:focusable="false"/>
</LinearLayout>
<ListView
android:id="#+id/listViewDevice"
android:layout_width="match_parent"
android:layout_height="300dp">
</ListView>

Related

setOnItemClick isnt getting recognized(Android)

I am displaying a Listview of recorded data and when the user clicks on a specific list item, it triggers an intent and brings the user to the profile for that selected user. I worked when i first ran my project but ever since it just will not work. Thank you in advance.
public class CowListView extends ListActivity {
RegisterCowAdapter cowAdapter;
private DataBaseHelper databaseHelper;
public ListView listView;
TextView student_Id;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cow_list_item);
cowAdapter = new RegisterCowAdapter(this);
cowAdapter.open();
updateCowUI();
listView = (ListView) findViewById(android.R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
student_Id = (TextView) view.findViewById(R.id.cowtagnolist);
String studentId = student_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(), CowProfile.class);
Toast.makeText(CowListView.this, "Clicked", Toast.LENGTH_SHORT).show();
objIndent.putExtra("student_Id", Integer.parseInt(studentId));
startActivity(objIndent);
}
});
}
private void updateCowUI() {
Cursor cursor = cowAdapter.getAllCowData();
startManagingCursor(cursor);
String[] from = new String[]{RegisterCowAdapter.COWTAGNO, RegisterCowAdapter.COWDOB};
int[] to = new int[]{R.id.cowtagnolist, R.id.cowdoblist};
SimpleCursorAdapter reminders = new SimpleCursorAdapter(
this,
R.layout.cow_list_item,
cursor,
from,
to
);
this.setListAdapter(reminders);
}
}
private void updateCowUI() {
Cursor cursor =cowAdapter.getAllCowData();
startManagingCursor(cursor);
String[] from = new String[]{RegisterCowAdapter.COWTAGNO, RegisterCowAdapter.COWDOB};
int[] to = new int[]{R.id.cowtagnolist, R.id.cowdoblist};
SimpleCursorAdapter reminders = new SimpleCursorAdapter(
this,
R.layout.cow_list_item,
cursor,
from,
to
);
this.setListAdapter(reminders);
}
}
My XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:longClickable="true">
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
<TextView
android:id="#+id/cowtagnolist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/black"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:descendantFocusability="blocksDescendants"
>
</TextView>
<TextView
android:id="#+id/cowdoblist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:descendantFocusability="blocksDescendants"
android:textColor="#color/black">
</TextView>
</LinearLayout>
Might be one of two things.
You have implemented OnClickListener but you have not set the ListView to listen to that specific class nor have you called any method in your onCreate that will set the ListView's listener to that class.Secondly I think you might need to implement OnItemClickListener and not onCLickListener since thats what is on the ListView, an Item.Im confused though why do you have onClick and then you set the listener inside this method? How will it know in the first place that the view has been clicked if it is not listening from the beginning i.e. in the onCreate or a method called in the onCreate ? Your logic seems abit off

How to add ListView items on button click using adapter

How to take data that was typed in EditText and by clicking "submit" in that window should add it to previous activity listview items?
What I need to do is:
Creating EditText and submit button
Creating listview in same Activity
By clicking submit button it should display it in listview.
I saw this similar question here:add items to listview dynamically android
But i couldn't understand the answer.Somebody please explain how to do this.
You just do the following :
Prepare your xml like this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/addItem"
android:hint="Add a new item to List View" />
<Button
android:id="#+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Add" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText" >
</ListView>
</RelativeLayout>
Activity looks like following :
public class MainActivity extends Activity {
EditText editText;
Button addButton;
ListView listView;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.addItem);
listView = (ListView) findViewById(R.id.listView);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
}
Create String Arraylist and initialize it
ArrayList<String> str1 = new ArrayList<String>();
Add some values on it
str1.add("First Row");
str1.add("Second Row");
str1.add("Third Row");
str1.add("Fourth Row");
str1.add("Fifth Row");
Then set Adapter to ListView
adapter=new ListAdapter(this,str1);
list.setAdapter(adapter);
then add your EditText text into str1 and then called adapter.notifyDataSetChanged(); like
str1.add(edit_message.getText().toString());
adapter.notifyDataSetChanged();
Try to add this code into Button onclick()
Demo Output:
Suppose you have an arraylist
ArrayList<String> dataList = new Arraylist ();
So On clicking of button, you need to add the new data item into your data arraylist.
For this first take the value entered in edittext and store in a string.
String editedValue = yourEditText.getText.toString();
Then we need to add this in our datalist.
Like
dataList.add(editedValue);
And then just call adapter.notifyDataSetChanged()
yourAdapter.notifyDataSetChanged();
It will work.

Android Spinner customization

I need to use spinner as a menu. But problem is that when I click on an item it gets selected and shown at that place a behavior which I want to avoid. Secondly I need that the very first item should always be a heading no matter which of the items has been selected as in the following images:
spinner in normal condition
when user taps the spinner
Now if user taps any of the items heading should not be changed but item should be selected. I have achieved it using ListView but I think I must use proper Android components (if it is really possible).
Thanks in advance.
I have solved the above issue using the following code, but need to use spinner.
layout file
<RelativeLayout
android:id="#+id/header_main"
style="#style/layout_f_w"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:background="#color/heading_color" >
<TextView
android:id="#+id/headingText"
style="#style/layout_wrap"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="MATCH CENTER"
android:textColor="#color/text_color_white"
android:textSize="15sp"
android:textStyle="bold" />
<ImageButton
android:id="#+id/matchcenter_menu"
style="#style/layout_wrap"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/headingText"
android:background="#android:color/transparent"
android:paddingTop="20dp"
android:src="#drawable/drp_down_menu" />
</RelativeLayout>
....
<ListView
android:id="#+id/mainscreen_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#android:color/black"
android:cacheColorHint="#00000000"
android:divider="#android:color/white"
android:dividerHeight="1dp"
android:drawSelectorOnTop="false"
android:listSelector="#android:color/transparent" />
Setting the views.
TextView headingText = (TextView)findViewById(R.id.headingText);
headingText.setTypeface(Utils.getCustomFont(LiveScoreCrowdScreen.this));
headingText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showMatchCenterMenu(v);
}
});
....
matcheCenterMenu = (ImageButton)findViewById(R.id.matchcenter_menu);
matcheCenterMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showMatchCenterMenu(v);
}
});
....
mainscreenMenu = (ListView)findViewById(R.id.mainscreen_menu);
....
public void showMatchCenterMenu(View btn) {
ScreenMenuItemsAdapter adapter = null;
mainscreenMenu = (ListView)findViewById(R.id.mainscreen_menu);
adapter = new ScreenMenuItemsAdapter(LiveScoreCrowdScreen.this, getResources().getStringArray(R.array.livescorecard_menuitems));
mainscreenMenu.setAdapter(adapter);
mainscreenMenu.setVisibility(View.VISIBLE);
mainscreenMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View row, int position, long id) {
CCApplication.isMenuOpened = false;
switch (position) {
case 0:// Refresh
//refresh screen
break;
case 1:// Highlights
//get highlights
break;
case 2:// Preferences
//get preferences
break;
case 3:// current time
// get current time
break;
}
mainscreenMenu.setVisibility(View.GONE);
}
});
}
just a hacking solution not proper one:
Again set the adapter with the spinner when you done all works in side onItemSelectedListener().
i.e
spinner.setAdapter(your_adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
//Do works here
//atlast again load the same adapter
spinner.setAdapter(your_adapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
It will load the same adapter after selecting an item and show you like before.

Android ListView - click handler not working

I'm still having a problem with a ListView click handler. The event is not being fired, so
I do not see the debugging message.
I want to use Activity instead of ListActivity
Here again is my code:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Capture our button from layout
//appState = ((MyApp)getApplicationContext());
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.listr);
//setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.fishicon);
setupDB();
populateList3();
ListView lv = (ListView) findViewById(R.id.list);
// lv.setClickable(true);
lv.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ListRecords.this,"Clicked!", Toast.LENGTH_LONG).show();
}
});
Here is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_height="fill_parent">
<!--Put form controls here-->
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="400dp" />
<Button
android:id="#+id/previousbutton"
android:gravity="center_horizontal"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:text="Previous Menu"/>
</LinearLayout>
I cannot figure out why the click listener is not working.
Thanks
Mike
Don't use inline listeners unless you're sure of how to use them - they can go out of scope and cause a variety of problems.
Try this...
public class MyActivity extends Activity
implements AdapterView.onItemClickListener {
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listr);
ListView lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(this);
// Do whatever else you need to do
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Do whatever
}
}
I would uncomment the #Override. It is there to guarantee that your signature matches the method you're trying to override.
If your method signature is correct, then I suspect the problem lies in populateList3(). Could you post that code as well?
You're not registering the list for the context menu: http://developer.android.com/reference/android/app/Activity.html#registerForContextMenu(android.view.View)

Not able to get the clicked row number in list view of android

I am trying to build a simple sms app for which edit page lists all the saved smses. I gave 2 buttons in my layout for Edit and Delete but when I am clicking on them I am unable to get the rowid (row number from top) to retrieve the sms corresponding to that particular row.. Somebody please help me..my sms adapter is not not extending anything..Here's my class and xml files..
public class SMSEdit extends ListActivity{
private SMSDbAdapter mDbHelper;
//private Button editsmsbtn, deletesmsbtn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editsmslist);
mDbHelper = new SMSDbAdapter(this);
mDbHelper.open();
fillData();
}
public void fillData() {
Cursor smsCursor = mDbHelper.fetchAllNotes();
startManagingCursor(smsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{SMSDbAdapter.KEY_TITLE,
SMSDbAdapter.KEY_BODY,
SMSDbAdapter.KEY_DATE,
SMSDbAdapter.KEY_TIME};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.smseditlistTO,
R.id.smseditlistMessage,
R.id.smseditlistDay,
R.id.smseditlistTime};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter smsadap =
new SimpleCursorAdapter(this, R.layout.smsrow, smsCursor, from, to);
setListAdapter(smsadap);
}
public void myEditClickHandler(View v)
{
//get the row the clicked button is in
LinearLayout vwParentRow = (LinearLayout)v.getParent();
Button btnChild = (Button)vwParentRow.getChildAt(4);
btnChild.setText("I've been clicked!");
ListAdapter pos = getListAdapter();
Intent intent = new Intent();
intent.setClass(SMSEdit.this, SMS.class);
// intent.putExtra(SMSDbAdapter.KEY_ROWID, id);
startActivity(intent);
finish();
}
public void myDeleteClickHandler(View v)
{
//get the row the clicked button is in
LinearLayout vwParentRow = (LinearLayout)v.getParent();
//TextView child = (TextView)vwParentRow.getChildAt(0);
Button btnChild = (Button)vwParentRow.getChildAt(5);
//btnChild.setText(child.getText());
btnChild.setText("I've been clicked!");
int c = Color.CYAN;
vwParentRow.setBackgroundColor(c);
vwParentRow.refreshDrawableState();
}
}
editsmslist.xml -- >>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView android:id="#+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Future SMS Yet" android:textSize="35px"/>
</LinearLayout>
smsrow.xml -- >>
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout android:id="#+id/LinearLayout03" android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="#string/smsdetailseditlist" android:id="#+id/smseditlistTO" android:paddingLeft="5px">
</TextView>
<TextView android:layout_height="wrap_content" android:text="#string/smsdetailseditlist" android:id="#+id/smseditlistMessage" android:paddingLeft="20px" android:maxLines="1" android:layout_width="wrap_content">
</TextView>
</LinearLayout>
<LinearLayout android:id="#+id/LinearLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" android:paddingLeft="5px">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Date: "></TextView><TextView android:text="#string/smsdetailseditlist" android:id="#+id/smseditlistDay" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Time: " android:paddingLeft="5px"> </TextView><TextView android:text="#string/smsdetailseditlist" android:id="#+id/smseditlistTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingRight="10px"></TextView>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/EditSMSButton" android:text="#string/editsms" android:onClick="#string/myEditClickHandler"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/DeleteSMSButton" android:text="#string/deletesms" android:onClick="#string/myDeleteClickHandler"></Button>
</LinearLayout>
</LinearLayout>
</ScrollView>
Also Please suggest if there'a yn better way to implement this or make the layout look better...
You can extend a cursorAdapter like this...
public class exampleAdapter extends CursorAdapter
{
LayoutInflater inflater;
public exampleAdapter (Context context, Cursor c) {
super(context, c);
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
Button btn_del = (Button)view.findViewById(R.id.button1);
btn_del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SMSDbAdapter vb = new SMSDbAdapter(context);
vb.open();
String xyz = cursor.getString(0); //Persumably your ID
vb.Delete(Integer.parseInt(cursor.getString(0)));
Toast.makeText(context, xyz + " Deleted!", Toast.LENGTH_SHORT).show();
vb.close();
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.smsrow, parent, false);
}
}
I had a similar problem with my ListView.
Assume you are filling a ListView dynamically. You have 5 rows (for example). The id of first row is 1 second is 2 and so on.
When you scroll whatever rows are visible to you, the id of the 1st row (that you currently see on screen) will always be 1. You need to control that by using mabye some another class (XYZ).
I simply used ArrayList<XYZ> and that worked.
You can override this method in your SMSAdapter:
public View getView(int position, View convertView, ViewGroup parent)
and then call the get(position) method that returns an ArrayList<XYZ>.
You should use ListView to display your messages.
Store the data retrieved from database in a Array of Strings say s1.
Then
private ArrayList<String> arr_sort = new ArrayList<String>();
And copy whole s1 into arr_sort by using add() method.
While setting adapter
lv.setAdapter(new ArrayAdapter<String>(DataAttach.this,
android.R.layout.simple_list_item_1, arr_sort));
where lv is the ListView refernce.
Then use this method for onClick
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = (String) lv.getItemAtPosition(position);
Toast.makeText(*.this,
"You selected - " + item + " ,Please wait...",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(*.this, *.class);
*.this.startActivity(intent);
}
});
Hope this helps..

Categories

Resources