I Declared
HeaderListView list;
I try to implement search bar. all are fine but this line show error. I am not using listview I used list
here is the line
list.setTextFilterEnabled(true);
What I have to do here?..
Thanks in advance
list = new HeaderListView(this);
list.setAdapter(new SectionAdapter() {
#Override
public int numberOfSections() {
return aStatesDetails.size();
}
#Override
public int numberOfRows(int section) {
return aStatesDetails.get(section).getCoursesDetails().size();
}
#Override
public Object getRowItem(int section, int row) {
return null;
}
#Override
public boolean hasSectionHeaderView(int section) {
return true;
}
#Override
public View getRowView(int section, int row, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null ) {
//Log.i("section Details","value : "+ section + " data : " + si + " view created");
convertView = SearchGolfCourseActivity.this.getLayoutInflater().inflate(R.layout.searchcourse_adapter, null);
holder = new ViewHolder();
holder.mTextView_CourseName = (TextView) convertView.findViewById(R.id.mTextView_CourseName);
holder.mTextView_Update = (TextView) convertView.findViewById(R.id.mTextView_Update);
holder.mTextView_CourseName.setPadding(dScreenSizeWidth/50, dScreenSizeHeight/50, dScreenSizeWidth/50, dScreenSizeHeight/50);
holder.mTextView_Update.setPadding(0, dScreenSizeHeight/50, dScreenSizeWidth/50, dScreenSizeHeight/50);
/*holder.mTextView_Update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
int getSection = (Integer) view.getTag(R.id.mTextView_CourseName);
int getPosition = (Integer) view.getTag(R.id.mTextView_Update);
Log.v("Item Clicked", getSection + " " + getPosition);
}
});*/
convertView.setTag(holder);
convertView.setTag(R.id.mTextView_CourseName, holder.mTextView_CourseName);
convertView.setTag(R.id.mTextView_Update, holder.mTextView_Update);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(holder.mTextView_CourseName != null)
{
holder.mTextView_CourseName.setText(aStatesDetails.get(section).getCoursesDetails().get(row).getCourseName());
holder.mTextView_CourseName.setTag(aStatesDetails.get(section).getCoursesDetails().get(row).getCourseId());
}
if(holder.mTextView_Update != null)
if(aStatesDetails.get(section).getCoursesDetails().get(row).getDownloadStatus())
{
holder.mTextView_CourseName.setTextColor(Color.parseColor("#FF0000"));
holder.mTextView_Update.setVisibility(View.VISIBLE);
holder.mTextView_Update.setText("Update");
holder.mTextView_Update.setTag(R.id.mTextView_CourseName, section);
holder.mTextView_Update.setTag(R.id.mTextView_Update, row);
}
else
{
holder.mTextView_CourseName.setTextColor(Color.parseColor("#000000"));
holder.mTextView_Update.setVisibility(View.GONE);
}
return convertView;
}
#Override
public int getSectionHeaderViewTypeCount() {
return 2;
}
#Override
public int getSectionHeaderItemViewType(int section) {
return section % 2;
}
#Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = (TextView) getLayoutInflater().inflate(getResources().getLayout(android.R.layout.simple_list_item_1), null);
}
((TextView) convertView).setText(aStatesDetails.get(section).getStateName());
convertView.setBackgroundColor(getResources().getColor(R.color.holo_brown_light));
return convertView;
}
#Override
public void onRowItemClick(AdapterView<?> parent, View view, final int section, final int row, long id) {
super.onRowItemClick(parent, view, section, row, id);
boolean isDownloaded = aStatesDetails.get(section).getCoursesDetails().get(row).getDownloadStatus();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SearchGolfCourseActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Info");
// Setting Dialog Message
if(isDownloaded)
alertDialog.setMessage("This course has been already downloaded. Do you want to update this course?");
else
alertDialog.setMessage("Do you want to download this course?");
// Setting alert dialog icon
alertDialog.setIcon(R.drawable.tab_info_light);
// On pressing Yes button
alertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//StandardRouteFinderActivity.mapObject.redrawMap();
dialog.cancel();
String courseId = aStatesDetails.get(section).getCoursesDetails().get(row).getCourseId();
String courseName = aStatesDetails.get(section).getCoursesDetails().get(row).getCourseName();
new MyAsyncTaskDownloadCourse().execute(courseId, courseName);
}
});
// on pressing No button
alertDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
Toast.makeText(SearchGolfCourseActivity.this, "Section " + section + " Row " + row, Toast.LENGTH_SHORT).show();
}
});
list.setTextFilterEnabled(true);
mCourseListRelativeLayout.addView(list);
As it pointed in official documentation your adapter should implements Filterable interface, only than you can use list.setTextFilterEnabled(true). Does your SectionAdapter implement it? If not, try to do it.
I am using through edit text,hope this will help you !
inputSearch = (EditText)findViewById(R.id.inputSearch);
ListView lv = getListView();
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
youractivityname.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Use Edittext for Filter data from Listview.
here what i have done in my Adapter class and in my activity to filter data:
Adapter Class
public class FindAProfessorAdapter extends ArrayAdapter<Data> implements
Filterable {
int layoutResourceId;
LayoutInflater mInflater;
ArrayList<Data> list;
ArrayList<Data> secondlist;
Context context;
Data data;
public FindAProfessorAdapter(Context context, int layoutResourceId,
ArrayList<Data> data) {
super(context, layoutResourceId, data);
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
list = new ArrayList<Data>();
secondlist = new ArrayList<Data>();
secondlist.addAll(data);
list.addAll(secondlist);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.list = data;
getFilter();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView
.findViewById(R.id.findproname);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(list.get(position).getName());
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<Data>) results.values;
notifyDataSetChanged();
clear();
for (int i = 0; i < list.size(); i++) {
add(list.get(i));
notifyDataSetChanged();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<Data> FilteredArrList = new ArrayList<Data>();
if (secondlist == null) {
secondlist = new ArrayList<Data>(list);
}
if (constraint != null && constraint.toString().length() != 0) {
constraint = constraint.toString().toLowerCase(
Locale.getDefault());
for (int i = 0; i < list.size(); i++) {
Data name = secondlist.get(i);
if (name.getName().toLowerCase(Locale.getDefault())
.contains(constraint)) {
FilteredArrList.add(name);
}
}
filterResults.count = FilteredArrList.size();
filterResults.values = FilteredArrList;
} else {
synchronized (this) {
filterResults.count = secondlist.size();
filterResults.values = secondlist;
}
}
return filterResults;
}
};
return filter;
}
class ViewHolder {
TextView textView;
}
}
In my Activity:
editText = (EditText) view.findViewById(R.id.findaprofessor);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
You need to use this as a example and edit your adapter according to this.
Related
so i want to set the color to red when stok <= limit, looks normal onbindviewholder. But when performing searching, the first row data when the search delete, it turns red. any solution?first load,search the text with red one,after searching, first data went red
Context context;
List<Obat> obatList;
List<Obat> obatTempList;
int limit, stok;
public ObatAdapter(Context context, List<Obat> TempList) {
this.obatList = TempList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.obat_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Obat obat = obatList.get(position);
holder.qty.setText(obat.getStok());
holder.nama.setText(obat.getNama());
holder.harga.setText("Rp. " + obat.getHarga());
holder.satuan.setText(obat.getSatuan());
limit = Integer.parseInt(obat.getLimit());
stok = Integer.valueOf(obat.getStok());
if (stok <= limit) {
holder.onklik.setBackgroundColor(Color.parseColor("#f44242"));
}
holder.onklik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainTouchMenu.class);
i.putExtra("nama", obat.getNama().toString());
i.putExtra("stok", obat.getStok().toString());
i.putExtra("harga", obat.getHarga().toString());
i.putExtra("satuan", obat.getSatuan().toString());
i.putExtra("limit", obat.getLimit().toString());
context.startActivity(i);
}
});
holder.onklik.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent i = new Intent(context, MainHoldMenu.class);
i.putExtra("nama", obat.getNama().toString());
i.putExtra("stok", obat.getStok().toString());
i.putExtra("harga", obat.getHarga().toString());
i.putExtra("satuan", obat.getSatuan().toString());
i.putExtra("limit", obat.getLimit().toString());
context.startActivity(i);
return false;
}
});
}
#Override
public int getItemCount() {
return obatList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final List<Obat> results = new ArrayList<Obat>();
if (obatTempList == null) {
obatTempList = obatList;
}
if (constraint != null) {
if (obatTempList != null & obatTempList.size() > 0) {
for (final Obat obat : obatTempList) {
if (obat.getNama().toLowerCase().contains(constraint.toString())) {
results.add(obat);
}
}
}
oReturn.values = results;
}
return oReturn;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
obatList = (List<Obat>) results.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView nama, harga, qty, satuan;
RelativeLayout onklik;
public MyViewHolder(View itemView) {
super(itemView);
nama = itemView.findViewById(R.id.nama);
harga = itemView.findViewById(R.id.harga);
qty = itemView.findViewById(R.id.qty);
onklik = itemView.findViewById(R.id.onklik);
satuan = itemView.findViewById(R.id.satuan);
}
}
try this way
int statuscolor = 0;
if (stok <= limit) {
statuscolor = Color.parseColor("#f44242");
}
then set the color in itemView Background
holder.itemView.setBackgroundColor(statuscolor);
I have not tested this code let me know if it works
import com.example.mis_internee.atendence_app_android.R;
public class EMP_LEAVE_ADAPTER extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemname;
public EMP_LEAVE_ADAPTER(Activity context, String[] itemname) {
super(context, R.layout.mylist, itemname);
// TODO Auto-generated constructor stub
this.context = context;
this.itemname = itemname;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.emp_leave_adpater_layout, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView image=(ImageView)rowView.findViewById(R.id.icon);
txtTitle.setText(itemname[position]);
return rowView;
};
}
You need to return different view and also you need to recycle the view manually as follows:
public View getView(int position, View view, ViewGroup parent) {
ViewHolder viewHolder;
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.emp_leave_adpater_layout, null,true);
viewHolder.txtTitle = (TextView) rowView.findViewById(R.id.item);
viewHolder.image=(ImageView)rowView.findViewById(R.id.icon);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.txtTitle.setText(itemname[position]);
return viewHolder;
};
public class viewholder {
public TextView txtTitle;
public ImageView image;
}
You have to implement filter class in your custom adapter and call this method from your class, have look
in your adapter :
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
Now in your activity where edittext is defined :
editTxt.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
mSearchableAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
change according to your requirement, hope it will help you!!
I am a newbie in android app development and I am following this tutorial to create an image gallery.
https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/.
It's working perfectly but now I want to display images in ViewPager for being able to display images by swiping left/right.I am using an adapter for doing it.
I have tried doing it but its not working I dont know why.I am not able to swipe images. Can anyone help me with it ? Am i using correct path for the images?
This project is available on github here :
https://github.com/avi003/MyApp0-master-master
ImageGallery.java:
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView)findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(ImageGallery.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale( ImageGallery.this,
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions( ImageGallery.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(ImageGallery.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
PhotosActivity.java:
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gridView = (GridView)findViewById(R.id.gv_folder);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images,int_position);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String abc = "file://" + al_images.get(int_position).getAl_imagepath().get(position);
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
i.putExtra("abc",abc);
startActivity(i);
}
});
}
}
GridViewAdapter.java:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Adapter_PhotosFolder.java:
public class Adapter_PhotosFolder extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
public Adapter_PhotosFolder(Context context, ArrayList<Model_images> al_menu) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.size() + "");
return al_menu.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.size() > 0) {
return al_menu.size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setText(al_menu.get(position).getStr_folder());
viewHolder.tv_foldersize.setText(al_menu.get(position).getAl_imagepath().size()+"");
Glide.with(context).load("file://" + al_menu.get(position).getAl_imagepath().get(0))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Model_images.java:
public class Model_images {
String str_folder;
ArrayList<String> al_imagepath;
public String getStr_folder() {
return str_folder;
}
public void setStr_folder(String str_folder) {
this.str_folder = str_folder;
}
public ArrayList<String> getAl_imagepath() {
return al_imagepath;
}
public void setAl_imagepath(ArrayList<String> al_imagepath) {
this.al_imagepath = al_imagepath;
}
}
FullImageActivity.java:
public class FullImageActivity extends AppCompatActivity {
ImageView images;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
images = (ImageView) findViewById(R.id.fullImage);
// Selected image id
position = i.getExtras().getInt("id");
Bundle extras = getIntent().getExtras();
String value = extras.getString("abc");
Glide.with(FullImageActivity.this)
.load(value)
.skipMemoryCache(false)
.into(images);
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new TouchImageAdapter(this,al_images));
}
}
activity_full_image.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/jazzy_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/fullImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="centerCrop"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
TouchImageAdapter.java:
class TouchImageAdapter extends PagerAdapter {
Context context;
String filename;
ArrayList<Model_images> al_menu = new ArrayList<>();
int position,int_position;
public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu){
this.al_menu = al_menu;
this.context = context;
}
#Override
public int getCount() {
return al_menu.size();
}
#Override
public View instantiateItem(ViewGroup container, int position) {
ImageView img = new ImageView(container.getContext());
img.setImageDrawable(getImageFromSdCard(filename,position));
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public Drawable getImageFromSdCard(String imageName,int position) {
Drawable d = null;
try {
String path = al_menu.get(int_position).getAl_imagepath().get(position)
+ "/";
Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
+ ".jpeg");
d = new BitmapDrawable(context.getResources(),bitmap);
} catch (IllegalArgumentException e) {
// TODO: handle exception
}
return d;
}
}
Here you are not passing count of images inside that folder, So in TouchImageAdapter you have passing the count of folder like :
al_menu.size() // it always give you size of folder,
al_menu.get(int_position).getAl_imagepath().size();
// passing the folder position so that correct folder images are to be shown.
public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu, int position){
this.al_menu = al_menu;
this.context = context;
this.int_position = position;
}
#Override
public int getCount() {
return al_menu.get(int_position).getAl_imagepath().size();
}
Here is the updated code I pushed on
https://github.com/redviper00/game
try this
String[] filenames = new String[0];
File path = new File(Environment.getExternalStorageDirectory() + "/your folder");
if (path.exists()) {
filenames = path.list();
}
for (int i = 0; i < filenames.length; i++) {
imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", imagesPathArrayList.get(i));
adapter = new ImageAdapter(FavActivity.this, imagesPathArrayList);
myviewpager.setAdapter(adapter);
}
create adapter class like this
public class ImageAdapter extends PagerAdapter {
Context context;
ArrayList<String> arrayList;
ImageAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
viewPagerImageView = new ImageView(context);
viewPagerImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap bitmap = BitmapFactory.decodeFile(arrayList.get(position));
viewPagerImageView.setImageBitmap(bitmap);
((ViewPager) container).addView(viewPagerImageView, 0);
return viewPagerImageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
It seems like you are showing Imageview above view pager
images = (ImageView) findViewById(R.id.fullImage);
that is why when you are trying to swipe imageview handle your tocuh action instead of view pager. Remove it.
I have a listview and an editText to filter data. It filters data correctly but e.g, if I filter list and open filtered item it shows me the data of item which was at index 0 of original list not that of filtered item.
My Adapter class:
public class Patient_Adapter extends BaseAdapter implements Filterable{
Activity context;
String[] name, age, number, dip_rate;
//for filtering use arraylists
LayoutInflater inflater;
private ValueFilter valueFilter;
ArrayList<ArrayList_get_set> arrayList;
private ArrayList<ArrayList_get_set> StringFilterList;
public Patient_Adapter(Activity applicationContext, ArrayList<ArrayList_get_set> arrayList) {
this.context = applicationContext;
/////
this.arrayList = arrayList;
StringFilterList = arrayList;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getFilter();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return arrayList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
private class Viewholder{
TextView name_
,date_
,number_
,dip_rate_
,tv_request_number;
Button button;
}
#Override
public View getView(final int position, View view, final ViewGroup viewGroup) {
Viewholder viewholder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null){
viewholder = new Viewholder();
view = inflater.inflate(R.layout.patient_item_list,null);
viewholder.tv_request_number = (TextView) view.findViewById(R.id.s_req_num);
viewholder.name_ = (TextView) view.findViewById(R.id.name);
viewholder.button = (Button) view.findViewById(R.id.btn_re);
viewholder.date_ = (TextView) view.findViewById(R.id.date);
view.setTag(viewholder);
}
else {
viewholder = (Viewholder) view.getTag();
}
viewholder.tv_request_number.setText((arrayList.size()-position)+".");
viewholder.name_.setText(arrayList.get(position).getName());
viewholder.date_.setText(getDate(Long.parseLong(arrayList.get(position).getDate())));
viewholder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView)viewGroup).performItemClick(v,position,1);
}
});
return view;
}
//Filter Results
#Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length()>0){
ArrayList<ArrayList_get_set> filterList = new ArrayList<>();
for(int i=0;i<StringFilterList.size();i++){
if((StringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ArrayList_get_set contacts = new ArrayList_get_set();
contacts.setName(StringFilterList.get(i).getName());
contacts.setDate(StringFilterList.get(i).getDate());
filterList.add(contacts);
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=StringFilterList.size();
results.values=StringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
arrayList = (ArrayList<ArrayList_get_set>) results.values;
notifyDataSetChanged();
}
}
This my main activity code
simListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id == 1){
//CUSTOM DIALOG///////////////////////////////
final Dialog dialog = new Dialog(getActivity());
dialog.setCanceledOnTouchOutside(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_re_evaluate);
name_ = (TextView) dialog.findViewById(R.id.name);
f_name_ = (TextView) dialog.findViewById(R.id.f_name);
age_ = (TextView) dialog.findViewById(R.id.age);
number_ = (TextView) dialog.findViewById(R.id.number);
gender_ = (TextView) dialog.findViewById(R.id.gender);
dip_rate_ = (TextView) dialog.findViewById(R.id.dip_rate);
date_ = (TextView) dialog.findViewById(R.id.date);
name_.setText(name[position]);
f_name_.setText(f_name[position]);
age_.setText(age[position]);
number_.setText(number[position]);
dip_rate_.setText(dip_rate[position]);
gender_.setText(gender[position]);
date_.setText(getDate(Long.parseLong(date[position])));
Button re_eval = (Button) dialog.findViewById(R.id.btn);
Button btn_cross = (Button) dialog.findViewById(R.id.cross);
btn_cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
re_eval.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p_name = name_.getText().toString();
p_f_name = f_name_.getText().toString();
p_age = age_.getText().toString();
p_number = number_.getText().toString();
p_dip_rate = dip_rate_.getText().toString();
p_gender = gender_.getText().toString();
p_date = date_.getText().toString();
//go from one fragment to another
Fragment fragment = null;
//send data to next fragment
Bundle bundle = new Bundle();
bundle.putString("name", p_name);
bundle.putString("f_name", p_f_name);
bundle.putString("age", p_age);
bundle.putString("number", p_number);
bundle.putString("dip_rate", p_dip_rate);
bundle.putString("gender", p_gender);
bundle.putString("date", p_date);
fragment = new Questions();
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment.setArguments(bundle);
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
dialog.dismiss();
}
});
dialog.show();
}
}
});
performing filtering here
protected void onPostExecute(String s) {
progressDialog.dismiss();
if (server_check) {
if (server_response.equals("1")) {
if (name.length > 0) {
patient_adapter = new Patient_Adapter(getActivity(),
arrayList);
simListView.setAdapter(patient_adapter);
//filtering data
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
patient_adapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
My code is working fine when it comes to clicking items. But the problem arises when I try to open activities after filtering listview. It always opens activity 1.
Here is my source code.
navigate.java
public class navigate extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] names;
int[] flag;
ArrayList<Object> arraylist = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Generate sample data
rank = new String[] { "1", "2", "3", "4", "5","6","7","8","9","10","11"};
names = new String[] { "Animal Bite", "Asthma Attack", "Choking","CPR","Black eye",
"Drowning", "Fracture","Heart Attack","Insect Bite","Poisoning","Spinal Injury",};
flag = new int[] { R.drawable.animal,
R.drawable.asthma, R.drawable.choke, R.drawable.cpricon,
R.drawable.blckeye,R.drawable.drown,R.drawable.fracture,R.drawable.hrtattck,R.drawable.insect,R.drawable.poison,R.drawable.spinal };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
Object wp = new Object(rank[i], names[i], flag[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> listView, View view,
final int position, long id) {
switch ((int) adapter.getItemId(position)) {
case 0:
Intent newActivity = new Intent(navigate.this, animalbite.class);
startActivity(newActivity);
break;
case 1:Intent newActivity1 = new Intent(navigate.this, asthmaattack.class);
startActivity(newActivity1);
break;
case 2:Intent newActivity2 = new Intent(navigate.this, animalbite.class);
startActivity(newActivity2);
break;}
}
});
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Object> objectList = null;
private ArrayList<Object> arraylist;
public ListViewAdapter(Context context,
List<Object> objectList) {
mContext = context;
this.objectList = objectList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Object>();
this.arraylist.addAll(objectList);
}
public class ViewHolder {
TextView name;
ImageView flag;
}
#Override
public int getCount() {
return objectList.size();
}
#Override
public Object getItem(int position) {
return objectList.get(position);
}
public String getCountry(int position){return objectList.get(position).getCountry();}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
//holder.rank = (TextView) view.findViewById(R.id.rank);
holder.name = (TextView) view.findViewById(R.id.name);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(objectList.get(position).getRank());
holder.name.setText(objectList.get(position).getCountry());
;
// Set the results into ImageView
holder.flag.setImageResource(objectList.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
// Pass all data rank
// Start SingleItemView Class
switch (position) {
case 0:
Intent intent = new Intent(mContext, animalbite.class);
mContext.startActivity(intent);break;
case 1:
Intent i2 = new Intent(mContext, asthmaattack.class);
mContext.startActivity(i2);break;
case 2:
Intent i3 = new Intent(mContext, choking.class);
mContext.startActivity(i3);break;
case 3:
Intent i4 = new Intent(mContext, cpr.class);
mContext.startActivity(i4);break;
case 4:
Intent i5 = new Intent(mContext, lackeye.class);
mContext.startActivity(i5);break;
case 5:
Intent i6 = new Intent(mContext, drowning.class);
mContext.startActivity(i6);break;
case 6:
Intent i7 = new Intent(mContext, Fracture.class);
mContext.startActivity(i7);break;
case 7:
Intent i8 = new Intent(mContext, heartattack.class);
mContext.startActivity(i8);break;
case 8:
Intent i9 = new Intent(mContext, insectbite.class);
mContext.startActivity(i9);break;
case 9:
Intent i10 = new Intent(mContext, poisoning.class);
mContext.startActivity(i10);break;
case 10:
Intent i11 = new Intent(mContext, spinalinjury.class);
mContext.startActivity(i11);break;
}}});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
objectList.clear();
if (charText.length() == 0) {
objectList.addAll(arraylist);
} else {
for (Object wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
objectList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Object.java
public class Object {
private String rank;
private String country;
private int flag;
public Object(String rank, String country,
int flag) {
this.rank = rank;
this.country = country;
this.flag = flag;
}
public String getCountry() {
return this.country;
}
public int getFlag() {
return this.flag;
}
}
How can I open different activities while clicking on listview items after I filter them.
This is the sample code I used. Although it doesn't provide the functionality to open original activities through intent ,just some forged up activity,so I'm trying to change that.
http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/
I think your adapter has problem, this below sample code of my application is extended from Filterable and work fine
public class AdapterContacts extends BaseAdapter implements Filterable {
private LayoutInflater inflater;
private Context context;
private List<ContactLists> categoryArrayList;
private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
private NameFilter filter;
public AdapterContacts(ArrayList<ContactLists> array) {
categoryArrayList = array;
}
public AdapterContacts(Context context, List<ContactLists> array) {
this.context = context;
inflater = LayoutInflater.from(this.context);
categoryArrayList = array;
originalList.addAll(array);
}
#Override
public int getCount() {
return categoryArrayList.size();
}
#Override
public ContactLists getItem(int position) {
return categoryArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_contacts_list_item, null);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
ContactLists item = getItem(position);
mViewHolder.fillItems(this, item, position);
return convertView;
}
private static class UI extends HelperUI {
public TextView tv_person_nickname_mobile_number;
public TextView btn_invite_message;
public ImageView img_contact_image;
public ImageView imgv_user_rank;
public TextView tv_contact_name;
public LinearLayout ll_root;
public UI(View view) {
parseUi(view);
}
}
private class ViewHolder {
private UI UI;
public ViewHolder(View view) {
UI = new UI(view);
}
public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
UI.tv_contact_name.setText(item.getContact_name());
if (item.getStatus() == 1) {
UI.btn_invite_message.setVisibility(View.GONE);
UI.imgv_user_rank.setVisibility(View.VISIBLE);
if (item.getRank() != null || !TextUtils.isEmpty(item.getRank())) {
//Picasso.with(G.context).load(item.getRank()).into(UI.imgv_user_rank);
}
UI.tv_person_nickname_mobile_number.setText(item.getNick_name());
//UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_button_actions));
if (item.getContact_image() == null || TextUtils.isEmpty(item.getContact_image())) {
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
} else {
// show user avatar from web
//Picasso.with(G.context).load(item.getContact_image()).into(UI.img_contact_image);
UI.img_contact_image.setImageBitmap(BitmapFactory.decodeFile(G.DIR_IMAGE + "/" + item.getContact_image()));
}
} else {
// UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_invite_actions));
UI.btn_invite_message.setVisibility(View.VISIBLE);
UI.imgv_user_rank.setVisibility(View.GONE);
UI.btn_invite_message.setText(UC.getString(R.string.invite_person));
UI.btn_invite_message.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.shape_invite_button_default));
UI.tv_person_nickname_mobile_number.setText(item.getMobile_number());
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new NameFilter();
}
return filter;
}
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
}