Android: Do some action AFTER filling ListView elements - android

I have an activity with listview and attached footer. I created my custom adapter for filling ListView. After I filled it I need to do some actions.
This is my activity's code part:
public class MainActivity extends ListActivity {
final public String NO_USERS_IN_DB = "No users yet, please add some...";
DBAdapter db = new DBAdapter(this);
Activity activity = MainActivity.this;
private static final Pattern PATTERN = Pattern.compile(": *([^|]+)");
private static final int REQUEST_LOAD = 0;
boolean rewrite;
boolean userSelected = false;
final public int REQUEST_SAVE = 1;
boolean showAvatars;
boolean settingsGot = false;
int backgroundColor;
int titleColor;
int buttonBackgroundColor;
int buttonTextColor;
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
if(!settingsGot){
getSettings();
settingsGot = true;
}
String[] users = getUsers();
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.main, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
label.setText(users[position]);
if(showAvatars){
ImageView icon=(ImageView)row.findViewById(R.id.icon);
byte[] bb = getAvatar(users[position]);
if(bb != null && bb.length != 0){
icon.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
icon.setVisibility(View.VISIBLE);
}
}
return row;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
db.open();
String[] users = db.getUsersList();
boolean showList = true;
if (users[0].equals("NOUSERSINTHEBASE")){
users[0] = NO_USERS_IN_DB;
}
if (showList){
View footer = getLayoutInflater().inflate(R.layout.footer, null);
ListView listView = getListView();
listView.addFooterView(footer);
this.setListAdapter(new MyCustomAdapter(this,
R.layout.main, users));
}else{
setContentView(R.layout.footer);
}
db.close();
}
So, method I need to do some actions after method getView done its work. Where should I place my doSomeMoreActionsAfterGetView() ?

After setListAdapter you can change it...

Related

Advanced search bar Crash [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to implement search in my app, and activity crashes when I click on search icon. The error is: https://i.imgur.com/CDOE9fT.png
Here is the code of Activity:
public class SearchActivity extends AppCompatActivity implements OnItemClickListener, AdapterView.OnItemClickListener {
DBHelper dbHelper;
SQLiteDatabase database;
ArrayList<Reminder> ReminderList = new ArrayList<>();
ListView listView;
MaterialSearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Material search");
toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));
dbHelper = new DBHelper(this);
database = dbHelper.getWritableDatabase();
//listView = (ListView) findViewById(R.id.ListOfReminders);
listView = (ListView)findViewById(R.id.ListOfReminders);
Cursor cursor = database.query(TABLE_REMINDERS, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
int idIndex = cursor.getInt(cursor.getColumnIndex(DBHelper.KEY_ID));
String nameIndex = cursor.getString(cursor.getColumnIndex(KEY_NAME));
String hourIndex = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_HOUR));
String dateIndex = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_DATE));
String name = nameIndex;
String hour = hourIndex;
String date = dateIndex;
ReminderList.add(new Reminder(idIndex, name, hour, date));
ReminderListAdapter2 adapter = new ReminderListAdapter2(this, R.layout.reminder_view2, ReminderList);
adapter.setListener(this);
listView.setAdapter(adapter);
} while (cursor.moveToNext());
} else
Log.d("mLog", "0 rows in db");
searchView = (MaterialSearchView)findViewById(R.id.search_view);
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
#Override
public void onSearchViewShown() {
}
#Override
public void onSearchViewClosed() {
listView = (ListView)findViewById(R.id.ListOfReminders);
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this, android.R.layout.simple_list_item_1,ReminderList);
listView.setAdapter(adapter);
}
}); searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText != null && !newText.isEmpty()){
ArrayList<Reminder> lstFound = new ArrayList<>();
for(Reminder item:ReminderList){
if(item.getName().contains(newText))
lstFound.add(new Reminder(item.getId(), item.getName(), item.getHour(), item.getDate()));
}
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this,android.R.layout.simple_list_item_1,lstFound);
listView.setAdapter(adapter);
} else {
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this,android.R.layout.simple_list_item_1,ReminderList);
listView.setAdapter(adapter);
}
return true;
}});
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_item,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void OnItemClick(View view, int position, int id, String name, String date, String hour) {
}}
Code of adapter:
public class ReminderListAdapter2 extends ArrayAdapter<Reminder> {
private Context mContext;
private int mResource;
OnItemClickListener listener;
public ReminderListAdapter2(#NonNull Context context, int resource, #NonNull ArrayList<Reminder> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
public void setListener(OnItemClickListener listener) {
this.listener = listener;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final int id = getItem(position).getId();
final String name = getItem(position).getName();
final String hour = getItem(position).getHour();
final String date = getItem(position).getDate();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
final TextView resId = convertView.findViewById(R.id.textId);
final TextView resName = convertView.findViewById(R.id.textName);
final TextView resHour = convertView.findViewById(R.id.textHour);
final TextView resDate = convertView.findViewById(R.id.textDate);
resId.setText(String.valueOf(id));
resName.setText(name);
resHour.setText(hour);
resDate.setText(date);
return convertView;
}}
Why object reference is null? Sorry if it is a stupid error, it's first app.
I tried to change lstFound.add(new Reminder(item.getId(), item.getName(), item.getHour(), item.getDate())); with lstFound.add(this);, but it is also null reference.
According to documentation:
To display a more custom view for each item in your dataset, implement a ListAdapter. For example, extend BaseAdapter and create and configure the view for each data item in
If so the first argument of layout inflater method should be layout instead of int
e.g convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
In your case you are trying to inflate int instead of layout
convertView = inflater.inflate(mResource, parent, false);
Closed.
The error was in ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this, android.R.layout.simple_list_item_1,ReminderList);
androidR.layout.simple_list_item_1 need to be changed to R.layout.reminderview2

how to get all checked value on button click from list-view in android

This is my adapter class :
public class CheckboxAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
Context context;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
ArrayList<String> selectedStrings = new ArrayList<String>();
public CheckboxAdapter(Context ctx, int viewResourceId, String[] strings) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mViewResourceId = viewResourceId;
}
public int getCount() {
return mStrings.length;
}
public String getItem(int position) {
return mStrings[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
final CheckBox tv = (CheckBox) convertView.findViewById(R.id.checkBox1);
tv.setText(mStrings[position]);
tv.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
selectedStrings.add(tv.getText().toString());
Toast.makeText(buttonView.getContext(),Boolean.toString(selectedStrings.add(tv.getText().toString())), Toast.LENGTH_SHORT).show();
} else {
selectedStrings.remove(tv.getText().toString());
}
}
});
return convertView;
}
}
This is my actvity
public class AddTime extends Activity {
CheckboxAdapter cadpter;
String daya[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday",
"Friday", "Saturday" };
ListView list;
ArrayList<String> selectedStrings = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtime);
list = (ListView) findViewById(R.id.listView1);
cadpter = new CheckboxAdapter(AddTime.this, R.layout.list_item, daya);
list.setAdapter(cadpter);
}
}
I am displaying all day in listview also i have display check box with each day when i enable check box it show true in toast but i want what ever i select day using check box i mean i want display all the day in textview in mainactvity please suggest me how i will get it .
how to get all checked value on button click from list-view in android
As adding all checked values in selectedStrings ArrayList. create a method in CheckboxAdapter class which return ArrayList of all selected values. for example :
public ArrayList<String> getAllSelectedValues(){
return this.selectedStrings;
}
Now use cadpter CheckboxAdapter class object for accessing getAllSelectedValuesmethod in Activity:
ArrayList<String> selectedStrings=cadpter.getAllSelectedValues();
get all values from selectedStrings arrayList
for(int i=0;i<=selectedStrings.sizes();i++){
String s =selectedStrings.get(i);
}
Take boolean Array
ArrayList<Boolean> selectedStrings = new ArrayList<>();
and add onClickListener in your checkbox
public View getView(final int position, View convertView, ViewGroup parent) {
-
-
tv.setChecked(false);
if(selectedStrings.size() <= position){
selectedStrings.add(position, false);
}else
tv.setChecked(selectedStrings.get(position));
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean state = selectedStrings.get(position);
selectedStrings.remove(position);
selectedStrings.add(position, state ? false : true);
}
});
}

ListView with custom adapter not getting updated

I want to update the list view whenever any item is updated or deleted.I have tried many options,but none of them is working.This is the code of the list view:
public class HelloBubblesActivity extends Activity {
private com.warting.bubbles.DiscussArrayAdapter adapter;
private ListView lv;
private LoremIpsum ipsum;
private EditText editText1;
private static Random random;
Runnable m_handlerTask;
TextView tv ;
LinearLayout ll;
Handler m_handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discuss);
lv = (ListView) findViewById(R.id.listView1);
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.listitem_discuss);
lv.setAdapter(adapter);
ll = (LinearLayout)findViewById(R.id.wrapper);
m_handler = new Handler();
addItems();
ReduceTimeIteration();
}
public void ReduceTimeIteration()
{
adapter.clear();
((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
lv.invalidate();
lv.requestLayout();
Log.d("Adapter: ", "Adapter is changed");
}
private String addItems() {
String a = "Hello bubbles";
adapter.add(new OneComment(true,a));
return a;
}
}
This is the code of the custom adapter:
public class DiscussArrayAdapter extends ArrayAdapter<OneComment> {
private TextView countryName;
private List<OneComment> countries = new ArrayList<OneComment>();
private LinearLayout wrapper;
static View row ;
#Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public DiscussArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.countries.size();
}
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listitem_discuss, parent, false);
}
wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
OneComment coment = getItem(position);
countryName = (TextView) row.findViewById(R.id.comment);
countryName.setText(coment.comment);
countryName.setBackgroundResource(coment.left ? R.drawable.bubble_yellow : R.drawable.bubble_green);
wrapper.setGravity(coment.left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
}
In the list view, i want to remove all the views using adapter.clear() and then want to update the list view.But even after calling adapter.clear() , the list view remains the same.Please help me. Thanks in advance.
I suggest you create you adapter in the following way:
// declared in activity
private List<OneComment> countries = new ArrayList<OneComment>();
// in onCreate()
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.listitem_discuss, countries);
And then call countries.clear(); adapter.notifyDataSetChanged(); to clear the list view. Because you are basically using now your "countries" (list) to tell which size the adapter has, and which item to get upon that list.

Can't fill the listView?

I have a listview, and i start an intent to fill it. But the list shows up with a default image and no text. It is supposed to show up with different images and text.
I have two arrays, one is in string type and the other one is in drawable type... But my list doesn't show me none of these that i wanted...
My ListActivity:
public class fillLeftMenu extends ListActivity {
private View menu;
ImageView findLocation;
Spinner cityList;
ListView leftList;
String [] textIndex;
Drawable [] imageIndex;
ArrayList<LeftListItems> Left;
listAdapter lAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataTransfer dt = BonubonActivity.deneme;
menu = dt.getView();
findLocation = (ImageView) menu.findViewById(R.id.image_findLocation);
leftList = (ListView) menu.findViewById(R.id.list);
// add items to listView
Left = new ArrayList<LeftListItems>();
textIndex = new String[] {"Bugünün Fırsatları", "Son Dakika Bonusları", "Kadın", "Aile", "Çocuk", "Alışveriş", "Şehirden Kaçış", "Kışa Özel"};
imageIndex = new Drawable[] {leftList.getResources().getDrawable(R.drawable.kucukicon_01),leftList.getResources().getDrawable(R.drawable.kucukicon_02),leftList.getResources().getDrawable(R.drawable.kucukicon_03),leftList.getResources().getDrawable(R.drawable.kucukicon_04),leftList.getResources().getDrawable(R.drawable.kucukicon_05),leftList.getResources().getDrawable(R.drawable.kucukicon_06),leftList.getResources().getDrawable(R.drawable.kucukicon_07),leftList.getResources().getDrawable(R.drawable.kucukicon_08)};
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);
getIndex();
lAdapter.notifyDataSetChanged();
leftList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
finish();
}
private void getIndex() {
try{
LeftListItems item = new LeftListItems();
for(int i=0; i<textIndex.length; i++) {
item.setText(textIndex[i]);
item.setImage(imageIndex[i]);
Left.add(item);
lAdapter.add(Left.get(i));
}
}
catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
}
private class listAdapter extends ArrayAdapter<LeftListItems> {
private ArrayList<LeftListItems> items;
private Context ctx;
public listAdapter(Context ctx, int textViewResourceId, ArrayList<LeftListItems> items) {
super(ctx, textViewResourceId, items);
this.ctx = ctx;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
LeftListItems index = items.get(position);
if(index != null) {
TextView text = (TextView) v.findViewById(R.id.text);
ImageView img = (ImageView) v.findViewById(R.id.icon);
if(text != null)
text.setText(index.getText());
if(img != null)
img.setBackgroundDrawable(index.getImage());
}
return v;
}
}
}
Try calling getIndex() method before creating the adapter and setting it to the list. Like this:
getIndex();
//then create new adapter
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);

Data in ListActivity not cached when going back to it

I've got a ListActivity filled by an adapter extending SimpleCursorAdapter. Some category buttons can be clicked, which fills the listview with a list of articles in the corresponding category. When clicking on an item in the list a new activity is launched which shows the detail of the article.
Now, when pressing the back button in that article detail page, no data is shown. Does it have to reload the data from the DB? Isn't the data supposed to be cached?
Moreover, when going back to the myListActivity, onCreate is not called. Only onResume is called. Shall I do everything in onResume? In that case what's the best way to keep the value of the current category and retrieve it when going back to the ListActivity from the article detail?
Thanks
public class Home extends ListActivity implements OnItemClickListener{
private DBAdapter dbAdapter;
private HomeListAdapter adapter; //extends SimpleCursorAdapter
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// open database
dbAdapter = new DBAdapter(this);
dbAdapter.open();
/* more stuff */
getArticlesbyCat(category);
/* more stuff */
}
private void getArticles(int category){
Cursor c = dbAdapter.fetchArtByCat(category);
c.moveToFirst();
startManagingCursor(c);
String[] from = new String[] {};
int[] to = new int[] {};
setListAdapter(new HomeListAdapter(this, R.layout.article_row, c, from, to));
adapter.notifyDataSetChanged();
c.close();
}
#Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
/* Go to article page */
}
#Override
protected void onPause() {
super.onPause();
// close database
dbAdapter.close();
}
}
EDIT
public class HomeListAdapter extends SimpleCursorAdapter {
private int mLayout;
private Cursor mCursor;
private Resources mResources;
// Column index
private int mCatInd;
private int mURLPicInd;
private int mIntroInd;
private int mTitleInd;
private LayoutInflater mLayoutInflater;
private final ImageDownloader mImageLoader;
private final class ViewHolder {
public TextView category;
public ImageView image;
public TextView intro;
public TextView title;
}
public HomeListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mLayout = layout;
this.mCursor = c;
this.mCatInd = mCursor.getColumnIndex(DBAdapter.KEY_CATEGORY_NAME);
this.mURLPicInd = mCursor.getColumnIndex(DBAdapter.KEY_URL_PIC);
this.mIntroInd = mCursor.getColumnIndex(DBAdapter.KEY_INTRO);
this.mTitleInd = mCursor.getColumnIndex(DBAdapter.KEY_TITLE);
this.mLayoutInflater = LayoutInflater.from(context);
mResources = context.getResources();
mImageLoader = new ImageDownloader(mResources,
((BitmapDrawable)mResources.getDrawable(R.drawable.default_row_pic)).getBitmap(), 1);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.category = (TextView) convertView.findViewById(R.id.cat);
viewHolder.image = (ImageView) convertView.findViewById(R.id.picture);
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.intro = (TextView) convertView.findViewById(R.id.intro);
viewHolder.intro.setMaxLines(3);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
String category = mCursor.getString(mCatInd);
String title = mCursor.getString(mTitleInd);
String intro = mCursor.getString(mIntroInd);
String url_pic = mCursor.getString(mURLPicInd);
viewHolder.category.setText(category);
viewHolder.title.setText(title);
viewHolder.intro.setText(intro);
if(!url_pic.equals("")){
mImageLoader.download(url_pic, (ImageView) viewHolder.image);
}
else {
viewHolder.image.setImageResource(R.drawable.default_row_pic);
}
}
return convertView;
}
}

Categories

Resources