I am performing listview's selected item id. but i'm unable to get item id. please help me..
public class ViewAllActivity extends AppCompatActivity {
ListView lv;
DbHelper dbh;
String selected;
final String ar[]={"Delete","Update"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
lv = (ListView) findViewById(R.id.listView);
dbh = new DbHelper(ViewAllActivity.this);
final ArrayList<DoctorPojo> arraylist = dbh.getData();
ArrayAdapter<DoctorPojo> adapter=new ArrayAdapter<DoctorPojo>(ViewAllActivity.this,android.R.layout.simple_list_item_1,arraylist);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
AlertDialog.Builder alert=new AlertDialog.Builder(ViewAllActivity.this);
alert.setTitle("Which Action You Want to Perform...!!!");
alert.setItems(ar, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selected=ar[which];
if(selected == "Delete") {
//Toast.makeText(ViewAllActivity.this, " Delete is pressed", Toast.LENGTH_LONG).show();
Intent i=new Intent(ViewAllActivity.this,DeleteActivity.class);
i.putExtra("id", arraylist.get((int) lv.getSelectedItemPosition()).toString());
startActivity(i);
}
else
{
Toast.makeText(ViewAllActivity.this, " Update is pressed", Toast.LENGTH_LONG).show();
}
}
});
alert.create().show();
return false;
}
});
}
}
here i cant get my listview's id. i want it because i want to pass that id because i want to delete that perticular record.and also want to perform update operation. so for that i want id os that listview's selected item. so please help me.
Try this:
DoctorPojo mPojo=arrayList.get(position);
i.putExtra("id",mPojo.getId());
Related
I'm trying to delete the selected item in listview through Context menu.
here is my code.
public class MainActivity extends AppCompatActivity
{
EditText editText;
Button add;
ListView listView;
final DBFunctions db=new DBFunctions(MainActivity.this);
ArrayAdapter<String> adapter;
String[] values;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= (EditText) findViewById(R.id.editText);
add= (Button) findViewById(R.id.button);
listView= (ListView) findViewById(R.id.listView);
values=db.getAlldata();
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,values);
listView.setAdapter(adapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editText.getText().toString();
if (!name.equals("")) {
editText.setText("");
long check = db.insertData(name);
if (check < 0) {
Toast.makeText(MainActivity.this, "Error in insert query", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, name + " inserted", Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
} else {
editText.setError("this field is empty");
}
}
});
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
int position=listView.getSelectedItemPosition();
String data=values[position]; //error line
Log.e("Value ", data );
Log.e("Position ", position+"" );
switch (item.getItemId())
{
case R.id.delete_name:
long check=db.deleteData(data);
if(check<0)
{
Toast.makeText(MainActivity.this,"Error in query",Toast.LENGTH_SHORT).show();
}
else
{
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,data+" deleted",Toast.LENGTH_SHORT).show();
}
return true;
default :
return super.onContextItemSelected(item);
}
}
}
when i run above code i get following error:
java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
at pack.madhan.listviewdemo.MainActivity.onContextItemSelected(MainActivity.java:72)
at android.app.Activity.onMenuItemSelected(Activity.java:2628)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:144)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:99)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3864)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:741)
is it possible to delete selected item in listview via context menu ?
please help me on this.
finally i found an answer
Error Code:
int position=listView.getSelectedItemPosition();
String data=values[position];
Updated Code:
AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String data=values[info.position];
where info.position gives the position of item in listView.
To refer click here
Based on the logstack, your function listView.getSelectedItemPosition() returns -1.
int position=listView.getSelectedItemPosition();
java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
-1 is not a correct index, and is the cause of this OutOfBoundsException.
I've never tried to keep track of the latest element selected in a list, but you could do as follow :
Add a variable at the begining of your MainActivity to keep track of the selectedItem;
// First item of the list is selected by defaul to avoid out of bound
int selectedItem = 0;
And update this variable with the onItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem = id;
}
});
I am having an issue with using a listview that when I click it nothing is happening. I would like for it when I click the listview item to make a toast so I know it is being clicked. I have been trying/researching for a while and nothing. Would anybody mind taking a look to see if I am missing something I just am overlooking? Many thanks in advance!
Here is my class:
public class MyCar extends Activity {
/**
* Called when the activity is first created.
*/
public ListView mylistView;
String carInfo;
private ArrayAdapter<String> mylistAdapter;
ArrayList<String> arrayListCar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycar);
mylistView = (ListView) findViewById(R.id.listView);
arrayListCar = new ArrayList<String>();
//Just had to remove setting this adapter 2 times. Took out line below to fix.
mylistView.setAdapter(mylistAdapter);
mylistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
carInfo = trySomethin();
fillList();
}
public void fillList() {
String make = "";
String model = "";
String[] pieces = carInfo.split("\"");
make = pieces[3];
model = pieces[7];
ArrayList<String> carList = new ArrayList<String>();
carList.add(make + " " + model);
// Create ArrayAdapter using the car list.
mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList);
mylistView.setAdapter(mylistAdapter);
mylistAdapter.notifyDataSetChanged();
}
}
if you have any elements on listview item change this for them
android:focusable="false"
and if you are changing any elements visibility on runtime you have to handle focus programatically each time you change its visibility.
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
Hi Every one I'm facing with a problem in android what i need is I'm having a list view in my Activity which is dynamically set with the values from database, If i select a particular item in the list view any action should not be occur and it should be get highlighted.Now I'm having a button(Submit) in the same Activity when ever i click the button the item in the list view value should be displayed in the second activity in a text view.Please help me in solving this
I have created the list view using array adapter
What i need is user should select a name from the list view and click on submit button so that his name should be displayed in the next activity.
Thanks in advance
public class Unitselctn extends Activity{
Button b1;
LinearLayout ll1;
ListView lv;
Cursor c;
SQLiteDatabase db;
Spinner sp1;
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.selection);
sp1=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> unt= ArrayAdapter.createFromResource(this, R.array.Units,android.R.layout.simple_spinner_item);
unt.setDropDownViewResource(android.R.layout.simple_spinner_item);
sp1.setAdapter(unt);
//sp1.setOnItemSelectedListener(this);
b1=(Button)findViewById(R.id.button1);
lv=(ListView)findViewById(R.id.listView1);
lv.setBackgroundColor(Color.WHITE);
//create database if not already exist
db= openOrCreateDatabase("Hangman", MODE_PRIVATE, null);
//create new table if not already exist
db.execSQL("create table if not exists user_reg(name varchar not null, phnum number not null,email varchar not null)");
displayData();
}
public void onNew(View v){
insertData();
}
public void insertData(){
//Toast.makeText(this, "Button1",5000).show();
AlertDialog.Builder adb=new AlertDialog.Builder(this);
ll1=new LinearLayout(this);
ll1.setOrientation(1);
final EditText name= new EditText(this);
final EditText phno= new EditText(this);
final EditText email= new EditText(this);
ll1.addView(name);
ll1.addView(phno);
ll1.addView(email);
name.setHint("UserName");
phno.setHint("Mobile No");
email.setHint("Email-id");
adb.setTitle("Registration");
adb.setView(ll1);
adb.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String nme=name.getText().toString();
String phn=phno.getText().toString();
String mail=email.getText().toString();
name.setText("");
phno.setText("");
email.setText("");
db.execSQL("insert into user_reg values('"+nme+"','"+phn+"','"+mail+"')");
Toast.makeText(getApplicationContext(), "Registered Successfully",5000).show();
displayData();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
adb.show();
}
public void displayData(){
List<String> array = new ArrayList<String>();
db=this.openOrCreateDatabase("Hangman",MODE_PRIVATE, null);
c=db.rawQuery("select name from user_reg", null);
if(c.moveToFirst()){
do{
String usr=c.getString(c.getColumnIndex("name"));
array.add(usr);
}while(c.moveToNext());
}
ArrayAdapter<String> adptr= new ArrayAdapter<String>(this,R.layout.row,R.id.member_name,array);
lv.setAdapter(adptr);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), adptr[pos], 5000).show();
}
});
adptr.notifyDataSetChanged();
}
}
1.have on arraylist add the item that get clicked to it
2.pass condition
if(yourArrayList.contains(item)){
return true;
}else
{
return false;
}
3.Set allItemareClickble to false
Sorry Now I can't post code, Just an Idea.
Create a variable SelectedItem;
Inside lv.setOnItemClickListener(new OnItemClickListener() { } assign the value of the selected list item to the variable(SelectedItem).
Inside OnClickListener method of the button Send this variable(SelectedItem) to the next activity using Intent.
I am trying to get a screen transition when i select a value from the spinner. My spinner has just 2 values. The 1st one is selected by default. What I want is that when i click on the 2nd value in my spinner, it should take me to the new screen.
Please Help!
Thanks in advance!
Use onItemSelectedListener of your Spinner. Here is a Demo,
public class AndroidSpinner extends Activity implements OnItemSelectedListener {
TextView selection;
Spinner spin;
String[] items = { "bangladesh", "bangla", "bd", "australia", "japan",
"china", "indiaA", "indiaC" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Spinner spin = new Spinner(this);
setContentView(spin);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
spin.setAdapter(aa);
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// Do your Stuff Here
Intent intent = new Intent(MyActivity.this, NextActivity.class);
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
selection.setText("");
}
}
Assuming that you know how to set up the spinner adapter and everything, simply add the code to go to the next screen when the other item is selected on the spinner.
public void onItemSelected(AdapterView<?> parent, View v, int position, long id)
{
if(position ==0)
//do nothing (assuming that you would want to stay in the same screen)
else if (position ==1)
{
//go to the next screen, probably by using an INTENT to the next activity or using setContentView(theLayoutXmlFile)
}
}
Use below code for open new activity or new screen onitemselected event of spinner.
public class SpinnerExample extends Activity implements OnItemSelectedListener {
String[] items = { "Dipak", "Aadi", "Bharat", "Pratik", "Usha", "Jayesh", "Deep", "Imran" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner mSpn1 = (Spinner) findViewById(R.id.mSpn1);
mSpn1.setOnItemSelectedListener(this);
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
mSpn1.setAdapter(adpt);
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// Do your Stuff Here
// For Open New Activity
Intent mInNewAccount = new Intent(MainActivity.this, SecondActivity.class);
startActivity(mInNewAccount);
finish();
// For Open New Screen
setContentView(R.layout.second_screen);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Here is the code:
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find your views
final ListView listPro = (ListView) findViewById(R.id.listProperty);
DBAdapter db = new DBAdapter(this);
db.open();
final Cursor c = db.getAllProperties();
startManagingCursor(c);
// Create the adapter
MainAdapter adapter = new MainAdapter(this, c);
listPro.setAdapter(adapter);
// here is where I think I should put the code to select the row but I
// haven't been able to figure out how to do it.
// all I need to get out is the row id number.. please help
Button addPropBut = (Button) findViewById(R.id.mainButton);
addPropBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i7 = new Intent(Main.this, Home.class);
startActivity(i7);
}
});
}
}
try this one, hope it will help you out.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
}
you can get the id number by using Log or System.out.println();
Instead of using Button's setOnClickListener use ListView's setOnItemClickListener.
listPro.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
The id parameter will give you the needed id.
Salil.