ArrayList and ListView are not being populated - android

I am completely lost and have no idea why my ListView is not being populated. In my method where I am inserting data into my ArrayList, it says my adapter symbol cannot be resolved, but as far as I know I have properly declared the adapter in my onCreate.
Am I correct in assuming that if I have a ListView inside of my activity, set up an ArrayList that fills my adapter, and then tie that adapter to the ListView that my ListView will auto-populate in my activity whenever the array receives information?
Here are my declarations inside of my onCreate.
ListView listView = (ListView) findViewById(R.id.dispScores);
ArrayList<viewScores> savedScores = new ArrayList<viewScores>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
These are the methods I am using to add data into my ArrayList.
public View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
//ATTEMPTING TO WRITE TO ARRAYLIST
viewScores addScore = new viewScores(input1.getText().toString());
adapter.notifyDataSetChanged();
adapter.add(addScore); //WHY DOESNT THIS WORK?
j++;
input1.setText(""); //Clear input text box
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
//CURRENTLY ONLY DISPLAYS THE LAST NUNMBER IN THE TEXTEDIT, NEED TO SET UP LISTVIEW!!!!!!
for (int i=0; i < j; i++){
// output1.setText(savedScores.get(i));
} break;
}
}
};
public class viewScores {
public String hole;
public viewScores(String holeNum) {
this.hole = holeNum;
}
}
public class ScoreAdapter extends ArrayAdapter<viewScores> {
public ScoreAdapter(Context context, ArrayList<viewScores> scores) {
super(context, 0, scores);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
viewScores score1 = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
TextView ListView1 = (TextView) convertView.findViewById(R.id.dispScores);
ListView1.setText(score1.hole);
return convertView;
}
}
The app doesn't crash and I am able to enter values into my EditText. Below is the XML for the ListView.
<ListView
android:id="#+id/dispScores"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
app:layout_constraintLeft_toLeftOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"
tools:layout_editor_absoluteY="244dp" />

Whenever you update the model observed by your adapter, you need to call
adapter.notifyDataSetChanged()
So in your case,
viewScores addScore = new viewScores(input1.getText().toString());
savedScores.add(addScore);
adapter.notifyDataSetChanged()

Related

Generating a ListView Using ArrayAdapter [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to populate a ListView using an ArrayAdapter that I am filling with input from an EditText. My program seems to compile fine but during app start up it immediately crashes. I suspect that it has something to do with me trying to set-up my list view. I am not sure what I am initializing wrong such that my app instantly crashes. Any and all tips would be greatly appreciated. Thanks in advance!
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
ListView listView = (ListView) findViewById(R.id.dispScores);
listView.setAdapter(adapter);
My Adapter Class:
private class ScoreAdapter extends ArrayAdapter<scoreScreen> {
private ScoreAdapter(Context context, ArrayList<scoreScreen> scores) {
super(context, 0, scores);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
scoreScreen score1 = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_scores, parent, false);
}
TextView holeNum = (TextView) convertView.findViewById(R.id.holeNum);
holeNum.setText(score1.hole);
return convertView;
}
}
My ListView inside of my onCreate method.
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
I am assuming my problem is not inside my EditText inputs since they are inside of an OnClickListener method, but just incase I have attached it below.
public View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
//savedScores.add(input1.getText().toString());
scoreScreen addScore = new scoreScreen("Score is" + num1);
adapter.add(addScore);
j++;
input1.setText(""); //Clear input text box
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
//CURRENTLY ONLY DISPLAYS THE LAST NUNMBER IN THE TEXTEDIT, NEED TO SET UP LISTVIEW!!!!!!
for (int i=0; i < j; i++){
// output1.setText(savedScores.get(i));
} break;
}
}
};
onCreate method added as requested:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Button scoresAct = (Button) findViewById(R.id.allScores); //THIS IS TO GO TO ALL SCORES ACTIVITY
scoresAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent scoreScreen = new Intent(MainActivity.this, AllScoresAct.class);
startActivity(scoreScreen);
}
});*/
Button sumScores = (Button) findViewById(R.id.buttTotal);
Button saveScores = (Button) findViewById(R.id.allScores);
Button changeScores = (Button) findViewById(R.id.editScore);
sumScores.setOnClickListener(onClickListener);
saveScores.setOnClickListener(onClickListener);
changeScores.setOnClickListener(onClickListener);
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
}
After moving my adapter and ArrayList into my onCreate, I get a new error. I did some research on null pointers, but I have already initialized both of these. Below is my logcat, any ideas? Thanks
Make sure super.onCreate(savedInstanceState) is the first thing you are calling in your onCreate() and also not trying to access any view from the layout xml before setContentView().
EDIT:
Initialize the adapter in onCreate() method instead of doing it globally.
onCreate() {
.......
this.adapter = new ScoreAdapter(this, savedScores);
}
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
You can declare those globally, but for the Adapter, the this parameter must be used within/after onCreate, as the error says
System services not available to Activities before onCreate()
For example
private ArrayList<ScoreScreen> savedScores = new ArrayList<>();
private ScoreAdapter adapter;
#Override
protected void onCreate(Bundle b) {
...
adapter = new ScoreAdapter(this, savedScores);
}

Android: Select ListView Items and get the Objects

i made a custom listView having two textViews..for example student name and roll no...
now i want to implement a selection...for example..i will click on few students in the listview and the object should get saved somewhere ...for example:
ClassList.add(new StudentList(99,"student1","code"));
ClassList.add(new StudentList(70,"student2","code"));
ClassList.add(new StudentList(20,"student3","code"));
ClassList.add(new StudentList(30,"student4","code"));
adapter = new StudentListViewAdapter(this, ClassList,"code");
listView.setAdapter(adapter);
now i should be able to set another method for example:
ClassList2=listView.getSelectedStudents();
this should return the selected students..for example if i select student 1,student 2 it should return Student List Objects for both of them so i can access there roll and Code too
And there is another problem...when i deselect it should remove that object from the list..
It would be really helpfull if someone will write a sample code
This is how i do it..but i don't think it is really a good method
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (ItemView == null) {
ItemView = inflater.inflate(R.layout.customvistview_atd, parent, false);
}
//find the hotels to work with
final studentlist currentList = totalClass_list.get(position);
//fill the view
final TextView textview_studentName = (TextView) ItemView.findViewById(R.id.textview_atd_studentName);
textview_studentName.setText((currentList.getName()));
final TextView textview_studentRollno = (TextView) ItemView.findViewById(R.id.textview_atd_studentRollno);
textview_studentRollno.setText((currentList.getRoll_no() + ""));
final CardView cardView = (CardView) ItemView.findViewById(R.id.card_view_atd);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i = 0; i < presentStudents.size(); i++) {
if (presentStudents.get(i).getMindex() == position) {
System.out.println("m-index : "+presentStudents.get(i).getMindex());
System.out.println("position : "+position);
isChecked = true;
System.out.println("I am in the loop, I am at position: "+i);
me = i;
break;
}
}
if (isChecked) {
presentStudents.remove(me);
isChecked = false;
ColorDrawable[] color = {new ColorDrawable(Color.parseColor("#198b9f")), new ColorDrawable(Color.WHITE)};
TransitionDrawable trans = new TransitionDrawable(color);
cardView.setBackground(trans);
trans.startTransition(1500);
textview_studentName.setTextColor(Color.GRAY);
textview_studentName.setTextColor(Color.GRAY);
//cardView.setBackgroundColor(Color.WHITE);
System.out.println("I am in isChecked");
} else {
presentStudents.add(new tempclass(currentList.getRoll_no(),atdCode,position));
ColorDrawable[] colorCard = {new ColorDrawable(Color.WHITE), new ColorDrawable(Color.parseColor("#198b9f"))};
TransitionDrawable trans = new TransitionDrawable(colorCard);
cardView.setBackground(trans);
trans.startTransition(1500);
textview_studentName.setTextColor(Color.WHITE);
textview_studentName.setTextColor(Color.WHITE);
// cardView.setBackgroundColor(Color.BLUE);
System.out.println("I am in else, making it blue");
}
}
});
you can use this one
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
StudentLists studentList = listView.getItemAtPosition(i);//selected object
adapter.dismiss(); // If you want to close the adapter
}
});

ArrayAdapter strange behaviour with id when items's height exceed Listview height

I'm facing a strange behaviour using an ArrayAdapter.
When the number of listview item exceed the height of the listView (say after item 8), the next item get the id 0 instead the id 9.
In my opinion this type of issue was explained here with the convertView, but i use it in the same way (i think).
The following code is my ArrayAdapter.
public class StepsAdapter extends ArrayAdapter<String> {
Context context;
List<String> steps;
public StepsAdapter(Context context, int resourceId, List<String> steps) {
super(context, resourceId, steps);
this.context = context;
}
private class ViewHolder {
EditText stepValue;
ImageView removeStep;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final String step = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_step, null);
holder = new ViewHolder();
holder.stepValue = (EditText) convertView.findViewById(R.id.stepEdit);
holder.removeStep = (ImageView) convertView.findViewById(R.id.removeStep);
holder.stepValue.setText(step);
holder.removeStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"* Remove id step " + position, Toast.LENGTH_LONG).show();
steps.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
Then my main activity where i get existing data and put it in my listView, the add button and the save button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_game);
mContext = getApplicationContext();
steps = new ArrayList<String>();
stepsAdapter = new StepsAdapter(mContext,R.layout.row_step,steps);
Gson gson = new GsonBuilder().create();
game = gson.fromJson(gameJson, Games.class);
/*
* Settings values
*/
gameNameValue.setText(game.getName());
gameBackgroundPreview.setBackgroundColor(game.getColor());
colorSelected = game.getColor();
for(int i = 0; i < game.getSteps().size() ; i++){
//steps.add(game.getSteps().get(i).toString());
//notifyDataSetChanged();
stepsAdapter.add(game.getSteps().get(i).toString());
}
final ListView listSteps = (ListView) findViewById(R.id.listViewSteps);
listSteps.setAdapter(stepsAdapter);
gameNameValue.setText(gameName);
addSteps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stepsId = steps.size();
Toast.makeText(getApplicationContext(), "addSteps : " + stepsId, Toast.LENGTH_LONG).show();
stepsAdapter.insert("newstep", stepsId);
}
});
buttonSaveGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String valueEditGameName = gameNameValue.getText().toString();
int valueColorBackaground = colorSelected;
String picture = "testPic";
for(int i=0; i < listSteps.getChildCount(); i++) {
LinearLayout rowLayout = (LinearLayout) listSteps.getChildAt(i);
//Log.e(TAG, ">> :) layout >>" + listSteps.getChildAt(i).getClass().getName());
EditText editRow = (EditText) rowLayout.getChildAt(0);
stepsValues.add(editRow.getText().toString());
//Log.e(TAG, ">> :) inside layout >>" + editRow.getText().toString());
}
if(valueEditGameName.trim().length() > 0 && picture.trim().length() >0 ){
Games game = new Games(valueEditGameName,valueColorBackaground,picture,stepsValues);
String goToSave = game.createJson();
Log.e(TAG, ">>Saved>>" + goToSave);
final CkdFile file = new CkdFile();
String saved = file.writeToSDFile(game.getName(), goToSave);
Toast.makeText(mContext, saved, Toast.LENGTH_LONG).show();
Intent backToMain = new Intent(mContext,MainActivity.class);
startActivity(backToMain);
} else {
Toast.makeText(mContext, "Fill all texts", Toast.LENGTH_LONG).show();
}
}
});
}
I try to add items in 2 different ways :
add item through : List steps
add item through : StepsAdapter stepsAdapter
Both give me same behaviour.
If someone has a clue to help understanding what i'm doing wrong with my implementation of ListView/ArrayAdapter.
Thanks in advance !
EDIT 1 :
After pushing some logs everywere, it understand the strange behaviour :
My adapter have only 6 slots (the limit came from the size of the listview in layout), and when my arraylist have more than 6 items, the getView select items only between 0 and 5.
I'm searching now a way to get the position in ArrayList and not the position in arrayadapter.
I faced same issue recently. Add following overrides to Adapter:
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
I found a simple xml "trick" to avoid this behaviour : i set a biger height to listView.
<ListView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:layout_gravity="center_horizontal"
android:id="#+id/listViewSteps"
android:layout_margin="10dp">
</ListView>
It's not really resolve but a take it ...

setVisibility(View.GONE) not removing space in listview item

I am making a question that could be like a duplicated question, but i have tried everything and nothing worked for me. I have created a listview witch every item has two views, one textview and one checkbox. Its like a multiselect listview. Every item has a level on its own: easy, normal, hard. When a level is chosen from a dropdown: All, Easy, Normal, Hard.. the list changes, just like a filter system.
But when i write listView.getChildAt(i).setVisibility(View.GONE); the content of the row is removed but the space occupied is not released.
Any help?
This is my code:
public class CreatePresentation extends Activity
{
DatabaseHelper db = new DatabaseHelper(this);
MyCustomAdapter dataAdapter = null;
List<Slider> list;
ListView listView;
String Text;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.create_presentation);
displayListView();
checkButtonClick();
}
private void displayListView()
{
list = new ArrayList<Slider>();
ArrayList<Slider> oldList = db.getAllSliders();
for (Slider anOldList : oldList) {
String s = anOldList.toString();
int in = anOldList.getId();
String lev = anOldList.getLevel();
Slider slider = new Slider(in, s, lev, false);
list.add(slider);
}
dataAdapter = new MyCustomAdapter(this, R.layout.list_check_box, list);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(dataAdapter);
}
private class MyCustomAdapter extends ArrayAdapter<Slider> {
private ArrayList<Slider> list;
public MyCustomAdapter(Context context, int textViewResourceId, List<Slider> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Slider>();
this.list.addAll(list);
}
private class ViewHolder {
TextView text;
CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final Slider slider = list.get(position);
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_check_box, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.sliderTitle);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
Spinner dropdown = (Spinner)findViewById(R.id.spinner);
String[] items = new String[]{"Tutto", "Facile", "Medio", "Difficile"};
ArrayAdapter<String> adapter = new ArrayAdapter<String (CreatePresentation.this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
Text = dropdown.getSelectedItem().toString();
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
try {
if (list.get(position).getLevel().equals("Facile"))
convertView.setBackgroundColor(Color.parseColor("#477C3D"));
else if (list.get(position).getLevel().equals("Medio"))
convertView.setBackgroundColor(Color.parseColor("#936019"));
else if (list.get(position).getLevel().equals("Difficile"))
convertView.setBackgroundColor(Color.parseColor("#A02307"));
} catch (Throwable e) {
e.printStackTrace();
}
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, final int position, long id) {
Text = parentView.getItemAtPosition(position).toString();
try {
if (Text.equals("All")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
}
};
runOnUiThread(run);
}
if (Text.equals("Easy")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Easy")) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
}
}
};
runOnUiThread(run);
}
if (Text.equals("Normal")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Normal"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
dataAdapter.notifyDataSetChanged();
}
}
};
runOnUiThread(run);
}
if (Text.equals("Hard")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Hard"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else
listView.getChildAt(i).setVisibility(View.GONE);
}
}
};
runOnUiThread(run);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(slider.getQuestion());
holder.checkbox.setChecked(slider.isSelected());
holder.checkbox.setTag(slider);
return convertView;
}
}
the best way to do this is to remove the item from the list and call dataAdapter.notifyDataSetChanged()
As you want to remove your view but keep your item inside your List I suggest you to use a different method. When the user choose a value that will cause the item to be hide just set that value to your item and then call
dataAdapter.notifyDataSetChanged();
Doing this you have to modify the logic inside your getView(), I mean if you find an item that is eligible to get hide instead of return convertView inside the getView() method of your customAdapter just return an empty view, like this you item won't be shown but it will still be in your list;)
You can use a parent Layout for Yuor item to resolve the issue:
For example:
<LinearLayout ...>
<!-- Here Your item content starts -->
<LinearLayout android:id="#+id/content">
...
</LinearLayout>
<!-- Here Your content ends -->
</LinearLayout>
Java code:
listView.getChildAt(i).getChildAt(0).setVisibility(View.GONE);
just like a filter system. Why "like", why not make it actually filterable? There are two options. Easier one is overriding toString of your slider. Other one is creating custom filter, which wouldn't use object's toString method. However, I don't remember how exactly to do second one, only that it's possible.
Slider:
String toString(){
return this.type;
}
When spinner selection changes:
adapter.getFilter().filter(selectedDifficulty);
This will automatically display items you want to see.
You shouldnt change visibility of views generated by adapter - they change every time when you scroll listview. Instead you should change the behaviour of underlying adapter.
You can try this layout instead of the ListView since there's only 4 filters:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<include
android:id="#+id/filter_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
</LinearLayout>
When you want to hide one of the filters you can just do something like:
findViewById(R.id.filter_4).setVisibility(View.GONE);
EDIT:
For instance, if you want to add information to a TextView inside the first include you just have to call the View like this:
View filter1 = findViewById(R.id.filter_1);
TextView tv1 = (TextView) filter1.findViewById(R.id.<the_id_of_the_textview);
tv1.setText("StackOverflow filter");
To prevent add another layout in outside of your layout. You just hide the item's all child views, not item itself.
For example:
if(i == 1){ // assume we need hide the first item.
//item itself
ViewGroup parent = ((ViewGroup) holder.convertView);
for (int j = 0; j < parent.getChildCount(); j++) {
parent.getChildAt(j).setVisibility(View.GONE);
}
}
And i have test this code, works fine for me.

Get tags from Radiobuttons in ListView Android

I have a custom listView built with ArrayAdapter. In ListView each item contents a TextView and a RadioGroup (with 4 RadioButton). I can choose one RadioButton to be selected for each list item. On the bottom of ListView i have a footer with button. What i want is to get all data when i click on button like this:
name1 - 1
name2 - 3
name3 - 2
name4 - 3
...
First column - Text from TextView
Second column - Tag of selected RadioButton
Atcivity with view:
public class MarksAdd extends ListActivity {
ArrayList<String> itemlist = new ArrayList<String>();
private Context context = null;
private ListView listView;
private Button BtnDone;
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.marks_add);
Intent intent = getIntent();
int day = intent.getIntExtra("day", 0);
int month = intent.getIntExtra("month", 0);
int year = intent.getIntExtra("year", 0);
String dayStr = String.valueOf(day);
String monthStr = String.valueOf(month);
String yearStr = String.valueOf(year);
if (day != 0) {
if(dayStr.length()==1){
dayStr = "0"+dayStr;
}
if(monthStr.length()==1){
monthStr = "0"+monthStr;
}
yearStr = yearStr.substring(2);
String date = dayStr+"."+monthStr+"."+yearStr;
Toast.makeText(this, date, Toast.LENGTH_SHORT).show();
}
final ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
getModel());
listView = getListView();
LayoutInflater inflater = getLayoutInflater();
listView.addFooterView(inflater.inflate(R.layout.list_footer, null), null, false);
setListAdapter(adapter);
BtnDone = (Button) findViewById(R.id.markListBtn);
BtnDone.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//get Values ?????
}
});
}
private List<Model> getModel() {
List<Model> list = new ArrayList<Model>();
dbHelper sql = new dbHelper(this);
SQLiteDatabase db = sql.getWritableDatabase();
Cursor cursor = db.query(
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("group", ""), new String[]{
"Id", "Name"},
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
"Name ASC" // The sort order
);
while (cursor.moveToNext()) {
// GET COLUMN INDICES + VALUES OF THOSE COLUMNS
int id = cursor.getInt(cursor.getColumnIndex("Id"));
String name = cursor.getString(cursor
.getColumnIndex("Name"));
list.add(get(name));
}
cursor.close();
// Initially select one of the items
return list;
}
private Model get(String question) {
return new Model(question);
}
}
ArrayAdapter:
public class InteractiveArrayAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.simple_list_item1_marks, list);
this.context = context;
this.list = list;
}
class ViewHolder {
TextView t = null;
RadioGroup group;
ViewHolder(View v) {
t = (TextView) v.findViewById(R.id.personName);
group = (RadioGroup) v.findViewById(R.id.myRgroup);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder = null;
if (v == null) {
LayoutInflater inflater = context.getLayoutInflater();
v = inflater.inflate(R.layout.simple_list_item1_marks, parent, false);
holder = new ViewHolder(v);
v.setTag(holder);
final View finalV = v;
holder.group
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
Integer pos = (Integer) group.getTag(); // To identify the Model object i get from the RadioGroup with getTag()
// an integer representing the actual position
Model element = list.get(pos);
switch (checkedId) { //set the Model to hold the answer the user picked
case R.id.rb1:
element.current = Model.ANSWER_ONE_SELECTED;
break;
case R.id.rb2:
element.current = Model.ANSWER_TWO_SELECTED;
break;
case R.id.rb3:
element.current = Model.ANSWER_THREE_SELECTED;
break;
case R.id.rb4:
element.current = Model.ANSWER_FOUR_SELECTED;
break;
default:
element.current = Model.NONE; // Something was wrong set to the default
}
}
});
} else {
holder = (ViewHolder) v.getTag();
}
holder.group.setTag(position); // I passed the current position as a tag
holder.t.setText(list.get(position).question); // Set the question body
if (list.get(position).current != Model.NONE) {
RadioButton r = (RadioButton) holder.group.getChildAt(list
.get(position).current);
r.setChecked(true);
} else {
holder.group.clearCheck(); // This is required because although the Model could have the current
// position to NONE you could be dealing with a previous row where
// the user already picked an answer.
}
return v;
}
}
Model:
public class Model {
String question; // hold the question
int current = NONE; // hold the answer picked by the user, initial is NONE(see below)
public static final int NONE = 1000; // No answer selected
public static final int ANSWER_ONE_SELECTED = 0; // first answer selected
public static final int ANSWER_TWO_SELECTED = 1; // second answer selected
public static final int ANSWER_THREE_SELECTED = 2; // third answer selected
public static final int ANSWER_FOUR_SELECTED = 3; // forth answer selected
public Model(String question) {
this.question = question;
}
}
I was doing this according to that tutorial with some changes. Actualy i'm realy newbie in development, so im asking you to help me. Sorry if my question is not correct, my english is not realy good.
Well be very thankfull for any help here.
The first thought would be to iterate over the ListView and get the checked button in each row. This won't actually work because ListView does not contain all of its children all of the time.
Instead, you should store the checked item when the user actually makes a selection. Then when you press the button, you already have all the data stored and don't have to iterate over the ListView. Also, having the current selections saved this way will be useful if you scroll back up the list because you can set the current checked radio button for previous items in getView().
Let's assume the row layout has this in it:
<RadioGroup android:id="#+id/radio_group" ... >
<RadioButton android:id="#+id/radio_button_1" ... />
<RadioButton android:id="#+id/radio_button_2" ... />
<RadioButton android:id="#+id/radio_button_3" ... />
<RadioButton android:id="#+id/radio_button_4" ... />
</RadioGroup>
In your adapter's getView(), give the RadioGroup an OnCheckedChangedListener defined in the adapter itself (so you have one OnCheckedChangedListener instead of one per row). Tag the RadioGroup with the position of the list item so that you can differentiate it in the callback.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
Model model = getItem(position);
int checkedId = ... //figure out checked id from model
viewHolder.group.check(checkedId);
viewHolder.group.setTag(position);
viewHolder.group.setOnCheckedChangedListener(checkChangedListener);
...
}
private OnCheckedChangedListener checkChangedListener = new OnCheckedChangedListener() {
#Override
public void onCheckChanged(RadioGroup group, int checkId) {
Object tag = group.getTag();
if (!(tag instanceof Integer)) {
// you have a bug. Fix it!
return;
}
int position = (Integer) tag;
Model model = getItem(position);
switch(checkedId) {
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_ONE_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_TWO_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_THREE_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_FOUR_SELECTED); break;
}
}
};
Now you just need to get your list of Models from the adapter.

Categories

Resources