ToggleButtons on ListView - android

What is the syntax to get a specific togglebutton from a listview containing the said togglebuttons within a listview_row layout?
I would like to initiate the state of each togglebutton (based on some values originating from a Database), within the onCreate method. I have the following code within a loop, but I am not sure how to change it to reference a specific togglebutton from the listview.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllAlarms();
for(int i = 0; i < array_list.size(); i++) {
arrayListItem = array_list.get(i).toString();
activationInt = Integer.parseInt(arrayListItem);
LayoutInflater vi = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.listview_row, null);
alarm_activated = (ToggleButton) view.findViewById(R.id.alarm_activated);
if (activationInt == 1) {
alarm_activated.setChecked(true);
alarm_activated.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);
} else {
alarm_activated.setChecked(false);
}
}
ArrayAdapter arrayAdapter =
new ArrayAdapter(this, listview_row,R.id.alarm_name,array_list);
obj = (ListView)findViewById(R.id.listViewAlarms);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String itemVal =(String) arg0.getItemAtPosition(arg2);
Bundle dataBundle = new Bundle();
dataBundle.putString("name", itemVal);
Intent intent = new
Intent(getApplicationContext(),DisplayAlarm.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});

Updating views of a ListView/RecyclerView should not really be done in this way.
First because child views referenced in a ListView do not represent the totality of your rows, but only the visible rows at one moment.
ListView binds their item views on DataSet values, so you'd better use data objects that contains your "checked" boolean status, then when you need to sync, update your DataSet and notifyDataSetChange your adapter.
So you'll have to create your custom adapter by following this kind of example : Custom Adapter for List View

Related

SQLite row IDs do not match the ListView row IDs

I have an SQLite database and a ListView displaying in the main activity. In the ListView, I display the details of each list number and upon pressing the list item, a new activity opens up which displays the details in a TextView.
I have a delete function for each of these ListViews and they are not working properly. Essentially, a unique ID is given to each created ListView, which is how the SQLite databases should work. However, upon deleting a row within the ListView, the unique ID increases but the row ID deletes that number and moves everything up. This means that after you delete an item, the row IDs and the database IDs no longer match up and when trying to select an item within the ListView, it crashes. This is an extract from my database adapter class:
public Integer deleteStat(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(STATS_TABLE, "id = ? ", new String[]{Integer.toString(id)});
}
This is my first attempt in the main activity. I got some information from this post but a failed to get the correct integer and received syntax errors:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView pos = (TextView) findViewById(R.id.editTitle);
displayText(Integer.parseInt(pos.getText().toString()));
}
});
}
public void displayText(int pos)
{
pos++;
String s = "";
s += pos;
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtra("id", s);
startActivity(intent);
}
This is my second attempt in the main activity. I used this tutorial to help me. The code I used from that website ruined the entire delete functionality:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int id_To_Search = arg2 + 1;
int id_To_Search = arg0.getCount() - arg2;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
How do I get the database IDs to match up with the row IDs? Any suggestions on how to do that?
EDIT: Added in Hashmap Code. When I press on a ListView Item, nothing happens
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mydb = new StatisticsDbAdapter(this);
ArrayList array_list = mydb.getAllStats();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
/*
New code starts here
*/
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
//means this is the view part not the add contact part
Cursor cursor = mydb.getData(Value);
hashMap.put(cursor.getString(1), cursor.getInt(0));
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int arg2, long arg3) {
TextView textView = (TextView) view.findViewById(R.id.editTitle);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", hashMap.get(textView.getText().toString()));
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
}
}
You should never pass a ListView position to delete a row in a database. I have done that many times before. First of all, within the class you are managing the click events, create a new HashMap. This HashMap will be used to store our row IDs from the database and we'll refer to that rather than the ListView item position. To create it, type this code:
public HashMap<String, Integer> hashMap = new HashMap<>();
Once you have done that, in the function where you display all of the rows in the ListView, you must also load up the same items into the HashMap like this:
hashMap.put(cursor.getString(1), cursor.getInt(0));
Please note that cursor.getString(1) might not be what you used. Please replace the 1 with your appropriate column number that has the name stored within it. cursor.getInt(0) gets the row ID from the database and the column number might be different for you, too. Now, within our OnClickListener function, we can type:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view) {
TextView textView = (TextView) view.findViewById(R.id.editTitle);
Bundle bundle = new Bundle();
bundle.putInt("id", hashMap.get(textView.getText().toString()));
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
Please note that the hashMap variable needs to be within the same class where you manage the click events of your ListView or you will get mistakes. Some of the parametres that you originally passed were removed since you don't need them. Also, I found this to work much better using a RecyclerView but that's now up to you. If you're having problems, please don't hesitate to comment below and I'll try to answer as soon as possible.

ListView creates one more item than needed

I have a ListView which is populated in my MainActivity, but when i want to find the selected item, all of the items appear to have the same position.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_teams);
ListView mainListView;
// Find the ListView in the UI.
mainListView = (ListView) findViewById( R.id.listView );
String values = "Team A vs Team B=Team C vs Team D";
//Matches are send in one long string, and are separated by the = sign.
//This splits the string up and puts it into an array.
String[] array = values.split("=", -1);
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.addAll( Arrays.asList(array) );
ArrayAdapter listAdapter;
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.list_view_style, arraylist);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter(listAdapter);
}
This makes a list like this:
Team A vs Team B [checkbox]
Team C vs Team D [checkbox]
I have a button and when it is clicked it runs this method:
public void matchStart(View view){
String selectedMatch = String.valueOf(((ListView) findViewById( R.id.listView )).getSelectedItemPosition());
Toast.makeText(SelectTeams.this, selectedMatch, Toast.LENGTH_SHORT).show();
}
However whenever i click the button, the toast displays the same value no matter which item in the listview is selected. Why is this?
You should use the adapters getView method, something like this:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.some_layout, parent,
false);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//here get what you need by the position
}
});
}
}

Can I have two different sources pass data to an array adapter?

I am trying to add data from two different sources to an array adapter. One source is from a spinner containing hard coded strings, the other is to allow the user to create their own string to pass to the array (via the adapter). Here is my code below. It appears to me that the array adapter can only except one data source according to the arguments that can be passed to it.......ie
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.alarmList, android.R.layout.simple_spinner_item );
Here I can only guess that the actual string input is gathered from......... android.R.layout.simple_spinner_item
Do I need to use another array adapter or is there a way to add my string variable to the adaoter as well as the item the user has chosen from the spinner? I've done some research here but drawing a blank!!Many thanks. Here's my code which tries to enter strings to adapter..........
public class NewAlarm extends Activity {
Spinner alarms;
//private Button b = (Button) findViewById(R.id.btnAddCustom);
final EditText et = (EditText) findViewById(R.id.edittext);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newalarm);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.alarmList, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//et.setText("name");
alarms = (Spinner) findViewById(R.id.cmbAlarms);
alarms.setAdapter(adapter);
}
public void addAlarm(View view) {
MainMenu.alarmList.add(new Alarm(alarms.getSelectedItem().toString()));
Toast.makeText(getApplicationContext(), "Added " + alarms.getSelectedItem().toString() + " alarm.", Toast.LENGTH_SHORT).show();
NewAlarm.this.finish();
}
public void addCustomAlarm (View view){
MainMenu.alarmList.add(new Alarm(et.getText().toString()));
}
}
And here's my array adapter code............
public View getView(final int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.alarm_item, null);
}
Thanks guys!!
// Get a handle on the UI controls
TextView name = (TextView) convertView.findViewById(R.id.txtAlarmName);
final TextView timeStamp = (TextView) convertView.findViewById(R.id.txtTimeStamp);
// if the value of the timestamp from the alarm at the position selected is not a null value then set the text label to the alarm timestamp value
if (MainMenu.alarmList.get(position).getTimeStamp() != null)
{
timeStamp.setText(MainMenu.alarmList.get(position).getTimeStamp().toString());
}
// Set the alarm name
name.setText(listItems.get(position).getName());
// Get a handle on the button
Button btnCheckNow = (Button) convertView.findViewById(R.id.btnCheckNow);
btnCheckNow.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Set the timestamp of the alarm object at the selected position
MainMenu.alarmList.get(position).setTimeStamp();
// Set the timestamp label
timeStamp.setText(MainMenu.alarmList.get(position).getTimeStamp().toString());
}
});
return convertView;
}
Instead of calling ArrayAdapter.createFromResource(), import the array and add the string before creating the adapter :
CharSequence[] array = Arrays.asList(
getResources().getTextArray(R.array.alarmList));
List<CharSequence> list = new ArrayList<CharSequence>(array);
list.add("custom string");
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, list);

Get Simple List Item Single Choice - Get Selected Item

So, this might be a simple question, or I may be doing things totally off here, but here's what I have:
public class SetPrefsActivity extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.radiolist);
ArrayList<Hall> listItems = new ArrayList<Hall>();
ArrayAdapter<Hall> ar = new ArrayAdapter<Hall>(this, android.R.layout.simple_list_item_single_choice, listItems);
setListAdapter(ar);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
boolean somethingChecked = false;
int lastChecked;
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
if(somethingChecked){
ListView lv = (ListView) arg0;
TextView tv = (TextView) lv.getChildAt(lastChecked);
CheckedTextView cv = (CheckedTextView) tv;
cv.setChecked(false);
}
ListView lv = (ListView) arg0;
TextView tv = (TextView) lv.getChildAt(arg2);
CheckedTextView cv = (CheckedTextView) tv;
if(!cv.isChecked())
cv.setChecked(true);
lastChecked = arg2;
somethingChecked=true;
}
});
new LoadListTask().execute(); //This loads Items into the List
Button b = (Button) findViewById(R.id.savePrefBtn);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//IF SOMETHING IS SELECTED,
//THEN UPDATE SHARED PREFERENCES
Intent i = new Intent(SetPrefsActivity.this, SomeOtherActivity.class);
startActivity(i);
}
}
});
}
//other stuff to fill the arrayAdapter
}
What I want to do, is:
When someone clicks the button, it gets information from the listview and updates a shared preference according to the radio option that's selected.
What I'm having trouble with is getting the index of the currently selected item. What is the best way to retrieve that information? Am I implementing the single choice list completely wrong?
Thank You!
arg2 is the position in your list.
It looks like you are doing some extra (unnecessary) processing. arg1 is your row view, and since the android.R.layout.simple_list_item_single_choice layout contains only a CheckedTextView, you can use that directly without having to look for it.
CheckedTextView cv = (CheckedTextView) arg1;

how to get text from a selected item on a list and set that text in a TextView?

I have created a list. And I need to get the text on the list item, when it is clicked. Then that text need to be set in a TextView. Following is my code and i get a force stop when I run it. Please give some ideas.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtTask = (EditText)findViewById(R.id.txtTask);
btnAdd = (Button)findViewById(R.id.btnAddTask);
selectedTask = (TextView)findViewById(R.id.textViewTask);
list = getListView();
list.setTextFilterEnabled(true);
btnAdd.setOnClickListener(this);
list.setOnKeyListener(this);
toDoItems = new ArrayList<String>();
oo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, toDoItems);
list.setAdapter(oo);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id3) {
int tmp = list.getSelectedItemPosition();
String v= toDoItems.get(tmp).toString();
selectedTask.setTag(v);
flippy.showNext();
}
});
}
Replace below 3 lines of your code in onItemClick method with my suggested code.
int tmp = list.getSelectedItemPosition();
String v= toDoItems.get(tmp).toString();
selectedTask.setTag(v);
Suggested Code
String v= toDoItems[position]; // or
String v = list.getItemAtPosition(position).toString();
selectedTask.setText(v);
After you have got the string v, you need to put the following line :
selectedTask.setText(v);
Also there is no need to put list.setOnKeyListener(this); since you need to listen for the item being clicked.

Categories

Resources