android - How to check how many elements are present in a GridView? - android

I am dynamically adding images to a GridView.
I want to have a counter to check how many images are present in a GridView.
The purpose is to restrict the user to add maximum of "n" images.
Therefore I want to have a counter which will count this number and I will check accordingly.
public class ExistingDetailedActivity extends Activity {
public String images,audiopath,name,assignedTo;
TextView ringtonename,assigned;
public GridView gridView;
public String [] imgpath;
CustomBaseExistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_existing_detailed);
Intent i = getIntent();
if(i.hasExtra("BNDL")){
Bundle bdl = getIntent().getBundleExtra("BNDL");
if(bdl.get("IMAGEPATH") != null){
images = bdl.getString("IMAGEPATH");
}
if(bdl.get("AUDIOPATH") != null){
audiopath = bdl.getString("AUDIOPATH");
}
if(bdl.get("RINGTONENAME") != null){
name = bdl.getString("RINGTONENAME");
}
if(bdl.get("ASSIGNEDTO") != null){
assignedTo = bdl.getString("ASSIGNEDTO");
}
}
Typeface FONT_NAME = Typeface.createFromAsset(this.getAssets(), "komika-title-brush-1361511399.ttf");
imgpath=images.split("\\*") ;
ringtonename=(TextView) findViewById(R.id.textView2);
ringtonename.setText(name);
ringtonename.setTypeface(null, Typeface.BOLD);
ringtonename.setTypeface(FONT_NAME);
assigned=(TextView) findViewById(R.id.textView4);
assigned.setText(assignedTo);
assigned.setTypeface(null, Typeface.BOLD);
assigned.setTypeface(FONT_NAME);
gridView=(GridView) findViewById(R.id.gridview1);
adapter = new CustomBaseExistAdapter(this,imgpath);
//adapter.notifyDataSetChanged();
gridView.invalidateViews();
gridView.setAdapter(adapter);
}
}
Another one is
public class CustomBaseExistAdapter extends BaseAdapter{
private final Activity context;
public String[] imagepath;
private String[] imagepath1=null;
private String[] imagepathBackUp=null;
public CustomBaseExistAdapter(Activity context,
String[] imagepath) {
this.context = context;
this.imagepath = imagepath;
this.imagepathBackUp =imagepath;
List<String> nonBlank = new ArrayList<String>();
for(String s: imagepath) {
if (!s.trim().isEmpty()) {
nonBlank.add(s);
}
}
imagepath1 = (String[]) nonBlank.toArray( new String[nonBlank.size()] );
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagepath.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.custom_image_with_checkbox, null);
CheckBox cb=(CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imgThumb);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int id = buttonView.getId();
if(isChecked){
/*String newList[] = new String[imagepath.length - 1];
int count = 0;
for (int i = 0; i < imagepath.length; i++) {
if (imagepath.length - 1 > 0) {
if (imagepath[i] == imagepath1[position]) { // itemPath[1] as the range starts from 0, so 1 would be ITEM2
// SKIP IF MATCHES THE ITEM YO WANT TO REMOVE
} else {
newList[count] = imagepath[i];
count++;
}
}
}
imagepath=new String[newList.length];
imagepath= newList;*/
List<String> newlist= new ArrayList<String>(Arrays.asList(imagepath));
newlist.remove(imagepath1[position]);
imagepath=null;
imagepath = newlist.toArray(new String[newlist.size()]);
/*new String[newlist.size()];
for(int j =0;j<newlist.size();j++){
imagepath[j] = newlist.get(j);
}*/
notifyDataSetChanged();
}
}
});
imageView.setImageBitmap(BitmapFactory.decodeFile(imagepath[position]));
}
return convertView;
}
}

To know number of Elements in GridView, here ,
put int count = (position + 1); in your GridView Adapter getView(..) method. It is callback method, called number of times to populate your Gridview. Starts from 0.
int count = 0; // define count as global instance var.
public View getView(final int position, View convertView, ViewGroup parent){
...
count = position + 1;
...
}
count is what you want.

Related

Custom listview adapter with a chronometer refreshes when scrolled

I have created a custom listview adapter to fit a button, a custom chronometer and a textview. When i scroll my listview, the rows that are "hidden" refresh themselves and so chronometers, how can i keep chronometers running even if they're hidden?
I am quite new to Android development so i may have done something wrong; I know that listview refresh its rows when scrolled but maybe there's something that i missed to make chronometers running in background
public class MyCustomAdapter extends BaseAdapter {
ArrayList<String> users;
Context context;
LayoutInflater inflater = null;
public MyCustomAdapter(Activity mainActivity, ArrayList<String> usersList) {
// TODO Auto-generated constructor stub
users = usersList;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return users.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return users.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
private class Holder {
TextView tv;
CustomChrono cr;
Button but;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.customized_list_view, null);
holder.tv = (TextView) rowView.findViewById(R.id.names_laps);
holder.cr = (CustomChrono) rowView.findViewById(R.id.chronometer_laps);
holder.but = (Button) rowView.findViewById(R.id.stop_button);
holder.cr.start();
holder.but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//((ListView) parent).performItemClick(v, position, 0);
holder.cr.stop();
stopped = true;
}
});
holder.tv.setText(users.get(position));
rowView.setTag(holder);
return rowView;
}
}
Then I have my activity class where I use this adapter
public class RunnerLaps extends AppCompatActivity {
ListView list;
ArrayList<String> runner_array;
private Map<Runner,String> map = new HashMap<Runner,String>(10);
private boolean isClicked = true;
private boolean isStartedNow = false;
boolean stopped = false;
ArrayList<Runner> arr_runners;
ArrayList<Runner> runners_arrList;
private long previousClickTime1 = 0;
Runner r = null;
String m = "";
SerializableManager serializableManager;
String filename = "myfile";
FileOutputStream outputStream = null;
ObjectOutputStream objectOutputStream = null;
//Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_laps);
Intent i = getIntent();
serializableManager = new SerializableManager();
runner_array = (ArrayList<String>) getIntent().getSerializableExtra("KEY");
ArrayList<Runner> running = getIntent().getExtras().getParcelableArrayList("arr2");
runners_arrList = new ArrayList<Runner>(runner_array.size());
for (String r : runner_array)
{
runners_arrList.add(new Runner(r));
}
for (int f = 0; f < runners_arrList.size();f++)
{
Log.d("Runner: " + f,runners_arrList.get(f).getName());
}
m = getIntent().getExtras().getString("booly");
for (int j = 0; j < runner_array.size(); j++) {
Runner r = new Runner(runner_array.get(j));
map.put(r, runner_array.get(j));
}
if (m!= null)
{
stopped = true;
}
list = (ListView) findViewById(R.id.laps_list);
final MyCustomAdapter adapter = new MyCustomAdapter(RunnerLaps.this,runner_array);
list.setAdapter(adapter);
//addRunners();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomChrono chr = (CustomChrono) view.findViewById(R.id.chronometer_laps);
r = runners_arrList.get(position);
r.setTemp(System.currentTimeMillis());
long temp = r.getTemp();
previousClickTime1 = temp;
if (previousClickTime1 != 0 && previousClickTime1 - temp < 300)
{
if (stopped == true)
{
chr.stop();
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
Intent i = new Intent (RunnerLaps.this,Runner_Display.class);
i.putExtra("key",(Serializable) r);
i.putParcelableArrayListExtra("arr",arr_runners);
for (int h = 0; h < runners_arrList.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
startActivity(i);
}
else
{
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
for (int h = 0; h < runner_array.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
}
}
else
{}
}
});
}
}

How to select two list items at same time ? To be specific ONLY TWO items not more than that

I have a list view like the below image.
Now I want to select Only Any two items from the list view at a time and pass the values of both listview items with Intent to next activity. How can I achieve it.?
If Both items are not selected set validation on it?
AdapterClass
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.img= (ImageView)convertView.findViewById(R.id.img);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.img.setBackgroundResource(R.drawble.myimg)
}
else
{
// for not selected row
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
ImageView img;
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}
}
Main Class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class LoadChart extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private SwipeListView listView;
DBHelper mydb;
Button det;
LoadAdapter loadAdapter;
ArrayList<DataBase> array_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_chart);
mydb = new DBHelper(this);
array_list = mydb.getAllCotacts();
Log.e("logging", String.valueOf(array_list));
// ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.load_chart_item,R.id.text, array_list);
det = (Button)findViewById(R.id.reli);
listView = (SwipeListView) findViewById(R.id.listview);
listView.setAdapter(new LoadAdapter(getApplicationContext(),array_list));
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = relationAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}
});
listView.setSwipeListViewListener(new BaseSwipeListViewListener() {
int openItem = -1;
int lastOpenedItem = -1;
int lastClosedItem = -1;
#Override
public void onOpened(int position, boolean toRight) {
lastOpenedItem = position;
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!toRight) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
if (openItem > -1 && lastOpenedItem != lastClosedItem) {
listView.closeAnimate(openItem);
}
openItem = position;
}
#Override
public void onStartClose(int position, boolean right) {
Log.d("swipe", String.format("onStartClose %d", position));
lastClosedItem = position;
}
#Override
public void onClosed(int position, boolean fromRight) {
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!fromRight) {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
#Override
public void onListChanged() {
}
#Override
public void onMove(int position, float x) {
}
#Override
public void onStartOpen(int position, int action, boolean right) {
}
#Override
public void onClickFrontView(int position) {
int id_To_Search = position;
DataBase test = array_list.get(position);
String id = test.getId();
String name = test.getName();
String loc = test.getLocation();
String dt = test.getDate();
String time = test.getTime();
Bundle dataBundle = new Bundle();
dataBundle.putString("name",name);
dataBundle.putString("date",dt);
dataBundle.putString("time",time);
dataBundle.putString("location",loc);
dataBundle.putInt("id", Integer.parseInt(id));
Intent intent = new Intent(getApplicationContext(),LoadedChart.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
#Override
public void onClickBackView(int position) {
Log.e("swipe", String.format("onClickBackView %d", position));
}
#Override
public void onDismiss(int[] reverseSortedPositions) {
}
});
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
#Override
public void onResume()
{
super.onResume();
Set_Referash_Data();
}
public void Set_Referash_Data() {
array_list.clear();
mydb = new DBHelper(this);
ArrayList<DataBase> con = mydb.getAllCotacts();
for (int i = 0; i < con.size(); i++) {
String tidno = con.get(i).getId();
String name = con.get(i).getName();
String cons = con.get(i).getCon();
String loc = con.get(i).getLocation();
DataBase cnt = new DataBase();
cnt.setId(tidno);
cnt.setName(name);
cnt.setCon(cons);
cnt.setLocation(loc);
array_list.add(cnt);
Log.e(String.valueOf(array_list),"RefreshData");
}
mydb.close();
array_list = mydb.getAllCotacts(); //reload the items from database
LoadAdapter ld = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(ld);
ld.refresh(array_list);
ld.notifyDataSetChanged();
Log.e(String.valueOf(array_list),"RefreshData Final");
}
}
Logcat
05-09 14:47:50.706 29939-29939/com.example.user.humandesignsample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.humandesignsample, PID: 29939
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.humandesignsample.RelationAdapter.getSelected()' on a null object reference
at com.example.user.humandesignsample.RelationShipChartList$1.onClick(RelationShipChartList.java:45)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I would use Action Mode with MultiChoiceModeListener.
http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html
There is a callback onItemCheckedStateChanged(ActionMode mode, int position, boolean checked).
You can easily get values of already checked list items ListView.getCheckedItemPositions. So you can prevent selection, if you already selected two or even at once pass the values(or ids) of selected ones without any effort.
You can simply put a counter on item selection.
Take a variable say for ex.
int count = 0;
Check this variable before marking item as selected/deselected:
if(item.isSelected())
{
// you need to make is disable
if(count>0)
{
count--;
// // mark item as deselected
}
}
else
{
// make it selected
if(count<2)
{
count++;
// mark item as selected
}
}
This will make you select ONLY TWO items at a time.
Modify your adapter like this:
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
ArrayList<Boolean> selected = new ArrayList<>();
private int count=0;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < arrayList.size(); i++) {
selected.add(false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.txtv_name.setTextColor(color.red);
}
else
{
// for not selected row
holder.txtv_name.setTextColor(color.black);
}
holder.txtv_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.txtv_name.getCurrentTextColor()== R.color.black)
{
//is not selected
if(count<2)
{
count++;
selected.set(position,true);
// mark item as selected
}
}
else
{
//is selected
if(count>0)
{
count--;
selected.set(position,false);
// // mark item as deselected
}
}
notifyDataSetChanged();
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}}
EDIT 2: For getting selected items from adapter define below method in
adapter and call it with an adapter object like : adp.getSelected()
public String getSelected() {
String selectedString = "";
int num=0;
for (int i = 0; i < selected.size(); i++) {
if (selected.get(i)) {
num++;
if (num == 1) {
selectedString = mProductItems.get(i).getName();
} else {
selectedString += "," + mProductItems.get(i).getName();
}
}
}
return selectedString;
}
Answer to issue 2 : If you want to use ImageView instead of text color change. The do the same things as above but replace the TextView + Color with ImageView + Image.
EDIT 3:
You have called the getSelected() method from a Null object. Modify your code like this:
listView = (SwipeListView) findViewById(R.id.listview);
loadAdapter = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(loadAdapter);
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = loadAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}

Display images in grid view of View pager

I am working on image gallery for which i have made use of ViewPager addon api. I am loading images from a specific folder in sdcard. My goal is to display only 9 images per screen in ViewPager, which i am not able to achieve. The below code is the mainactivity.
public class AndroidSwipeGalleryActivity extends Activity {
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.image_gallery);
File file = new File(Environment.getExternalStorageDirectory()+"/xxxxxxx/images");
if (file.exists()) {
size = file.listFiles().length;
System.out.println("=====File exists====Length is====="+size);
double quo = (double)size/9;
System.out.println("====Dividing by 9====" + quo);
size = (int) Math.ceil(quo);
System.out.println("===Math===== "+size);
} else {
System.out.println("======File does not exists====");
}
MyPagerAdapter adapter = new MyPagerAdapter(this);
adapter.setScrCount(size);
ViewPager myPager = (ViewPager) findViewById(R.id.viewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
The Pager Adapter and Image adapter are in the below class:
public class MyPagerAdapter extends PagerAdapter {
private TextView tv;
private GridView gv;
private int scrCount;
private int count;
public int imageCount;
private Cursor cursor;
private int columnIndex;
private Activity act;
public MyPagerAdapter(Activity act) {
this.act = act;
}
public int getCount() {
return getScrCount();
}
public Object instantiateItem(View collection, int position) {
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the cursor pointing to the SDCard
String uri = MediaStore.Images.Media.DATA;
String condition = uri + " like '%/beverlyhills/images%'";
cursor = act.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, condition, null, null);
count = cursor.getCount();
System.out.println("Cursor count::::"+count);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
for (int i = 0; i < getScrCount() ; i++) {
if (count > 9) {
if (position == i) {
int num = 0;
num = count - 9;
count = num;
imageCount = 9;
}
} else {
imageCount = count;
}
}
resId = R.layout.number_one;
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
tv = (TextView) collection.findViewById(R.id.swipeTitleTextView);
tv.setText("Swipe Gallery");
gv = (GridView) collection.findViewById(R.id.galleryGridView);
ImageAdapter imageAdapter = new ImageAdapter(collection.getContext(), imageCount);
gv.setAdapter(imageAdapter);
// Set up a click listener
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(#SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
// Get the data location of the image
String[] projection = {MediaStore.Images.Media.DATA};
cursor = act.managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
// Get image filename
String imagePath = cursor.getString(columnIndex);
// Use this path to do further processing, i.e. full screen display
System.out.println("=====Image Path:::::"+imagePath);
}
});
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
public int getScrCount() {
return scrCount;
}
public void setScrCount(int scrCount) {
this.scrCount = scrCount;
}
private class ImageAdapter extends BaseAdapter {
private int count;
public ImageAdapter(Context ctx, int count) {
this.count = count;
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(act);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
}
The problem is I am able to load the images and display them on screen but not able to display exactly 9 images per screen. Please go through the code, it's not complex.
i have create the other demo example of view pager to manage the page and also load images. follow the steps wise, its perfectly works..
its a Pager adapter and mDataHolder(List of images) and
Set the property of gridview android:numColumns="3"
private int size;
private int start;
private int end;
private int MATRIX = 9;
public int getCount() {
int size = 0;
if (mDataHolder != null)
modular = mDataHolder.get_Listholder().size() % MATRIX;
if (modular != 0)
size++;
return ((mDataHolder.get_Listholder().size()) / MATRIX) + size;
}
#Override
public Object instantiateItem(ViewGroup container, final int pageIndex) {
mRelativeLayoutInflater = (RelativeLayout) mMasterFragmentActivity.getLayoutInflater().inflate(R.layout.member_pager_adapter, container, false);
mGridView = (GridView) mRelativeLayoutInflater.findViewById(R.id.member_gridView_list);
Calculation of pages<
size = MATRIX;
start = pageIndex * MATRIX;
end = 0;
int temp = 0;
if ((start + MATRIX) < mDataHolder.get_Listholder().size()) {
end = start + MATRIX;
} else {
temp = mDataHolder.get_Listholder().size() - start;
end = start + temp;
size = temp;
}
... and then pass the variable to gridview adapter to set other content in pager.
mAdapterMember = new AdapterMember(mContext, start, end, size);
mGridView.setAdapter(mAdapterMember);
((ViewPager) container).addView(mRelativeLayoutInflater);
return mRelativeLayoutInflater;
}
Below Manage pages variables also use the Gridview adapter to set the postion.
when the set page content position to be like (start + position)
private class AdapterMember extends BaseAdapter {
private ViewHolder mViewHolder;
private Context mContext;
private int start;
private int end;
private int size;
private AdapterMember(Context mContext, int start, int end, int size) {
this.mContext = mContext;
this.start = start;
this.end = end;
this.size = size;
}
#Override
public int getCount() {
if (size > 0)
return size;
else
return 0;
}
#Override
public Object getItem(int position) {
if (mMemberListVO.getMember().size() > 0)
return mMemberListVO.getMember().get(position);
else
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) mContext).getLayoutInflater().inflate(R.layout.row_member_list, null);
mViewHolder = new ViewHolder();
mViewHolder.mImageViewMemberPhoto = (NetworkImageView) convertView .findViewById(R.id.row_member_list_imageView_person);
mViewHolder.mTextViewMemberName = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_name);
mViewHolder.mTextViewMemberDesignation = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_designation);
mViewHolder.mTextViewMemberAddress = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_address);
mViewHolder.mTextViewMemberNotification = (TextView) convertView .findViewById(R.id.row_member_list_imageview_msg_notification);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
mViewHolder.mTextViewMemberName.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_First_Name)
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder(). get(start + position).get(DBHelper.mFieldMember_Last_Name));
mViewHolder.mTextViewMemberDesignation.setText(mDataHolder.get_Listholder().get(start + position)
.get(DBHelper.mFieldMember_Occupation));
mViewHolder.mTextViewMemberAddress.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_Block_No)
+ "," + getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_House_No) + ","
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_Home_Address) + ".");
return convertView;
}
private class ViewHolder {
private NetworkImageView mImageViewMemberPhoto;
private TextView mTextViewMemberName, mTextViewMemberDesignation, mTextViewMemberAddress,
mTextViewMemberNotification;
}
}
its perfectly Working with your requirement...
The problem is solve to load the images and display them on screen its display exactly 9 images per screen.

How to Display two dimensional Array in ListView?

I Have 2D Array and this 2D Array has Strings. I would like to know How to Display the Strings in ListView?how to scroll both vertically and horizontally?
String[][] board = new String[][] {{"1","10","100"},{"hi0","1hello","test"},{"test31","test32","test43"}};
It seem to be you are asking basic things, How to use ListView. please check it you will get all about ListView.
Android ListView and ListActivity
It is to display two-d array in list view.Here's my source code in which i have implemented 2-d array in list view
My Adapter class:-
public class MyArrayAdapter extends ArrayAdapter<List>{
QuickActionDemo quickActionDemo;
public Activity context;
public List<List> list;
int CAMERA_PIC_REQUEST=10;
private int selectedPos = -1;
int clickPosition,rowPosition;
Camera camera;
private static final String TAG = "CameraDemo";
public MyArrayAdapter(Activity context,List<List> list) {
super(context,R.layout.attach_pic,list);
this.context = context;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position+1;
}
static class ViewHolder {
public TextView tv1,tv2,tv3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = null;
final ViewHolder holder = new ViewHolder();
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
rowView = inflator.inflate(R.layout.attach_pic, null);
holder.tv1 = (TextView) rowView.findViewById(R.id.defectpic);
holder.tv2 = (TextView) rowView.findViewById(R.id.no_of_uploded_pics);
holder.tv3 = (TextView) rowView.findViewById(R.id.camera);
holder.tv3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent in = new Intent(getContext(),QuickActionDemo.class);
// context.startActivityForResult(in,0);
}
});
rowView.setTag(holder);
List itemVal1 = (List)getItem(position);
String st1 = (String)itemVal1.get(0);
holder.tv1.setText(st1);
List itemVal2 = (List)getItem(position);
String st2 = (String)itemVal2.get(1);
holder.tv2.setText(st2);
} else {
rowView = convertView;
((ViewHolder) rowView.getTag()).tv1.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv2.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv3.setTag(list.get(position));
}
return rowView;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return list.size();
}
}
Here's my activity class:-
public class MyActivity extends ListActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // to hide the virtual keyboard
setContentView(R.layout.defect_pic_listview);
try{
ArrayAdapter<List> adapter = new MyArrayAdapter(this,makeList());
setListAdapter(adapter);
}
}
private List<List> makeList(){
List<List> all = new ArrayList();
String[] newArray1 = {"Defect Picture1", "2"};
List<String> newListObject1 = Arrays.asList(newArray1);
String[] newArray2 = {"Defect Picture2","1"};
List<String> newListObject2 = Arrays.asList(newArray2);
String[] newArray3 = {"Defect Picture3","4"};
List<String> newListObject3 = Arrays.asList(newArray3);
String[] newArray4 = {"Defect Picture4","1"};
List<String> newListObject4 = Arrays.asList(newArray4);
String[] newArray5 = {"Defect Picture5","3"};
List<String> newListObject5 = Arrays.asList(newArray5);
all.add(newListObject1);
all.add(newListObject2);
all.add(newListObject3);
all.add(newListObject4);
all.add(newListObject5);
return all;
}
}
Creating a model as an inner class always works well.
Good way to store any number of items.
public class ActivityClass extends Activity {
...
ArrayList<ValuesModel> listViewValues = new ArrayList<ValuesModel>();
listViewValues.add(new ValuesModel("row title", "row details"));
ListViewAdapter listAdapter = new ListViewAdapter(this, listViewValues);
((ListView) findViewById(android.R.id.list)).setAdapter(listAdapter);
...
public class ValuesModel {
private String rowTitle;
private String rowDetails;
public ValuesModel(String rowTitle, String rowDetails) {
this.rowTitle = rowTitle;
this.rowDetails = rowDetails;
}
public String getRowTitle() {
return rowTitle;
}
public String getRowDetails() {
return rowDetails();
}
}
Then inside of your list adapter,
public class ListViewAdapter extends ArrayAdapter<ActivityClass.ValuesModel> {
private ArrayList<ActivityClass.ValuesModel> mValues;
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
//here whenever you need to retrieve your values, just say:
// mValues.get(position).getRowTitle();
// mValues.get(position).getRowDetails();
//if you use a viewholder pattern, you can do this:
viewHolder.rowTitle = (TextView) convertView.findViewById(R.id.row_title_textview);
viewHolder.rowTitle.setText(mValues.get(position).getRowTitle());
...
}
}

how to iterate through each checkboxes in each row of a listview in android?

I have an application with three textviews and one checkbox in each row of a listview.what I want that on a click of a button I will be able to get the state of each checkbox and the row corresponding to (isChecked) checkboxes get deleted.one more thing my checkboxes are hardcoded in an xml file.I have searched a lot but couldn't find anything specific.thanks in advance.HERE IS MY CODE...
public class recentcalllistultimate extends ListActivity implements OnClickListener {
CheckBox cb;
Button edit,done;
ImageButton contacts;
ListView lv;
ListView lvultimate;
listviewadapterultimate lvar;
int[] uniqueid;
String[] names;
String[] types;
;
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LayoutParams params=newRelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
LayoutInflater layoutInflater = getLayoutInflater();
mainLayout.addView(layoutInflater.inflate(R.layout.listviewonly, null));
mainLayout.addView(layoutInflater.inflate(R.layout.allbuttons, null));
this.addContentView(mainLayout, params);
cb = (CheckBox) findViewById(R.id.checkboxdelete);
getContacts();
lv = (ListView) findViewById(android.R.id.list);
lvar = new listviewadapterultimate(this, names, types,uniqueid);
lv.setAdapter(lvar);
contacts = (ImageButton) findViewById(R.id.button_keypad);
contacts.setOnClickListener(this);
edit = (Button) findViewById(R.id.editbutton);
done=(Button)findViewById(R.id.donebutton);
done.setOnClickListener(new View.OnClickListener() {
------>>> public void onClick(View v) {
// TODO Auto-generated method stub
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, booleanisChecked) {
// TODO Auto-generated method stub
//WHAT TO DO HERE....
}
}
});
}
------>>> });
edit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
AddDialog ada=new AddDialog(recentcalllistultimate.this);
ada.show();
}
});
}// on create
public void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
int i = 0;
int foo = 0;
names = new String[cur.getCount()];
types = new String[cur.getCount()];
duration = new long[cur.getCount()];
uniqueid = new int[cur.getCount()];
int n = cur.getColumnIndex(CallLog.Calls._ID);
int k = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
int y = cur.getColumnIndex(CallLog.Calls.NUMBER);
int z = cur.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE);
while (cur.moveToNext()) {
uniqueid[foo] = cur.getInt(n);
String str = cur.getString(k);
if (str == null) {
names[foo] = cur.getString(y);
}// if
else {
names[foo] = str;
}
int temp = cur.getInt(z);
switch (temp) {
case 0:
types[foo] = "unknown";
break;
case 1:
types[foo] = "home";
break;
case 2:
types[foo] = "mobile";
break;
case 3:
types[foo] = "work";
break;
}// switch
long doo = cur.getInt(d);
duration[foo] = doo;
foo++;
} // while
}// if
}//getcontacts
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==contacts){
Intent intent = new Intent();
intent.setClassName("com.a.Activities",
"com.a.Activities.DialPad");
startActivity(intent);
finish();
}
}
}// class
.................................
public class listviewadapterultimate extends BaseAdapter {
viewHolder holder;
Activity context;
String[] names;
String[] types;
String[] duration;
int[] uniqueid;
public listviewadapterultimate(Activity context, String[] names,
String[] types, int[] uniqueid2 ) {
this.context = context;
this.names = names;
this.types = types;
uniqueid=uniqueid2;
}
public int getCount() {
// TODO Auto-generated method stub
return names.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class viewHolder {
TextView top;
TextView bottom;
TextView down;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
holder = new viewHolder();
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.recenttextviewonlyultimate, null);
holder.top = (TextView) convertView.findViewById(R.id.toptext_u);
holder.bottom = (TextView) convertView
.findViewById(R.id.bottomtext_u);
holder.down = (TextView) convertView.findViewById(R.id.recentuniqueid_u);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
//holder.cb.setVisibility(View.VISIBLE);
}
holder.top.setText(names[position]);
holder.bottom.setText(types[position]);
holder.down.setText("" + uniqueid[position]);
return convertView;
}
}
................
Try this:
Inside your getView(...) method...
final CheckBox lChk = ((CheckBox) pConvertView.findViewById(R.id.myChkBoxID));
private List<lisInfo> m_lisInfo = new ArrayList<lisInfo>();
lChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Populate the listInfo with check box status
m_lisInfo.get(lPosition).setChkBoxStatus((isChecked));
}
});
public class lisInfo{
private boolean chkBoxStatus;
public boolean isChkBoxStatus() {
return chkBoxStatus;
}
public void setChkBoxStatus(boolean chkBoxStatus) {
this.chkBoxStatus = chkBoxStatus;
}
}
Now iterate the listInfo wherever required to get the check boxes statuses in the list view
maintain an array of boolean inside adapter . set listener on ckeckbox in getview which will swipe values of array on check/uncheck .
now make this array accesible in activity where on button
click()
{
for(int i=0;i<array.size;i++)
{
if(array[i])
adapter.deelet(item i);
//modify syntax
}
}

Categories

Resources