I'm trying to put onListItemClick, but when I start my app nothing happens with onListItemClick. Can anyone help me with this?
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = (new DatabaseHelper(this)).getWritableDatabase();
searchText = (EditText) findViewById(R.id.searchText);
employeeList = (ListView) findViewById(R.id.list);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
search(employeeList);
}
});
}
public void search(View view) {
// || is the concatenation operation in SQLite
cursor = db
.rawQuery(
"SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?",
new String[] { "%" + searchText.getText().toString()
+ "%" });
adapter = new SimpleCursorAdapter(this, R.layout.employee_list_item,
cursor, new String[] { "firstName", "lastName", "title" },
new int[] { R.id.firstName, R.id.lastName, R.id.title });
employeeList.setAdapter(adapter);
}
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this, EmployeeDetails.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
}
There is no error messages and search is working normally.
employeeList = (ListView) findViewById(R.id.list);
add these line below the above line
employeeList = (ListView) findViewById(R.id.list);
employeeList .setOnItemClickListener(this);
Updated:: sample code
public class SampleActivity extends Activity implements OnItemClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mWebView);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
}
}
register an OnItemClickListener() with setOnItemClickListener for your listview like this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
Intent intent = new Intent(this, EmployeeDetails.class);
Cursor cursor = (Cursor) adapter.getItem(pos);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
});
You have to register your listener as listview.setOnItemClickListener(this) in your code.
Try this
listview.setOnItemClickListener(new OnItemClickListener() {
// Your Code Goes Here
});
Related
Based on information from Android: Create spinner programmatically from array. I can select room choices from spinner based on ArrayList. However,it never get inside the process setOnItemSelectedListener.I cannot figure out why does it happen.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_room);
SpaceRoomTable = (TableLayout) findViewById(R.id.tvSpaceRoomTable);
AddroomButton = (Button)findViewById(R.id.btLinkAddRoom);
Backtomenu = (Button) findViewById(R.id.bBackToMenu_DogTrack);
Delete = ContextCompat.getDrawable(this, R.drawable.bin);
dropdown = (Spinner) findViewById(R.id.spinListRoom);
summitDelete = (Button) findViewById(R.id.btDeleteSummit);
AddroomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToEditroom = new Intent (EditRoom.this,AddRoom.class);
startActivity(LinkToEditroom);
}
});
Backtomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToHomeMenu = new Intent(EditRoom.this,HomeMenu.class);
EditRoom.this.startActivity(LinkToHomeMenu);
}
});
showRoom();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
Object Itemselected = adapterView.getItemAtPosition(i);
Toast.makeText(getApplicationContext(),"Inside"+String.valueOf(Itemselected),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
In XML Layout :-
<Spinner
android:id="#+id/dropdown"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
then, in your activity findViewById like this:-
dropdown= (Spinner) findViewById(R.id.dropdown);
then Create an ArrayAdapter using the string array and a default spinner layout :-
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
For OnIemClickListener use like this:-
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner dropdown;
String[] showitemName = {"A","B","C","D","E"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropdown= (Spinner) findViewById(R.id.dropdown);
dropdown.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),"Inside" + parent.getItemAtPosition(position) , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
More information:
You can check in details from these links:-
https://developer.android.com/guide/topics/ui/controls/spinner.html
https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
https://android--code.blogspot.in/2015/08/android-spinner-onitemselected.html
http://www.java2s.com/Code/Android/UI/SpinnerItemSelectedListener.htm
https://android--code.blogspot.in/2015/08/android-spinner-get-selected-item-text.html
For more Information about showroom method
public void showRoom()
{
refroom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
int Length_Record = dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").child("LIST_ROOM_LENGTH").getValue(int.class);
int RunRecord =0;
int printRoom =0;
final String userId = dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class);
for (DataSnapshot zonesnapshot : dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").getChildren())
{
if(printRoom!=Length_Record)
{
zonesnapshot.getValue();
String[] parts = String.valueOf(zonesnapshot.getValue()).split(",");
String part1 = parts[0]; // Room Id
String part2 = parts[1]; // Room Name
String part3 = parts[2]; // TypeRoom
String OnRoom = dataSnapshot.child("CurrentUser").child("Tracking").child("Location").getValue(String.class);
itemsName.add(part2+","+part3); // put to arraylist to prepare a room choice for deletion
showitemName.add(part2+"("+part3+")");
itemOfUser.put(userId+"Room"+printRoom,part2+","+part3); // keep room for each user
inRow(dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class), RunRecord, part2, OnRoom, part3);
}
printRoom++;
}
summitDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storageReference = storage.getInstance().getReferenceFromUrl("gs://********-*****.appspot.com/imagesRoom").child(userId).child(selection);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error Can not delete file",Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
below code will get the selected item text automatically
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
String item = adapterView.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(),"Inside"+item,Toast.LENGTH_SHORT).show();
}
I need an answer on how to create an add button to add listview item, and a delete button to delete last added item. Look at my code. I made an add button but that item exists only for a few seconds and every time I close that page (go to other activity in usermode) it is deleted. Please let me know how can I fix this code and how can I write code for delete button. I need to know how to delete last made item. Thanks for your help in advance. I am looking forward to reply.
public class dodaj extends Activity {
ListView lv;
SearchView sv;
EditText txtinput;
ArrayList<String> arrayList;
String[] recepies={};
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dodaj);
registerClickCallback();
lv=(ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView);
txtinput=(EditText)findViewById(R.id.txtinput);
Button addbutton=(Button)findViewById(R.id.addbutton);
Button buttondel=(Button) findViewById(R.id.buttondel);
arrayList= new ArrayList<>(Arrays.asList(recepies));
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
String newItem=txtinput.getText().toString();
arrayList.add(newItem);
adapter.notifyDataSetChanged();
}
});
buttondel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
int i = arrayList.size()-1;
arrayList.remove(arrayList.get(i));
}
});
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
private void registerClickCallback(){
lv=(ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
TextView textView= (TextView) viewClicked;
if(position==0){
goToMojRecept1();
}else if(position==1){
goToMojRecept2();
}else if(position==2){
goToMojRecept3();
}else if(position==3){
goToMojRecept4();
}else if(position==4) {
goToMojRecept5();
}
}
});
}
private void goToMojRecept5() {
Intent intent = new Intent(this, MojRecept5.class);
startActivity(intent);
}
private void goToMojRecept4() {
Intent intent = new Intent(this, MojRecept4.class);
startActivity(intent);
}
private void goToMojRecept3() {
Intent intent = new Intent(this, MojRecept3.class);
startActivity(intent);
}
private void goToMojRecept2() {
Intent intent = new Intent(this, MojRecept2.class);
startActivity(intent);
}
private void goToMojRecept1() {
Intent intent = new Intent(this, MojRecept1.class);
startActivity(intent);
}
I want to take the value in spinner and user press the ok Button and then start new activity from against the value of spinner. The string array is just like that. and I use two spinners value get and new activity start against the spinners
Spinner s, s1;
Button ok;
Object _globalString, _globalString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner);
s.setAdapter(adapter);
s1 = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner01);
s1.setAdapter(adapter1);
//
// s2=(Spinner)findViewById(R.id.spinner02);
// ArrayAdapter<String> adapter2=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,array_spinner02);
// s2.setAdapter(adapter2);
ok = (Button) findViewById(R.id.btn_ok);
ok.setOnClickListener(this);
s.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
_globalString = parent.getItemAtPosition(position);
}
//#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
s1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
_globalString2 = parent.getItemAtPosition(position);
}
// #Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_ok) {
if (_globalString.equals("Honda") || _globalString2.equals("Civic")) {
startActivity(new Intent(getApplicationContext(), Civic.class));
} else if (_globalString.equals("Toyota") || _globalString2.equals("Gli")) {
startActivity(new Intent(getApplicationContext(), Toyota.class));
}
}
}
}
here is the code this can error generate. Sorry application has been stopped
so i stuck on this code.
use setOnItemSelectedListener instead of setOnItemClickListener:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Spinner s, s1;
Button ok;
Object _globalString, _globalString2;
String[] array_spinner = {"Honda", "Toyota"};
String[] array_spinner01 = {"Civic", "Gli"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner);
s.setAdapter(adapter);
s1 = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner01);
s1.setAdapter(adapter1);
//
// s2=(Spinner)findViewById(R.id.spinner02);
// ArrayAdapter<String> adapter2=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,array_spinner02);
// s2.setAdapter(adapter2);
ok = (Button) findViewById(R.id.btn_ok);
ok.setOnClickListener(this);
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
_globalString = parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
_globalString2 = parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_ok) {
if (_globalString.equals("Honda") || _globalString2.equals("Civic")) {
startActivity(new Intent(getApplicationContext(), Civic.class));
} else if (_globalString.equals("Toyota") || _globalString2.equals("Gli")) {
startActivity(new Intent(getApplicationContext(), Toyota.class));
}
}
}
}
My main activity page for the android app is mainly a listView and on clicking an item in that list I would like a new activity to start. I have created the intent and such as follows in the onCreate method of my MainActivity class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(adapter);
final MainActivity context = this;
lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent myIntent = new Intent(context, SubActivity.class);
myIntent.addFlags(position); //Optional parameters
context.startActivity(myIntent);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My new activity class looks like this:
public class SubActivity extends MainActivity{
ArrayList<String> sublist = new ArrayList<String>();
ArrayAdapter<String> subadapter;
ArrayList<ArrayList<String>> corrReceipts;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
int position = intent.getFlags(); //this gives me the index of the receipt
corrReceipts = super.addedReceipts;
TextView tv = new TextView(this);
tv.setText("Hello");
subadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sublist);
ListView slv = (ListView) findViewById(R.id.sublistview);
slv.setAdapter(subadapter);
sublist.addAll(corrReceipts.get(position));
subadapter.notifyDataSetChanged();
setContentView(slv);
}
}
I have my subActivity class extending MainActivity because it needs to access an array from which to get the information from. When I run this code, and click a list item, nothing happens. Any help as to what I'm doing wrong would be of great help!
All you want is an ItemClickListener not an ItemSelectedListener.
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent myIntent = new Intent(context, SubActivity.class);
myIntent.addFlags(position); //Optional parameters
context.startActivity(myIntent);
}
});
OnItemSelectedListener is used for Spinners, and OnItemClickListener is used for ListViews.
I can't seem to figure out what is wrong with this code. When I click a list item to open the delete dialog, it won't do anything. Though if I restart the activity, all items will be deleted.
public class ContextsList extends Activity {
EditText display;
ListView lv;
public ArrayAdapter<String> adapter;
Button addButton;
String temp_appender;
String appender = "";
List<String> dataset;
String[] splitup;
public String items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contexts_list);
display = (EditText) findViewById(R.id.editText);
lv = (ListView) findViewById(R.id.listView);
addButton = (Button) findViewById(R.id.bAdd);
LoadPreferences();
lv.setAdapter(adapter);
LoadPreferences();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appender = LoadPreferences();
if(display.getText().toString() != null){
temp_appender = display.getText().toString();
String string_to_split = appender + "," + temp_appender;
List<String> items = Arrays.asList(string_to_split.split(","));
adapter = new ArrayAdapter<String>
(getApplicationContext(), android.R.layout.simple_list_item_1, items);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", string_to_split);
LoadPreferences();
}
display.setText("");
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
deleteItem(arg1);
}
});
}
protected void deleteItem(final View arg1)
{
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Delete");
dialogBuilder.setMessage("Do you want to delete \"" +
((TextView) arg1).getText() + "\"?");
dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
items = LoadPreferences();
try {
adapter.remove(((TextView) arg1).getText().toString());
adapter.notifyDataSetChanged();
SavePreferences("LISTS", items);
} catch (Exception ignored) {
}
SavePreferences("LISTS", items);
}
});
dialogBuilder.setNeutralButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog deleteDialog = dialogBuilder.create();
deleteDialog.show();
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected String LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "");
dataset = Arrays.asList(dataSet.split(","));
splitup = dataSet.split(",");
List<String> items = Arrays.asList(dataSet.split(","));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
return dataSet;
}
}
I've been at this for hours, so if anyone could help spot this error I'd really appreciate it. Just let me know if you need any more input from me.
Here is the answer
The reason is following: according to API the list is immutable in terms of adding/deletion. But on add operation you create a new adapter, so it runs well. But when you try to delete an object from "immutable" list, you get an error.
And please, never ever ever use empty catch block without clear explanation why it is empty. Just put ignored.printStackTrace(); is will save you a tonn of time!
Hai in my project i am doing list deletion. I am using like this. when the user click the list. please get the position of the list and pass through dialog function arg.
lv.remove(positiontoDelete);