BaseAdapter On Scroll Refresh Data in ListView - android

I'm Very new to Java and android... I'm Try to create an ListView using BaseAdapter List being created successfully i have a EditText along with button for each list item but the real problem is when i put some data into editText Field and scroll down to change value of last list item then i go back to the top it refreshes the data to default value it doesn't contain the value which was entered by user before scrolling down
My BaseAdaper Code
class CoustomAdptr extends BaseAdapter{
String[] dates;
Integer[] inventory;
Integer totalrooms;
public CoustomAdptr(RoomFragment roomFragment, String[] dates, Integer[] inventory, Integer totalrooms) {
this.dates = dates;
this.inventory = inventory;
this.totalrooms = totalrooms;
}
#Override
public int getCount() {
return dates.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.inventory_listview,null);
TextView textView = (TextView) view.findViewById(R.id.roomListViewText);
final EditText editText = (EditText) view.findViewById(R.id.roomListInventory);
final Button updateButton = (Button) view.findViewById(R.id.roomListViewInventoryUpdateButton);
if(inventory[i] == 0){
editText.setBackgroundColor(getResources().getColor(R.color.SoldOut));
editText.setTextColor(getResources().getColor(R.color.SoldOutTextColor));
} else if(inventory[i] < totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.invetory));
editText.setTextColor(getResources().getColor(R.color.invetoryTextColor));
} else if(inventory[i] == totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.fullInventory));
editText.setTextColor(getResources().getColor(R.color.fullInventoryTextColor));
}
editText.setText(String.valueOf(inventory[i]));
textView.setText(dates[i]);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String name = editText.getText().toString();
//String name1 = dates[i];
//String name2 = getArguments().getString("room_id");
updateButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_done_black_24dp,0,0,0);
//updateButton.setBackgroundColor(getResources().getColor(R.color.SoldOut));
updateButton.setText("Updated");
updateButton.setEnabled(false);
Toast.makeText(getContext(), "Update Inventory Button Clicked", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is How Im Passing Data to My Adapter
JSONObject jObj = parentObject.getJSONObject("success");
JSONObject jObj2 = jObj.getJSONObject("data");
JSONArray arrajson = jObj2.getJSONArray("inventories");
String arrayCount = Integer.toString(arrajson.length());
String[] dates = new String[arrajson.length()];
Integer[] inventory = new Integer[arrajson.length()];
Integer totalrooms = new Integer(jObj2.getInt("total_room"));
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
dates[i] = jsonObject.getString("date");
inventory[i] = jsonObject.getInt("inventory");
}
CoustomAdptr coustomAdptr = new CoustomAdptr(RoomFragment.this,dates,inventory,totalrooms);
listView.setAdapter(coustomAdptr);
Help Needed :- I Want to retain same visible and Value of edittext as users enters on scroll up or down... i hope i was able to explain my problem clearly

After clicking a button, save it's state in a boolean array or somewhere else. And inside getView method, check if this button was previously clicked or not then setup your view accordingly.
It would be better if you create a model class for rows.

Related

Scrolling down the ListView the favourite button checked gets unchecked android studio

The code below saves the current text of the TextView when the favourite button is clicked and the button Image changes to Fav_Checked when I click again the favourite button is unchecked and the text in array is removed but the issue is when I scroll down the ListView updates and the favourite buttons are unchecked. kindly help.
public class MainActivity extends AppCompatActivity {
// ArrayList<String> names = new ArrayList<>();
private ArrayList<String> names;
int x = names.size();
// private boolean[x] favorites;
private SharedPreferences sharedPreferences;
Context context = this;
MediaPlayer mPlayer;
Boolean isPlay = true;
ImageView playPauseGlobelBtn;
int maxVolume,resID,position;
String fname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView)findViewById(R.id.listView);
mPlayer = MediaPlayer.create(context, R.raw.asdf);
CustomAdapter customAdapter=new CustomAdapter();
listView.setAdapter(customAdapter);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");
if(favoriteItems.isEmpty()) {
names = new ArrayList<>();
}
else {
names = new ArrayList<>(Arrays.asList(favoriteItems.split(",")));
}
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.customlayout, null);
final TextView textView_name = (TextView)
view.findViewById(R.id.textView_name);
final Button favoritebutton = (Button) view.findViewById(R.id.tgbFav);
buttonInfo.setOnClickListener(new View.OnClickListener() {
String tag = v.getTag().toString();
if(tag != null) {
int i = Integer.parseInt(tag);
System.out.println(tag);
}
}
});
private ArrayList<String> names;
private SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");
if(favoriteItems.isEmpty())
names = new ArrayList<>();
else
names = new ArrayList<>(Arrays.asList(favoriteItems.split(",")); //Update like this
favoritebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (!names.contains(textView_name.getText())){
names.add((String) textView_name.getText());
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
}
}
else {
System.out.println(textView_name.getText() + " is already present in the Array at index " + names.indexOf(textView_name.getText()));
int currentIndex = names.indexOf(textView_name.getText());
names.remove(currentIndex);
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
}
sharedPreferences.edit().putString("FAVORITE_ITEMS", TextUtils.join(",", names)).apply();
}
});
<ToggleButton
android:id="#+id/tgbFav"
android:layout_width="30dp"
android:layout_height="30dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:textOff=""
android:layout_toLeftOf="#+id/button"
android:textOn=""/>
Mate, what i have get from your question and snippet you post is you're saving all the favourite item name in shared-preference. But as you know you get that 'FAVORITE_ITEMS' in onCreate so it will only provide you the previously added favourite item. And in your you know if your scroll list view the item get update because getView() called for every item as such your favourite item that you clicked only seems as favourite until you didn't scroll list. For showing that item you need to check your item is present in favourite items or not for that add this snippet in your getView()
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
Your code....
String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");
if (favoriteItems.contains(textView_name.getText())) {
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
} else {
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
....
}
Remember to notify list when any favouriteButton clicked.
When you scroll the ListView, the few visible view items will be reused for the entire list. If you aren't handling the getView correctly, the item that was previously used for a name without favorite will be reused for a name that is set as favorite. Hence, it will look like the favorite button gets unchecked while scrolling the ListView. You have to keep track of the favorite status of all the names and use it in getView to show the proper UI.
Now, when the favoritebutton is clicked, you are updating it's background, and updating the ArrayList "names". You need to use this ArrayList in your getView, check the current favorite status of the name, and use that to set the proper background resource for the favoritebutton in your getView.

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.

Android: Showing the listview with custom adapter - filter the arraylist

I have a peculiar problem. I am parsing a restaurant's menu card. They have it in english and in german. I have a class FoodItem as :
public class FoodItem {
private int foodClass;
private String foodType;
private String foodName;
private String foodCost;
private String hauptBeilage;
private String salat;
}
Now, I have an arraylist of fooditems downloaded using Jsoup. I separate the german and english menu using the String foodType.
I want to list german menu at the start. But, I get the english menu appended to the list as well. How should I tackle this?
My downloadThread (Jsoup) is :
public void run()
{
Log.i("downloadThread", "Inside run() - Starting getFoodItems");
getDailyGerman();
getDailyEnglish();
//Sending a message through handler here
}
In my activity, I have:
handler = new android.os.Handler() {
#Override
public void handleMessage(Message msg) {
foodItemAdapter.notifyDataSetChanged();
}
};
If I send a message through handler after getDailyGerman(); then i get a illegalstateexception saying the content of the adapter has changed, but the listview is not updated.
My Adapter code :
public FoodItemAdapter(Context context, int textViewResourceId, ArrayList<FoodItem> FoodItemArg) {
super(context, textViewResourceId, FoodItemArg);
FoodItemAdapter.foodItems = FoodItemArg;
this.setNotifyOnChange(false);
// if(FoodItemAdapter.foodItems == null)
// Log.i("Adapter", "Problem Inside Adapter Constructor");
}
//=========================public methods============================
public static ArrayList<FoodItem> getDailyEnglishFoodItems()
{
ArrayList<FoodItem> returnList = new ArrayList<FoodItem>();
for(FoodItem eachItem : FoodItemAdapter.foodItems)
{
if(eachItem.getFoodClass() == 1)
{
Log.i("Adapter" , "Adding English Daily Food : " + eachItem.getFoodName());
returnList.add(eachItem);
}
}
return returnList;
}
public static ArrayList<FoodItem> getDailyGermanFoodItems()
{
ArrayList<FoodItem> returnList = new ArrayList<FoodItem>();
for(FoodItem eachItem : FoodItemAdapter.foodItems)
{
if(eachItem.getFoodClass() == 2)
{
Log.i("Adapter" , "Adding German Daily Food : " + eachItem.getFoodName());
returnList.add(eachItem);
}
}
return returnList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
* Describes each view in the list view.
* Get the question and find the question text, timestamp and the votes.
* Show them in the textview which is a part of the listview.
*/
View v = convertView;
FoodItem foodItem =(FoodItem) FoodItemAdapter.foodItems.get(position);
if(foodItem == null)
{
Log.i("Adapter", "Null Food Item");
}
int colorPos = 0;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.fooditem_row, null);
colorPos = position % colors.length;
}
Please help as I am stuck at this point for 3 days. Thanks.
I had the same issue once I added the items and called
notifyDataSetChanged() in the UI
thread issue solved
From What I understand of your question, you want to have the English items at the top of the list then the German Items. you can do that using Collection.sort method and Using a specific comparator for the task in hand.
For example:
final List<FoodItem> combinedList = getDailyGermanFoodItems();
combinedList.addAll(getDailyEnglishFoodItems());
Collections.sort(compinedList, new FoodItemComparator());
//then you call the handler to update the adapter and the listView
handler.post(new Runnable(){
public void run(){
FoodItemAdapter adapter = new FoodItemAdapter(activity.this, layout, combinedList);
listView.setAdapter(adapter);
}});
where FoodItemComparator:
public class FoodItemComparatorimplements Comparator<FoodItem>{
public int compare(FoodItem item1, item2) {
String foodType1 = item1.getFoodType();
String foodType2 = item2.getFoodType();
if (foodType1.equals(foodType2))
return 0;
if (foodType1.equals("English"))
return 1;
if (foodType2.equals("English))
return -1;
return foodType1.compareTo(foodType2);
}
}
Assuming foodType Value is guaranteed to be German/English only.
Also you will have to have a getter funcion inside your FoodItem Class so the comparator can access it:
Class FoodItem
.......
public String getFoodType(){
return foodType;
}
EDIT
If you want to display each one alone , then store the two lists inside your activity object, then when user select a language (english / german):
FoodItemAdapter adapter = new FoodItemAdapter(activity.this, layout, germanList);
listView.setAdapter(adapter);

Updating a List View

I've been stuck with this for a long while and it's really frustrating. Basically the app starts off with a ListView containing Movie Titles, their Gross, and Year.
The user then can add a new movie, gross, and year using a different activity from the menu. The values are then returned back to the first activity and is placed at the bottom of the list.
This is where my problem begins. The first problem I had is that the app Force Closes when it's about to display the new item. Now, it doesn't want to display at all. Here's the Code:
public class Lab7_084106 extends ListActivity {
private SampleCustomAdapter adapter;
private ArrayList<MyMovies> movieList;
public static boolean Flag = false;
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
//create stuff
super.onCreate(savedInstanceState);
movieList = new ArrayList<MyMovies>();
Intent data = getIntent();
//Flag = data.getStringExtra("Flag");
String[] oldMovieList = getResources().getStringArray(R.array.movieArray);
String[] oldGrossList = getResources().getStringArray(R.array.worldwideGross);
String[] oldYearList = getResources().getStringArray(R.array.yearArray);
//if there's no new movie to display
if(!Flag){
for (int i = 0; i < oldMovieList.length; i++) {
MyMovies newMovie = new MyMovies();
newMovie.setMovie(oldMovieList[i] + "NEW");
newMovie.setGross(oldGrossList[i]);
newMovie.setYear(oldYearList[i]);
movieList.add(newMovie);
}
//adapter = new SampleCustomAdapter(movieList);
//setContentView(R.layout.row);
//setListAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Else Entered", Toast.LENGTH_SHORT).show();
int newLength = 50; //oldMovieList.length + 1;
//create new array to store the new value
String[] newMovieArray = new String[newLength];
String[] newGrossArray = new String[newLength];
String[] newYearArray = new String[newLength];
//populate the new list with the old one plus the new one
for (int i = 0; i < newLength; i++) {
if( i != newLength - 1){
newMovieArray[i] = oldMovieList[i];
newGrossArray[i] = oldGrossList[i];
newYearArray[i] = oldYearList[i];
}
else{
newMovieArray[i] = data.getStringExtra("Title");
newGrossArray[i] = data.getStringExtra("Gross");
newYearArray[i] = data.getStringExtra("Year");
}
}
//populate the old one using the new list
for (int i = 0; i < newLength; i++) {
oldMovieList[i] = newMovieArray[i];
oldGrossList[i] = newGrossArray[i];
oldYearList[i] = newYearArray[i];
}
//display stuff
for (int i = 0; i < newLength; i++) {
MyMovies newMovie = new MyMovies();
newMovie.setMovie(oldMovieList[i]);
newMovie.setGross(oldGrossList[i]);
newMovie.setYear(oldYearList[i]);
movieList.add(newMovie);
}
//adapter = new SampleCustomAdapter(movieList);
//setListAdapter(adapter);
}
adapter = new SampleCustomAdapter(movieList);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//set stuff such that Page2 sends back a result to page 1
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView t = (TextView) view.findViewById(R.id.title);
String name = (String) t.getText();
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
}
});
}
private class SampleCustomAdapter extends BaseAdapter {
private ArrayList<MyMovies> internalList;
String[] oldMovieList = getResources().getStringArray(R.array.movieArray);
String[] oldGrossList = getResources().getStringArray(R.array.worldwideGross);
String[] oldYearList = getResources().getStringArray(R.array.yearArray);
private ArrayList<MyMovies> GetSearchResults(){
ArrayList<MyMovies> results = new ArrayList<MyMovies>();
// make sure the arrays have the same length
for (int i = 0; i < oldMovieList.length; i++) {
MyMovies sr = new MyMovies();
sr.setMovie(oldMovieList[i]);
sr.setGross(oldGrossList[i]);
sr.setYear(oldYearList[i]);
results.add(sr);
}
return results;
}
public SampleCustomAdapter(ArrayList<MyMovies> contacts){
internalList = contacts;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return internalList.size();
}
#Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return internalList.get(index);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// NOTE: you can only do this if you have access to the Activity object
// which is why this is an inner class
LayoutInflater inflater = getLayoutInflater();
View view;
//System.out.println(parent.getClass().getName());
//System.out.println(position);
if (convertView==null){
view = inflater.inflate(R.layout.row, null);
}
else{
view = convertView;
}
// extract the views to be populated
TextView movie = (TextView) view.findViewById(R.id.title);
TextView gross = (TextView) view.findViewById(R.id.gross);
TextView date = (TextView) view.findViewById(R.id.date);
// extract the object that will fill these
MyMovies movies = GetSearchResults().get(position);
//MyMovies movies = internalList.get(position);
movie.setText(movies.getMovie());
gross.setText(movies.getGross());
date.setText(movies.getYear());
// return the view
return view;
}
}
//menu lawl
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menupage1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection using item.getItemId()
switch(item.getItemId()){
case R.id.addMovie:
AddMovie();
break;
}
return true;
}
//end menu stuff lol
public void AddMovie(){
Intent intent2 = new Intent(this, com.Android.Lab7.addMovie.class);
startActivity(intent2);
finish();
}
}
The Flag Boolean variable basically tells if the user added a movie. If the user added a movie, it will enter the else statement and update from there. I'm really confused where to put this if-else statement.
I ran a few experiments with the GetSearchResult function of SampleCustomAdapter and found out that it directly affects the output of the ListView. I tried placing the if-else statement there but I ended up with a LOT of items in the ListView.
Using adapter.notifyDataSetChanged(); gives a NullPointerException error and points to where I placed it. So even if do something like:
MyMovies newMovie = new MyMovies();
newMovie.setMovie(data.getStringExtra("Title"));
newMovie.setGross(data.getStringExtra("Gross"));
newMovie.setYear(data.getStringExtra("Year"));
movieList.add(newMovie);
adapter.notifyDataSetChanged();
As the else block, it does not work. I think it has something to do with the fact that I'm getting my initial values from the string.xml resource folder and not via hardcode or user input.
This problem has been frustrating me ever since 2-3 days ago and help is really appreciated. Thanks.
you just have to notify the data set Changed on your adapter
movieList.add(newMovie);
adapter.notifyDataSetChanged();
the listview will be updated automatically
UPDATE
you can always use the following it'll work but I prefer notifying the adapter.
movieList.add(newMovie);
adapter = new SampleCustomAdapter(movieList);
setListAdapter(adapter);
you should use adapter.notifyDataSetChanged(). CheckThis Link

getView not getting called?

I have an adapter that extends simplecursoradapter. The new view is supposed to take a cursor from a database along with an image, populate a list with a couple of checkboxes. For some reason I can't seem to see, my getView is not even being called. I have a breakpoint inside getView and it never gets there and the list just shows up empty.
Can anyone take a look thru and see what I've done wrong
public class TakeStudentAttendance extends ListActivity {
private gradeBookDbAdapter mDbHelper;
private Long mRowId;
private TextView mNameText;
private String classname;
private Boolean new_attendance = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor stud;
mDbHelper = new gradeBookDbAdapter(this);
mDbHelper.open();
mRowId = (savedInstanceState == null) ? null
: (Long) savedInstanceState
.getSerializable(gradeBookDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras
.getLong(gradeBookDbAdapter.KEY_ROWID) : null;
}
// pull in class data
stud = mDbHelper.fetchClass(mRowId);
startManagingCursor(stud);
classname = stud.getString(
stud.getColumnIndexOrThrow(gradeBookDbAdapter.KEY_CLASSNAME));
String title = "Attendance for " + classname;
setTitle(title);
setContentView(R.layout.attendance_list);
Button doneButton = (Button) findViewById(R.id.Done);
doneButton.setOnClickListener(mAttendanceActivity);
// check previous attendance date
String prevdate = stud.getString(
stud.getColumnIndexOrThrow(gradeBookDbAdapter.KEY_PREVDATE));
stud = mDbHelper.fetchAttendanceByClass(mRowId); // this query yields _id, name,
// attend, late, dtime
if (mDbHelper.getClassDate() == prevdate){
// previous date is the same, so we're doing attendance again: retain values
new_attendance = false;
}
else {
// dates are different, so we're starting from scratch and all students are
// absent until counted present. I just need names and will populate attendance
new_attendance = true;
// upon attendance start-up, NO ONE is present. Set all entries in DB to not present (0)
setNoAttend(stud, mRowId);
// reset cursor position
stud.moveToFirst();
}
// Create an array to specify the fields we want to display in the list
String[] from = new String[]{gradeBookDbAdapter.KEY_NAME,
gradeBookDbAdapter.KEY_ROWID,
gradeBookDbAdapter.KEY_ATTEND,
gradeBookDbAdapter.KEY_LATE,
gradeBookDbAdapter.KEY_DTIME};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.stuname,
R.id.stuIndex,
R.id.attend,
R.id.late,
R.id.stuIndex};
// Now create a simple cursor adapter and set it to display
// mRowId holds the class index.
MyDataAdapter studs =
new MyDataAdapter(this, R.layout.show_attendance, stud, from, to, mRowId, new_attendance);
setListAdapter(studs);
}
Here's my adapter code:
public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
private Long classnum;
private gradeBookDbAdapter mDbHelper;
private Boolean newValues;
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<Boolean> itemCheckedHere = new ArrayList<Boolean>();
private ArrayList<Boolean> itemCheckedLate = new ArrayList<Boolean>();
private ArrayList<Integer> itemCheckedIdx = new ArrayList<Integer>();
int idxCol;
int idx;
// itemChecked will store the position of the checked items.
public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, Long mRowId, Boolean new_attendance) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
mDbHelper = new gradeBookDbAdapter(context);
mDbHelper.open();
classnum = mRowId;
newValues = new_attendance;
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
itemCheckedHere.add(i, false); // initializes all items value with false
itemCheckedLate.add(i, false); // initializes all items value with false
}
}
public View getView(final int pos, View inView, ViewGroup parent) {
File file;
ImageView studentPhoto;
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(R.layout.show_attendance, null);
}
// set up name field
final TextView studentName = (TextView) inView.findViewById(R.id.stuname);
final TextView studentIndex = (TextView) inView.findViewById(R.id.stuIndex);
if (studentName != null)
{
c.moveToPosition(pos);
int index = c.getColumnIndex(gradeBookDbAdapter.KEY_NAME);
String name = c.getString(index);
studentName.setText(name);
index = c.getColumnIndex(gradeBookDbAdapter.KEY_STUDENT);
String Index = c.getString(index);
studentIndex.setText(Index);
// set up photo icon
file = new File(Environment.getExternalStorageDirectory () +
"/gradeBook/" + name + ".jpg");
studentPhoto = (ImageView) inView.findViewById(R.id.icon);
if (file.exists()) {
String fileName = file.getAbsolutePath();
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm;
bm = BitmapFactory.decodeFile(fileName, opts);
studentPhoto.setImageBitmap(bm);
}
else {
// use icon image
studentPhoto.setImageResource(R.drawable.person_icon);
}
}
final CheckBox cBoxH = (CheckBox) inView.findViewById(R.id.attend);
final CheckBox cBoxL = (CheckBox) inView.findViewById(R.id.late);
cBoxH.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.attend);
if (cb.isChecked()) {
itemCheckedHere.set(pos, true);
int Index = new Integer(studentIndex.getText().toString());
mDbHelper.insertAttend(Index, classnum, 1 );
} else if (!cb.isChecked()) {
itemCheckedHere.set(pos, false);
int Index = new Integer(studentIndex.getText().toString());
mDbHelper.deleteAttend(Index, classnum );
}
}
});
cBoxL.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.late);
if (cb.isChecked()) {
itemCheckedLate.set(pos, true);
// do some operations here
} else if (!cb.isChecked()) {
itemCheckedLate.set(pos, false);
// do some operations here
}
}
});
cBoxH.setChecked(itemCheckedHere.get(pos)); // this will Check or Uncheck the
cBoxL.setChecked(itemCheckedLate.get(pos)); // this will Check or Uncheck the
// CheckBox in ListView
// according to their original
// position and CheckBox never
// loss his State when you
// Scroll the List Items.
return inView;
}
}
This got answered in the comment, but it might as well get a real answer ^^
getCount() is actually returning 0, so the problem is in the query coming back empty, and not in the adapter.
There can be another reason, why getView is never called. In my case I had two elements in LinearLayout - TextView and ListView. The attribute layout_height of TextView was set to fill_parent and ListView element was out of screen bounds because of this. As getView method is called only when ListView item becomes visible to user, so it has never been called. Changing layout_height property to wrap_content solved this problem.
Another thing is to make sure you have called setContentView() with the appropriate argument.

Categories

Resources