Android - ListView - Output value in listview to screen - android

I have a SQLite Database that contains the following information
--------------------------------
Account_Name Account_Balance
--------------------------------
Savings 1000.00
Checking 1000.00
I have the item being output to a Listview. My question is how do I get my OnItemClick to properly tell me the value that was selected? When I click Savings, I want "Savings" to appear through a Toast. When I tried output, I could only output the item position. I don't want the position in the listview, I am more interested in the String value.
public void onItemClick(AdapterView parent, View view, int position, long id)
{
/*What do I need to code here to just have the value outputted*/
//Toast toast = Toast.makeText(getApplicationContext(), temp1, Toast.LENGTH_LONG);
//toast.show();
}
CODE:
main_menu_activity.java
public class main_menu_activity extends Activity implements AdapterView.OnItemClickListener
{
DatabaseHandler db;
ArrayList<Account> account_details;
ListView accountList;
int num;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_activity);
accountList = (ListView)findViewById(R.id.accountListView);
db = new DatabaseHandler(getApplicationContext());
displayListView();
// Empty Account table
//db.deleteFromAccountTable();
accountList.setOnItemClickListener(this);
num = 1;
}
// MENU //
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu_activity, menu);
return super.onCreateOptionsMenu(menu);
}
// MENU //
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// take appropriate action for each action item clicked
switch(item.getItemId())
{
case R.id.action_add_new:
{
// perform add new item action
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Enter account details:");
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Set an EditText view
final EditText input = new EditText(this);
input.setHint("Account Name");
layout.addView(input);
final EditText input2 = new EditText(this);
input2.setHint("Account Balance");
layout.addView(input2);
alert.setView(layout);
alert.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
if (input.getText().toString() != null)
{
// Create empty Account
Account temp_account;
temp_account = new Account();
// Save information to SQLiteDatabase
temp_account.setAccountName(input.getText().toString());
temp_account.setAccountBalance(Double.parseDouble(input2.getText().toString()));
// Add temp account
db.addAccount(temp_account);
displayListView();
}
else
{
dialogInterface.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
// Output to logcat
/*ArrayList<Account> allAccounts = db.getAllAccounts();
for (Account account: allAccounts)
{
Log.d("Output", Integer.toString(account.getAccountID()));
Log.d("Output", account.getAccountName());
Log.d("Output", Double.toString(account.getAccountBalance()));
}*/
// cancel
dialogInterface.cancel();
}
});
alert.show();
return true;
}
default:
{
return super.onOptionsItemSelected(item);
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
/* CODE TO OUTPUT SELECTED LISTVIEW VALUE */
}
// DISPLAY ACCOUNT LISTVIEW //
public void displayListView()
{
account_details = new ArrayList<Account>();
account_details = db.getAllAccounts();
accountList.setAdapter(new ListViewBaseAdapter(account_details,this));
}
}
listview.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<TextView
android:id="#+id/account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textColor="#00628B"
android:textSize="22dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/account_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textColor="#00628B"
android:textSize="22dp"/>
</RelativeLayout>

You're going to need to have a custom adapter (and layout file) for the row and then add handler for each View in that row.
Vogella has some awesome tutorials so instead of regurgitating them I will point you there.

If you just want to get the name, then why don't you try something like this:
Define an XML layout that contains a row, probably a TextView for each.
Put this code in a custom adapter.
Set the id for the value that contains the savings/checking name, let's say android:id="#+id/accountType
Find that view in the onItemClicked, and get the text.
The code looks like:
String type=((TextView) view.findViewById(R.id.accountType)).getText();

I assume you have your own custom adapter for that. So you can just attach OnClickListeners at the getView() method to every needed View (TextView in your case). Then inside this listener do the following:
View.OnClickListener() {
#Override
public void onClick(View v) {
TextView myView = (TextView) v;
Toast.makeText(context, myView.getText(),Toast.LENGTH_SHORT).show();
}
}

Related

How to get a ListView's elements in a AlertDialog

I am relatively new to android and I am stuck on this problem. I created a button which launches a Dialog. The AlertDialog (to be specific) then programatically create a listView and assign an adapter to it. Now the user can click on some of the elements and the textView elements in the ListView become red. I then store the elements that were clicked. Now, when I create a dialog again, the same texts that were clicked become white.
So my question is, how do I access the listView's elements beforehand so I can alter the colour of the items that were previously clicked.
this is the java code:
private void populateListView(String[] els) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.single_listview_item,R.id.txtitem, els);
list = new ListView(this);
list.setAdapter(adapter);
list.setOnItemClickListener( new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ViewGroup vg=(ViewGroup)view;
TextView txt=(TextView)vg.findViewById(R.id.txtitem);
if(!currentList.isSelected(position)) {
txt.setBackgroundResource(R.color.redPastel);
currentList.select(position);
}
else{
txt.setBackgroundResource(R.color.white);
currentList.unselect(position);
}
}
});
}
//the listener for the button
public void showDialogListView(View view){
String [] selection = {};
Button buttonUsed = null;
switch (view.getId()){
case R.id.cuisineButton:
selection = cuisines.getArray();
currentList = cuisines;
buttonUsed = (Button) findViewById(R.id.cuisineButton);
break;
case R.id.mealTimeButton:
selection = times.getArray();
currentList = times;
buttonUsed = (Button) findViewById(R.id.mealTimeButton);
break;
}
populateListView(selection);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
final Button finalButtonUsed = buttonUsed;
builder.setPositiveButton("Select",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finalButtonUsed.setText(currentList.getSelectionText());
}
});
builder.setNegativeButton("Cancel",null);
builder.setView(list);
AlertDialog dialog=builder.create();
dialog.show();
}
}
this is the layout of the single element XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtitem"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textSize="25sp"
android:gravity="center"
/>
</LinearLayout>
You can get listView item like as
lv_view_task.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,final int arg2,
long arg3) {
final View selectedView v = arg1 ; // Save selected view in final variable**
AlertDialog.Builder alert=new AlertDialog.Builder(ViewTask.this);
alert.setTitle("title stackoverflow");
alert.setIcon(R.drawable.ic_launcher);
alert.setPositiveButton("Fix",new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String str=lv_view_task.getItemAtPosition(arg2).toString();
Toast.makeText(getApplicationContext(), str,Toast.LENGTH_LONG).show();
//Access view object v here
TextView label=(TextView) v.findViewById(R.id.label);
String xyz = label.getText();
}
});

Grid View setOnItemClickListener() not working for custom grid view

I have a button and when I click that button my first custom grid view pops up as dialogue. When I click an item my second custom grid view pops up dismissing my first custom grid view. Now the problem is here, when I click an item in my second custom grid view nothing happens. My setOnItemClickListener() is not working there.I couldn't able to trace my problem where I have done wrong.
Showing my first grid view `
public void outletList() {
dialogOutlet = new Dialog(SelectCategory.this);
dialogOutlet.setContentView(R.layout.outlet_dialogue_grid);
dialogOutlet.setTitle("Select Outlet");
final GridView lv = (GridView) dialogOutlet.findViewById(R.id.gridOutletView);
oa = new OutletAdapter(this, ParseData.OutletList);
lv.setAdapter(oa);
outletFlag = 1;
lv.setOnItemClickListener(this);
dialogOutlet.show();
dialogOutlet.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
Showing second grid view `
public void billList() {
dialogueBill = new Dialog(SelectCategory.this);
dialogueBill.setContentView(R.layout.bill_dialogue_grid);
dialogueBill.setTitle("Select Bill");
final GridView bv = (GridView) dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
System.out.println("focusable "+bv.isFocusableInTouchMode());
System.out.println("focusable "+bv.findFocus());
System.out.println("Outlet Flag Bill List>>>>>>"+outletFlag);
bv.setOnItemClickListener(this);
dialogueBill.show();
dialogueBill.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
On Item Click
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
System.out.println("Outlet Flag inside Item Click>>>>>>"+outletFlag);
if(outletFlag!=1){
HashMap<String, String> out = BillAdapter.billData.get(pos);
String sel_bill = out.get(ParseData.KEY_BILL_NO);
System.out.println("Selected Bill>>>>>>"+sel_bill);
selected_bill = sel_bill;
Intent iii = new Intent(SelectCategory.this, FBHome.class);
startActivity(iii);
}
else{
HashMap<String, String> out = OutletAdapter.outletData.get(pos);
String sel_name = out.get(ParseData.KEY_NAME);
String sel_code = out.get(ParseData.KEY_CODE);
out_pos = pos;
selected_outlet = sel_code;
selected_outlet_name = sel_name;
dialogOutlet.dismiss();
outletFlag = 0;
new GetBillDetails().execute();
}
}
Thanks in advance :)
In your Gridview Layout if you are using Clickable Widgets like Button or an ImageButton Change it and try.
That is android does not recognize click events inside the Gridadpater views, so if you change that everything should work fine
You could try
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/darker_gray"
android:layout_width="90dp"
android:layout_height="90dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/bt_grid"
android:layout_width="wrap_content"
android:textColor="#android:color/white"
android:layout_height="wrap_content" />
</LinearLayout>
Try using Alert Dialog
private void showGridDialog() {
// Prepare grid view
final GridView bv = (GridView)
dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
bv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do something here
}
});
// Set grid view to alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(bv);
builder.setTitle("Goto");
builder.show();
}

How to make a listview(already created) clickable (Android)?

I made a list and now I want when the user clicks an item, it opens a new screen showing the PKMN data. Here's my code:
Kanto.class
public class Kanto extends ActionBarActivity {
//fasendu listaa = making list
ListView listView; //criandu var = making variable
String[] pokemonsKanto = {
"#1 Bulbasaur", "#2 Ivysaur", "#3 Venusaur"
}; //lista = list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kanto);
//continuandu a lista = the other part to the list work
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> array = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, pokemonsKanto);
listView.setAdapter(array);
//lista cabada = finished
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.kanto, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
activity_kanto.xml
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Kanto">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
How can I do that? Sorry, I'm a completely newbie .
Now you just have to set an onItemClickListener to your ListView, like this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//create an Intent to your new `Activity` with PKMN data
Intent pkmnActivityIntent = new Intent(Kanto.this, YourPKMNActivity.class);
//pass your pkmn number and name (from your `String` array) in the `Intent`, so it can be shown in the new `Activity`
pkmnActivityIntent.putExtra("name",pokemonsKanto[position] );
//start your new Activity
startActivity(pkmnActivityIntent );
}
});
This listener is activated when the user clicks an item in your list. You can set it right after listview.setAdapter() method.
Edit: Do not forget to declare your new Activity on your manifest.xml file.
Then in your new Activity, just get the pkmn name by using:
String pkmnName = getIntent().getStringExtra("name");
Now you can show your pkmnName in a TextView or something.
You need to add a listener to the items of the list,for example I will give you how to show the text of the item in an alert dialog (you can put the title of the item in a string to pass it in intent rather than display it in an alert dialog) :
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//The title of the Item is recovered in a String
String item = (String) listView.getAdapter().getItem(position);
AlertDialog.Builder adb = new AlertDialog.Builder(kanto.this);
//The title of the alert Dialog
adb.setTitle("Your Item");
//The name of the Item
adb.setMessage("You have selected : "+item);
//the OK button
adb.setPositiveButton("Ok", null);
//show the alert dialog
adb.show();
}
});

Highlight selected Spinner Item

I have implemented Custom Spinner using Button following wildnove's answer. Everything works fine, but I am not able to display the highlighted radio button for the selected button.
Below is the code.
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// How to highlight Radio button of a selected Item???
final String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Button) findViewById(R.id.btnSpinnerPlanets)).setText(items[which]);
dialog.dismiss();
}
}).create().show();
}
});
Can somebody help me how to highlight selected Item's Radio button ...
Unfortunately this behavior is not natively implemented in Spinner component, however, you can always create your own BaseAdapter to show whatever you need weather is in the spinner it self or in the dropdown like this:
private class ExampleAdapter extends BaseAdapter{
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Here is where you actually get the chance to return whatever you want in the spinner component (the single bar with the arrow)
return yourCommonView;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
//Here is where you get the chance to return whatever you want in the dropdown menu so here you should validate what's the currently selected element and return an image accordingly...
return yourSelectedView;
}
}
The important method here is, getDropDownView that is the one that gives you the chance to return an element with a checked CheckBox, or any mark you want to use, of course you have to create your own layout and validate if the element currently created need to be marked or not...
Regards!
The problem with this code is that you are creating the Spinner each time the Button is clicked. Try the following code:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
switch(id) {
case 1:
Button b=((Button) findViewById(R.id.btnSpinnerPlanets));
builder = new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(get_the_adapter(b), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
b.setText(b.getResources().getStringArray(R.array.planets__entries)[which]);
dismissDialog(1);
}
})
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
}
public ArrayAdapter<String> get_the_Adapter(Button view){
String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
return adapter;
}
And for the Button's onClick():
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(1);
}
});

Multiple choice AlertDialog with custom Adapter

I am trying to create a AlertDialog with multiple choice option. I have tried with the setMultiChoiceItems but what i have is a ArrayList<Category> and not a CharSequence so i tried with the adapter.
The problem with setAdapter is that when i select one item it closes the dialog window. And what i want is to select the items and then hit the OK button to see what items where selected.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
ArrayAdapter<Category> catsAdapter = new ArrayAdapter<Category>(this, android.R.layout.select_dialog_multichoice,this.categories);
builder.setAdapter(catsAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}
});
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do something
}
});;
AlertDialog alert = builder.create();
alert.show();
Unfortunately, there doesn't seem to be an easy way to toggle on AlertDialog's multichoicemode without calling setMultiChoiceItems().
However, you can set an adapter, then turn on multichoice mode in the contained ListView itself.
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setAdapter(yourAdapter, null)
.setPositiveButton(getResources().getString(R.string.positive), null)
.setNegativeButton(getResources().getString(android.R.string.cancel), null)
.create();
dialog.getListView().setItemsCanFocus(false);
dialog.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
dialog.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Manage selected items here
System.out.println("clicked" + position);
CheckedTextView textView = (CheckedTextView) view;
if(textView.isChecked()) {
} else {
}
}
});
dialog.show();
this will stop ur dialog from disappearing after one selection.
AlertDialog alertDialog = builder.create();
ListView listView = alertDialog.getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
To get which items are selected , you need to plan your adapter accordingly.
see below code it may help you. i used this in my app.
public static ArrayList<String> Party_list_new = new ArrayList<String>();
ArrayList<String> party_multi_cheked = new ArrayList<String>();
public void show_alert() {
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.alert_);
dia.setTitle("Select File to import");
dia.setCancelable(true);
final ListView list_alert = (ListView) dia
.findViewById(R.id.alert_list);
list_alert.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_multiple_choice,
Party_list_new));
list_alert.setItemsCanFocus(false);
list_alert.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_alert.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
}
});
Button btn = (Button) dia.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SparseBooleanArray positions = list_alert
.getCheckedItemPositions();
int j = 0;
for (int k = 0; k < Party_list_new.size(); k++) {
if (positions.get(k)) {
party_multi_cheked.add("" + k);
}
}
dia.dismiss();
}
});
dia.show();
}
alert_list.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Party" />
<ListView
android:id="#+id/alert_list"
android:layout_width="match_parent" android:padding="5dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
make it right if it is correct.

Categories

Resources