Cardview onclick event is not working with clickable=true - java

This what I have achieved so far
Image adapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
TextView text;
ImageView imageView;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(mContext, R.layout.grid_view, null);
RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.relaGrid);
ImageView image = (ImageView) rl.findViewById(R.id.chooseImage);
TextView text = (TextView) rl.findViewById(R.id.chooseText);
image.setImageResource(mThumbIds[position]);
text.setText(mThumbTxt[position]);
Typeface customFont = Typeface.createFromAsset(mContext.getAssets(), "fonts/faruma.ttf");
text.setTypeface(customFont);
return rl;
}
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.ic_action_gallery, R.drawable.ic_action_gallery,
R.drawable.ic_action_gallery, R.drawable.ic_action_gallery,
R.drawable.ic_action_gallery, R.drawable.ic_action_gallery,
R.drawable.ic_action_gallery, R.drawable.ic_action_gallery
};
private String[] mThumbTxt = {
"Morning", "Evening", "Test deler", "Hepsi", "Test 2",
"Test 3", "Test 4", "Test 5"
};
}
View
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/relaGrid"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="6dp"
android:translationZ="5dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="onCardclick"
android:clickable="true"
android:paddingBottom="10dp">
<ImageView
android:id="#+id/chooseImage"
android:layout_width="match_parent"
android:layout_height="85dp">
</ImageView>
<TextView android:id="#+id/chooseText"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:textSize="18sp"
android:layout_below="#+id/chooseImage"
android:gravity="center"
android:supportsRtl="true"
android:singleLine="true"
android:paddingRight="5dp"
android:paddingLeft="5dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever">
</TextView>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
I am trying to get ripple effect on cardview with onclick listener start another intent. but when ripple effect is enabled, onclick event is not working. I just only see ripple effect only. Onclick listener doesn't work. How to achieve both? Please help
Full MainActivity
package com.mycompany.alun;
import android.content.*;
import android.database.sqlite.*;
import android.graphics.*;
import android.os.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.support.v7.widget.SearchView;
import android.util.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
import java.io.*;
import android.support.v7.widget.Toolbar;
import android.app.*;
import android.support.v4.view.*;
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabase;
DatabaseHelper mDBHelper;
TextView APP_NAME;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHelper = new DatabaseHelper(this);
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if(false == database.exists()) {
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
// Custom title
TextView textCustomTitle = (TextView) findViewById(R.id.appName);
Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/faruma.ttf");
textCustomTitle.setTypeface(customFont);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
if (!isTaskRoot()) {
finish();
return;
}
}
public void onCardclick(AdapterView<?> a, View v, int position, long id) {
switch(position)
{
case 0:
Intent newActivity = new Intent(MainActivity.this,ViewDataActivity.class);
startActivity(newActivity);
break;
case 1:
Intent newActivity2 = new Intent(MainActivity.this,MorningActivity.class);
startActivity(newActivity2);
break;
case 2:
Intent new1Activity = new Intent(MainActivity.this,ViewDataActivity.class);
startActivity(new1Activity);
break;
case 3:
Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.daily_life); // the original file yourimage.jpg i added in resources
Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
String yourText = "My custom Text adding to Image";
Canvas cs = new Canvas(dest);
Paint tPaint = new Paint();
tPaint.setTextSize(35);
tPaint.setColor(Color.BLUE);
tPaint.setStyle(Paint.Style.FILL);
cs.drawBitmap(src, 0f, 0f, null);
float height = tPaint.measureText("yY");
float width = tPaint.measureText(yourText);
float x_coord = (src.getWidth() - width)/2;
cs.drawText(yourText, x_coord, height+15f, tPaint); // 15f is to put space between top edge and the text, if you want to change it, you can
try {
dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/ImageAfterAddingText.jpg")));
// dest is Bitmap, if you want to preview the final image, you can display it on screen also before saving
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 4:
new CustomToast(getApplicationContext(), getApplicationContext().getString(R.string.add_favorites));
break;
case 5:
Intent searchActivity = new Intent(MainActivity.this,SearchActivity.class);
startActivity(searchActivity);
break;
default:
Toast.makeText(MainActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.nav_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
return super.onCreateOptionsMenu(menu);
}
public void getInput(String searchText)
{
Intent in = new Intent(this, SearchActivity.class);
in.putExtra("SEARCH", searchText);
startActivity(in);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_favorites) {
Intent newActivity = new Intent(MainActivity.this,FavoritesActivity.class);
startActivity(newActivity);
}
if (item.getItemId() == R.id.action_search) {
Intent newActivity = new Intent(MainActivity.this,SearchActivity.class);
startActivity(newActivity);
}
return super.onOptionsItemSelected(item);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
Log.d("ViewDataActivity", "outFileName : "+outFileName);
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.w("ViewDataActivity","DB copied");
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

Inside adapter method getView()
CardView cardView = view.findViewById(R.id.card_view_id_from_grid_view)
cardView.setOnClickListener(...)
EDIT
interface CustomClick{
void onClick(int position)
}
private CustomClick customClick;
// Constructor
public ImageAdapter(Context c, CustomClick customClick) {
mContext = c;
this.customClick = customClick;
}
cardView.setOnClickListener(view -> customClick.onClick(position))
MainActivity implements CustomClick
new ImageAdapter(this, this)

First of all assign a specific ID to it.
android:id="#+id/btnCardView"
And yes have it clickable="true".
Then the usual work, go to that respective activity.
Then initialise your card view there.
private CardView cardview;
cardview = findViewById(R.id.btnCardView);
btnCardView.setOnClickListener(new ....) {
//Your function here
}
My intention is to say add the onClickListener to the CardView itself instead of the Relative layout in it.
And just a note that ripple effect won't work on older versions of Android.

Related

Getting child from ListView causes android.view.View android.view.View.findViewById(int) on a null object reference

When the edit button is clicked on my activity_main.xml it fires this method in my main activity.
public void editActivity(View view) {
editIds.clear();
//Check to see if any activities are ticked (checked) and grab the id if they are.
for (int i = 0; i < adapter.getCount(); i++) {
CheckBox c = listView.getChildAt(i).findViewById(R.id.checkBox);
if (c.isChecked()) {
editIds.add(adapter.getItemId(i));
}
}
//If only one item is checked start the Edit activity
if (editIds.size() == 1) {
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("ID", String.valueOf(editIds.get(0)));
startActivityForResult(intent, 2);
}
//If more than 1 or none are checked inform the user
else {
String output = "VIEW / EDIT: Please select one activity.";
Toast.makeText(this, output, Toast.LENGTH_SHORT).show();
}
}
This is checking for any checkboxes checked in the ListView. All works fine until the size of the ListView outgrows the size of the screen. What I mean is as soon as the list has to be scrolled clicking Edit causes the app to crash with this error:
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.activitytracker.MainActivity.editActivity(MainActivity.java:108)
All works fine until the size of the list exceeds the size of the screen and some research has indicated that although my custom adapter contains all the entries for the entire list view the list view only stores the visible entries. I think this is why I get the error.
How can I populate the ArrayList editIds with the checked items id so I can either retrieve that record from the SQLite db or delete it.
My adapter:
package com.example.activitytracker;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class ActivityAdapter extends CursorAdapter {
public ActivityAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.activity, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView activityTitle = (TextView) view.findViewById(R.id.activityTitle);
TextView activityDescription = (TextView) view.findViewById(R.id.activityDescription);
TextView activityDate = (TextView) view.findViewById(R.id.activityDate);
// Extract properties from cursor
String activity = cursor.getString(cursor.getColumnIndexOrThrow("activity"));
String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
// Shorten description for cleaner screen display
String displayValueOfDescription = description;
if (description.length() > 20) {
displayValueOfDescription = description.substring(0, 19) + "...";
}
// Create UK date format for screen display
String yearDB = date.substring(0, 4);
String monthDB = date.substring(5, 7);
String dayDB = date.substring(8, 10);
String dateDB = dayDB + "-" + monthDB + "-" + yearDB;
// Populate fields with extracted properties
activityTitle.setText(activity);
activityDescription.setText(String.valueOf(displayValueOfDescription));
activityDate.setText(String.valueOf(dateDB));
}
public void update(Cursor cursor) {
this.swapCursor(cursor);
this.notifyDataSetChanged();
}
}
My layout_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/AppTheme">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/activity"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="18sp"
android:textStyle="italic"
android:padding="5dp"
android:layout_weight="4"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/description"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="18sp"
android:textStyle="italic"
android:padding="5dp"
android:layout_weight="6"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/date"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="18sp"
android:textStyle="italic"
android:padding="5dp"
android:layout_weight="3"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme">
<Button
android:id="#+id/edit"
android:onClick="editActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/edit" />
<Button
android:id="#+id/delete"
android:onClick="deleteActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/delete" />
</LinearLayout>
</LinearLayout>
My ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#null"
android:layout_weight="1"/>
<TextView
android:id="#+id/activityTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/activity"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="15sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:layout_weight="3"/>
<TextView
android:id="#+id/activityDescription"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/description"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="15sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:layout_weight="6"/>
<TextView
android:id="#+id/activityDate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/date"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="15sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:layout_weight="3"/>
</LinearLayout>
Any help is appreciated as I am a complete beginner with Android and Java.
Here is my onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbManager = new DBManager(this);
dbManager.open();
adapter = new ActivityAdapter(this, dbManager.fetch());
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
EDIT
I have added this code to my Adapter
checked.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// Do the stuff you want for the case when the row TextView is clicked
// you may want to set as the tag for the TextView the position paremeter of the `getView` method and then retrieve it here
Integer realPosition = (Integer) v.getTag();
// using realPosition , now you know the row where this TextView was clicked
Log.d("CLICKEDCHECK", "POS=" + v.getId());
}
});
Im logging the getId but this is the same no matter what tickbox i check. How do I get to the records id for that particular checkbox? Then I could add or remove them from an array list.
EDIT
Update with code from devgianlu.
Code always returns the same id whatever box you check to edit or delete.
here is the updated ActivityAdapter
package com.example.activitytracker;
import android.content.Context;
import android.database.Cursor;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class ActivityAdapter extends CursorAdapter {
private final SparseBooleanArray checked = new SparseBooleanArray();
public ActivityAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.activity, parent, false);
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
TextView activityTitle = (TextView) view.findViewById(R.id.activityTitle);
TextView activityDescription = (TextView) view.findViewById(R.id.activityDescription);
TextView activityDate = (TextView) view.findViewById(R.id.activityDate);
CheckBox check = (CheckBox) view.findViewById(R.id.checkBox);
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked.put(cursor.getPosition(), isChecked);
}
});
// Extract properties from cursor
String activity = cursor.getString(cursor.getColumnIndexOrThrow("activity"));
String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
// Shorten description for cleaner screen display
String displayValueOfDescription = description;
if (description.length() > 20) {
displayValueOfDescription = description.substring(0, 19) + "...";
}
// Create UK date format for screen display
String yearDB = date.substring(0, 4);
String monthDB = date.substring(5, 7);
String dayDB = date.substring(8, 10);
String dateDB = dayDB + "-" + monthDB + "-" + yearDB;
// Populate fields with extracted properties
activityTitle.setText(activity);
activityDescription.setText(String.valueOf(displayValueOfDescription));
activityDate.setText(String.valueOf(dateDB));
}
public boolean isChecked(int pos) {
return checked.get(pos, false);
}
public void update(Cursor cursor) {
this.swapCursor(cursor);
this.notifyDataSetChanged();
}
}
and my call to the isChecked method in MainActivity
public void editActivity(View view) {
editIds.clear();
//Check to see if any activities are ticked (checked) and grab the id if they are.
// Add checked items to deleteIds
for (int i = 0; i < adapter.getCount(); i++) {
if (adapter.isChecked(i)) {
editIds.add(adapter.getItemId(i));
Log.d("EDITACT", "ID="+adapter.getItemId(i) + "size="+editIds.size());
}
}
//If only one item is checked start the Edit activity
if (editIds.size() == 1) {
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("ID", String.valueOf(editIds.get(0)));
startActivityForResult(intent, 2);
}
//If more than 1 or none are checked inform the user
else {
String output = "VIEW / EDIT: Please select one activity.";
Toast.makeText(this, output, Toast.LENGTH_SHORT).show();
}
}
Further update
My ActivityAdapter now looks like this.
package com.example.activitytracker;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import java.util.ArrayList;
import java.util.List;
class Activities {
private boolean checked = false;
private DBManager dbManager;
Cursor cursor = dbManager.fetch();
public Activities(Cursor cursor) {
List<Activities> items = new ArrayList<>();
while (cursor.moveToNext()){
items.add(new Activities(cursor));
}
}
}
public class ActivityAdapter extends BaseAdapter {
private final List<Activities> items;
private final LayoutInflater inflater;
public ActivityAdapter(Context context, List<Activities> items) {
this.items = items;
this.inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity, parent, false);
}
final Activities item = items.get(position);
CheckBox checkBox = convertView.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// item.isChecked() = isChecked;
}
});
// *** Bind the data to the view ***
return convertView;
}
public boolean isChecked(int pos) {
// return items.get(pos).checked;
return true;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
Also now my adapter is not populating my listView on startup and any call to adapter crashes the app.
Here is where I used to check the listview for checked boxes then refresh the adaptor. Not sure what to do here now.
deleteIds.clear();
// Add checked items to deleteIds
for (int i = 0; i < adapter.getCount(); i++) {
CheckBox c = listView.getChildAt(i).findViewById(R.id.checkBox);
if (c.isChecked()) {
deleteIds.add(adapter.getItemId(i));
}
}
//Check to see if any activities are ticked (checked)
if (deleteIds.size() > 0) {
//If there are checked activities a dialog is displayed for user to confirm
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to delete?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < deleteIds.size(); i++) {
dbManager.delete(deleteIds.get(i));
adapter.update(dbManager.fetch());
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteIds.clear();
dialog.cancel();
}
}).show();
}
}
Thanks so much for you help so far.
This is a bit of code I wrote to put all the Cursor data into objects and then bind these objects to views. This way it is much easier to control the checkbox state.
public class CustomItem {
public boolean checked = false;
public CustomItem(Cursor cursor) {
// Get yuor data and put it in the object
}
}
public class CustomAdapter extends BaseAdapter {
private final List<CustomItem> items;
private final LayoutInflater inflater;
public CustomAdapter(Context context, List<CustomItem> items) {
this.items = items;
this.inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(/* Your layout ID */, parent, false);
}
final CustomItem item = items.get(position);
CheckBox checkBox = convertView.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
item.checked = isChecked;
}
});
// *** Bind the data to the view ***
return convertView;
}
public boolean isChecked(int pos) {
return items.get(pos).checked;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
Cursor cursor = ....;
List<CustomItem> items = new ArrayList<>();
while (cursor.moveToNext())
items.add(new CustomItem(cursor));
Adapter adapter = new BaseAdapter(this /* Your activity */, items);
listView.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++) {
System.out.println(i + " IS " + adapter.isChecked(i));
}

Adding Dynamic Buttons to different layouts for phone and tablet using RecyclerView with GridLayoutManager

I am adding dynamic buttons to a layout. Each button is added one at a time, and the layout must update itself if new buttons were added based on a user's action. So the layout could have 3 buttons, or 16, or whatever, depending on the user's action. And the buttons can be added at different times. So if the user opens the app and adds a button, then leaves and returns to the app and adds another button, the old one must remain.
I want my buttons to be added, one by one, into a layout like this:
I have looked around about how to do this, and it was recommended to me that I use a RecyclerView with a GridLayoutManager. I have added this to my code, but the problem is that when I add a button, and then if I add another button, the second one is added on top of the first. So if the user action says that 16 buttons should be made, I am just getting 16 buttons on top of each other and not in the layout that I want.
Here is my code:
My Main Fragment that Initiates the RecyclerView: I have another activity that initiates "createButton" method and passes a drawable and string. These drawables and strings are passed to this method one at a time based on the user's action, and create an image button one at a time
public class MyFragment extends Fragment {
private GridLayoutManager lLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
// Create an empty list to initialize the adapter (or else get nullPointerException error)
List<ItemObject> myList = new ArrayList<ItemObject>();
lLayout = new GridLayoutManager(getActivity(), 4, GridLayoutManager.HORIZONTAL, false);
RecyclerView rView = (RecyclerView)view.findViewById(R.id.recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayout);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(),myList);
rView.setAdapter(rcAdapter);
return view;
}
private List<ItemObject> getAllItemList(String applicationName, Drawable app_drawable){
List<ItemObject> allItems = new ArrayList<ItemObject>();
allItems.add(new ItemObject(applicationName, app_drawable));
return allItems;
}
public void createButton (Drawable d, String appName){
List<ItemObject> rowListItem = getAllItemList(appName, d);
lLayout = new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);
RecyclerView rView = (RecyclerView)getView().findViewById(R.id.recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayout);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), rowListItem);
rView.setAdapter(rcAdapter);
}
}
Here is RecyclerViewHolders:
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView AppName;
public ImageButton AppButton;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
AppName = (TextView)itemView.findViewById(R.id.new_app_name);
AppButton = (ImageButton)itemView.findViewById(R.id.new_app_button);
}
#Override
public void onClick(View v) {
}
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_fragment, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.AppName.setText(itemList.get(position).getName());
holder.AppButton.setImageDrawable(itemList.get(position).getPhoto());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}
ItemObject
public class ItemObject {
private String name;
private Drawable d;
public ItemObject(String name, Drawable d) {
this.name = name;
this.d = d;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Drawable getPhoto() {
return d;
}
public void setPhoto(Drawable d) {
this.d = d;
}
}
and my layout (my_fragment)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:layout_marginTop="15dp"
android:id="#+id/my_fragment"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="horizontal" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/new_app_button"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/new_app_name"
android:gravity="center"
android:layout_below="#+id/new_app_button"
/>
</RelativeLayout>
</LinearLayout>
ANSWER:
HERE IS HOW I GOT MY LAYOUT TO BE DIFFERENT ON THE PHONE AND TABLET (2 rows on the phone, 3 rows on the tablet)
This code was added to my onCreateView method of MyFragment
// Get screen size so we can have different layouts for phone and tablet
int screenSize = getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;
String toastMsg;
switch(screenSize) {
case Configuration.SCREENLAYOUT_SIZE_LARGE:
toastMsg = "Large screen";
Log.d("tag_name", "Large screen");
break;
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
toastMsg = "Normal screen";
Log.d("tag_name", "Normal screen");
break;
case Configuration.SCREENLAYOUT_SIZE_SMALL:
toastMsg = "Small screen";
Log.d("tag_name", "Small screen");
break;
default:
toastMsg = "Screen size is neither large, normal or small";
Log.d("tag_name", "Screen size is not large, normal, or small");
}
Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG).show();
// Create an empty list to initialize the adapter (or else get nullPointerException error)
List<ItemObject> myList = new ArrayList<ItemObject>();
if (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
|| screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
lLayout = new GridLayoutManager(getActivity(), 3, GridLayoutManager.HORIZONTAL, false);
}
else lLayout = new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);
You can detect screen size with this answer.
If the screen size is Configuration.SCREENLAYOUT_SIZE_LARGE or Configuration.SCREENLAYOUT_SIZE_XLARGE then it maybe a tablet.
int spanCount = 2;
if (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
or screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
spanCount = 3;
}

How do i open an image by clicking on a listview in android?

So, here is the thing. I wanted to experiment a bit. So, i wrote this program which looks for images with (.jpg) extension in my mnt/shared/Newpictures folder in my GennyMotion Emulator. In my program, i captured the name of the files with .jpg extension in a String array adapter and the file path in a filepath string array. Now, here is the part where i am blank, i have the path,name and i can get the position by clicking on the list. But how do i open the image when i click on the list. I researched online and most of the codes were too confusing. So, may be someone can suggest me an easier approach. This is what i tried so far. Thanks.
package com.example.user.imageapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
/**
* Created by user on 06-08-2015.
*/
public class Splash extends Activity {
Button load;
String s;
private ListView mainList;
private String[] FilePathStrings;
ArrayList<String>filesinFolder = GetFiles("/mnt/shared/NewPictures");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// load = (Button)findViewById(R.id.Load);
mainList = (ListView) findViewById(R.id.imagelist);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,filesinFolder );
mainList.setAdapter(adapter);
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//what do i put here
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath)
{
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
FilePathStrings = new String[files.length];
for (int i = 0; i < files.length; i++) {
// Get the path of the image file
if(files[i].getName().contains(".jpg")) {
FilePathStrings[i] = files[i].getAbsolutePath();
// Get the name image file
MyFiles.add(files[i].getName());
}
}
return MyFiles;
}
}
A simple way to achieve this would be to create a dialog containing an imageview and then set the imageview's image to the file. Something like this should do the job:
public void onItemclick(AdapterView<?> adapterView, View view, int pos, long id){
String filePath = filesInFolder.get(pos);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_img_preview, null);
builder.setView(view);
ImageView imgView = (ImageView)view.findViewById(R.id.preview_imgview);
imgView.setImageBitmap(BitmapFactory.decodeFile(filePath));
AlertDialog dialog = builder.create();
dialog.show();
}
Here is simple example, how you can view image by click on gridview but you can change to listview in xml file.
This is gridview display.
GridViewActivity.java
public class GridViewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(GridViewActivity.this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
}
});
}
}
This class will display image in single page.
SingleViewActivity.java
public class SingleViewActivity extends Activity {
ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_view);
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565).build();
// Get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.SingleView);
//imageView.setImageResource(imageAdapter.mThumbnames[position]);
imageLoader.displayImage(imageAdapter.mThumbnames[position],imageView,options);
}
}
i have used some random images from internet. This same concept is used in listview for displaying image.
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
layoutInflater = LayoutInflater.from(mContext);
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
public int getCount() {
return mThumbnames.length;
}
public Integer getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder1 holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.grideview_item, null);
holder = new ViewHolder1();
holder.image = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder1) convertView.getTag();
}
// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view
// which implements ImageAware interface)
//imageLoader.displayImage("drawable://" + mThumbIds[position], holder.image);
imageLoader.displayImage(mThumbnames[position], holder.image, options);
//holder.image.setImageDrawable(mContext.getResources().getDrawable(mThumbIds[position]));
return convertView;
}
public static class ViewHolder1 {
ImageView image;
}
// Keep all Images in array
/* public Integer[] mThumbIds = {
R.drawable.ab, R.drawable.ac,
R.drawable.ad, R.drawable.ae
};*/
public String[] mThumbnames = {
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg"
};
}
gridview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:scaleType="fitXY" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:layout_marginBottom="5dip"
android:background="#80000000"
android:gravity="center"
android:text="images"
android:textColor="#000000"
android:textSize="20dp" />
</FrameLayout>

Android loses content when rotate device or re-open APP without logout

I'm create a items list with CardViews and RecyclerView.
When I rotate, re-open the APP without logout or re-create the activity the content is lost. The content is displayed only when you first create the activity (after Login in APP).
I'm not sure why it may be happening and I wonder if someone could help me out.
I put the code here:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBar actionBar;
TextView textView;
Intent intent;
private SQLiteHandler db;
private SessionManager session;
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager lManager;
private ProgressDialog pDialog;
JSONParser jParser;
private static final String TAG_SUCCESS = "success";
private static final String TAG_itemS = "items";
private static final String TAG_item_ID = "item_id";
private static final String TAG_NAME = "name";
private static final String TAG_USERNAME = "username";
private static final String TAG_PHOTO = "photo";
List<item> items;
JSONArray items = null;
HashMap<String, String> user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new ArrayList<>();
new LoadAllitems().execute();
recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new itemAdapter(items);
recycler.setAdapter(adapter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
if (navigationView != null) {
setupNavigationDrawerContent(navigationView);
View header = (View)getLayoutInflater().inflate(R.layout.navigation_drawer_header, null);
TextView navheaduser = (TextView) header.findViewById(R.id.usernameSession);
navheaduser.setText("asdfa");
}
setupNavigationDrawerContent(navigationView);
db = new SQLiteHandler(getApplicationContext());
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
user = db.getUserDetails();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_allitems, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.item_navigation_drawer_allitems:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MainActivity.this, MainActivity.class);
return true;
case R.id.item_navigation_drawer_myitems:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MainActivity.this, Myitems.class);
return true;
case R.id.item_navigation_drawer_logout:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
logoutUser();
return true;
}
return true;
}
});
}
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
class LoadAllitems extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadingitems));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All items from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_ALL_itemS, "GET", params);
// Check your log cat for JSON reponse
Log.d("All items: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// items found
// Getting Array of items
items = json.getJSONArray(TAG_itemS);
// looping through All items
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
items.add(new item(c.getInt(TAG_item_ID), getResources().getIdentifier(String.valueOf(LoadImageFromWebOperations(c.getString(TAG_PHOTO))), "drawable", getPackageName()), c.getString(TAG_NAME), c.getString(TAG_USERNAME)));
}
pDialog.dismiss();
} else {
// no items found
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
itemAdapter.class:
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.itemViewHolder> {
private List<item> items;
public static class itemViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView name;
public TextView userName;
//public TextView description;
public TextView username;
public itemViewHolder(View v) {
super(v);
image = (ImageView) v.findViewById(R.id.itemImage);
name = (TextView) v.findViewById(R.id.itemName);
//userName = (TextView) v.findViewById(R.id.userName);
//description = (TextView) v.findViewById(R.id.itemdescription);
username = (TextView) v.findViewById(R.id.username);
}
}
public itemAdapter(List items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public itemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card, viewGroup, false);
return new itemViewHolder(v);
}
#Override
public void onBindViewHolder(itemViewHolder viewHolder, int i) {
viewHolder.image.setImageResource(items.get(i).getImagen());
viewHolder.name.setText(items.get(i).getName());
viewHolder.username.setText(viewHolder.username.getText() + " " + String.valueOf(items.get(i).getUsernamer()));
}
}
item.class:
public class item {
private int item_id;
private int image;
private String name;
private String username;
private String description;
public item(int item_id, int imagen, String name, String username) {
this.item_id = item_id;
this.image = imagen;
this.name = name;
this.username = username;
this.description = description;
}
public int getitem_id() {
return item_id;
}
public String getName() {
return name;
}
public String getUsernamer() {
return username;
}
public String getdescription() {
return description;
}
public int getImagen() {
return image;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="#bool/fitsSystemWindows">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_height"
android:background="?colorPrimary"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_height"
android:background="?colorPrimaryDark"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/status_bar_height">
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="3dp"
android:layout_marginTop="55dp"
android:scrollbars="vertical" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ToolbarTheme" />
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="#bool/fitsSystemWindows"
app:headerLayout="#layout/navigation_drawer_header"
app:menu="#menu/navigation_drawer_menu"
app:theme="#style/NavigationViewTheme" />
</android.support.v4.widget.DrawerLayout>
item_card.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="150dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/itemImage"
android:layout_width="100dp"
android:layout_height="150dp"
android:scaleType="centerCrop" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/itemName"
android:textColor="#666"
android:layout_toRightOf="#+id/itemImage"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/userTag"
android:id="#+id/username"
android:textColor="#666"
android:layout_below="#+id/itemName"
android:layout_alignLeft="#+id/itemName" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:background="#ffd5d5d5"
android:id="#+id/linea"
android:layout_toRightOf="#+id/itemImage">
</View>
</RelativeLayout>
</android.support.v7.widget.CardView>
Can anyone help me? I'm searching and trying for fix it but I can't make it work.
Thanks!!
EDIT:
I added this code and now the list is loader on rotate an re-create the activity, but the list is duplicated adding itself.
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("ITEMS", items);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
items.clear();
items = savedInstanceState.getParcelableArrayList("ITEMS");
adapter = new itemAdapter(items);
recycler.setAdapter(adapter);
}
Android recreates the layout everytime you rotate your device. Therefore, if
you want the user to be able to rotate the device (orientation change), you have
to override the Activity method onSaveInstanceState and provide a Bunde
with all your needed information's.
After the orientation is changed, this bundle will be given to you in
protected void onCreate(Bundle savedInstanceState)
so you can recreate your views and activity state.
Edit: also do not forget to finish your AsyncTask
Edit: I already added a small explanation what you need to do, but in this
case I think a Google link is valid: Recreating an Activity
As said, Android will recreate your Activity, everytime you change the orientation of your device. Because the layout needs to reinflate etc..
initialize your app in onCreate
do your activity logic while the activity is active
if the activity goes into background onSaveInstanceState is called
save ALL your needed information's in the bundle (which is given as an arguement to the method)
your activity is recreated
fetch your saved information's from the bundle given to onCreate
You can use the #JacksOnF1re solution or add this in your manifest in the activity that require
android:configChanges="orientation|screenSize"
Any additional code is not necessary in your case.

Select checkall in listview to check all the checkbox

I am having an listview with checkboxes,from the top i am giving an "select all",while check the select all,i want all checkbox has to select it.But now while checking the select all is not selecting all the checkbox.Seperate checkbox is working fine.
This is the layout for select all for listview.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:paddingRight="5dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/strAll"
/>
<CheckBox
android:id="#+id/chkAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</RelativeLayout>
"ContactActivity.java"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
lv =(ListView)findViewById(R.id.lv);
getAllCallLogs(this.getContentResolver());
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
send = (Button) findViewById(R.id.button1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,lv);
setListAdapter(adapter);
final CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);
chkAll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int size = 0;
boolean isChecked = chkAll.isChecked();
if (isChecked == true) {
size = lv.getCount();
for (int i = 0; i <= size; i++)
lv.setItemChecked(i, true);
} else if(isChecked==false)
{
size = lv.getCount();
for (int i = 0; i <= size; i++)
lv.setItemChecked(i, false);
}
}
});
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
phno0.add(phno1.get(i).toString()) ;
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(ContactActivity.this, checkedcontacts,1000).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name",phno0);
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
private void setListAdapter(ArrayAdapter<String> adapter1) {
// TODO Auto-generated method stub
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#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 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
private int getCheckedItemCount(){
int cnt = 0;
SparseBooleanArray positions = lv.getCheckedItemPositions();
int itemCount = lv.getCount();
for(int i=0;i<itemCount;i++){
if(positions.get(i))
cnt++;
}
return cnt;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
I am posting another answer. Please listen carefully.
1.) Create a global boolean variable :-
boolean flag = false;
2.)in your getView, do this. This will not check all the checkboxes in your listview. I am assuming that you have only one checkbox in your listview.
holder.checkBoxinyourListView.setChecked(flag);
3.) Now, in the listener of the checkbox which is NOT in your listview, add this code :-
checkBox not in listView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
adapter.notifyDataSetChanged();
}
});
ScreenShot 1:- When not checked
ScreenShot 2:- When Checked
This Code Works 100%
NOTE :- In my project, i am using a lazy loader for images. Please don't get confused.
Jars in my project :- universal-image-loader-1.8.7 , android-support-v4
MainActivity.Class
package com.example.listviewwithselectallcheckbxox;
//import it.sephiroth.android.library.widget.AdapterView;
//import it.sephiroth.android.library.widget.AdapterView.OnItemClickListener;
//import it.sephiroth.android.library.widget.HListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
public class MainActivity extends Activity{
DisplayImageOptions options;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
boolean flag = false;
CheckBox selectAll;
private static final String LOG_TAG = "MainActivity";
ListView listView;
TestAdapter mAdapter;
List<RowItem> rowItems;
public static final String[] url = {"https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg",
"https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s1024/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",
"https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpg",
"https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s1024/Antelope%252520Butte.jpg",
"https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpg",
"https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s1024/Antelope%252520Walls.jpg",
"https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s1024/Apre%2525CC%252580s%252520la%252520Pluie.jpg",
"https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s1024/Backlit%252520Cloud.jpg",
"https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s1024/Bee%252520and%252520Flower.jpg",
"https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s1024/Bonzai%252520Rock%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s1024/Caterpillar.jpg",
"https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s1024/Chess.jpg"};
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.build();
ImageLoader.getInstance().init(config);
listView = (ListView) findViewById( R.id.hListView1 );
selectAll = (CheckBox) findViewById(R.id.selectall);
rowItems = new ArrayList<RowItem>();
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(0))
.cacheOnDisc(true)
.build();
for (int i = 0; i < url.length; i++) {
RowItem item = new RowItem(url[i]);
rowItems.add(item);
}
mAdapter = new TestAdapter(this,R.layout.list_item, rowItems);
listView.setHeaderDividersEnabled( true );
listView.setFooterDividersEnabled( true );
listView.setAdapter( mAdapter );
selectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
mAdapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Toast.makeText(getApplicationContext(), position+"", Toast.LENGTH_SHORT).show();
CheckBox check = (CheckBox)view.findViewById(R.id.radio);
final Integer index = Integer.valueOf(position);
if(!checkedPositions.contains(index))
checkedPositions.add(index);
else
checkedPositions.remove(index);
check.setChecked(checkedPositions.contains(index));
}
});
Log.i( LOG_TAG, "choice mode: " + listView.getChoiceMode() );
}
public class TestAdapter extends ArrayAdapter<RowItem> {
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
Context context;
protected ImageLoader imageLoader = ImageLoader.getInstance();
public TestAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
CheckBox radio1;
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public int getItemViewType( int position ) {
return position%3;
}
ViewHolder holder=null;
#Override
public View getView(final int position, View convertView, ViewGroup parent ) {
RowItem rowItem = getItem(position);
holder = new ViewHolder();
final int i = position;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.radio1 = (CheckBox) convertView.findViewById(R.id.radio);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.radio1.setChecked(flag);
if(flag){
if(!checkedPositions.contains(position))
checkedPositions.add(position);
}
else
{
checkedPositions.clear();
}
final Integer index = Integer.valueOf(position);
holder.radio1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if(isChecked){
if(!checkedPositions.contains(index))
checkedPositions.add(index);
}
else
checkedPositions.remove(index);
}
});
imageLoader.displayImage(rowItem.getimageUrl(), holder.imageView, options, animateFirstListener);
holder.radio1.setChecked(checkedPositions.contains(index));
return convertView;
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 5000);
displayedImages.add(imageUri);
}
}
}
}
}
RowItem.class
package it.sephiroth.listviewwithselectallcheckbxox;
public class RowItem {
private int imageId;
private String imageUrl;
public RowItem(int imageId) {
this.imageId = imageId;
}
public RowItem(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getimageUrl() {
return imageUrl;
}
public void setimageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ListView
android:id="#+id/hListView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:paddingTop="20dip"
android:paddingBottom="20dip"
android:background="#11000000"
/>
<CheckBox
android:id="#+id/selectall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/hListView1"
android:layout_marginLeft="60dp"
android:layout_marginTop="64dp"
android:text="selectall" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="ImageView"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
</ImageView>
<CheckBox
android:id="#+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/icon"
android:layout_marginLeft="33dp"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.sephiroth.android.sample.horizontalvariablelistviewdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In the getView(), Add all the position of the checkboxes
ArrayList<Integer> addIndex= new ArrayList<Integer>();//Global
checkedPositions.add(position);
This will contain all the checkboxes position
Use a ArrayList to maintain all the checkbox states in the ListView to keep track of which checkbox is checked with a boolean.
Then when you click on checkAll CheckBox you update all boolean in your list to true and do yourAdapter.notifyDataSetChanged();
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();//Global
Scenario : When Checking individual Checkboxes, adding in array list. The code below is to be added in ListView.setOnItemClickListener()
final Integer index = Integer.valueOf(position);
if(!checkedPositions.contains(index))
checkedPositions.add(index);
else
checkedPositions.remove(index);
check.setChecked(checkedPositions.contains(index));
Scenario 2 : When you check the SelectAll Checkbox.
holder.selectAllCheckbox.setOnCheckedChangeListener() listener
//Write your code here. Write an if condition that matches for the indexes in both the array list i have created and set checked as per your need
Note :- i have used an integer array list. You can use a boolean and do the same steps and the code below:-
if(list.get(position).isChecked()){
cellHolder.checkBox.setChecked(true);
}
else{
cellHolder.checkBox.setChecked(false);
}
All the boolean are at true so all the checkBoxes will be checked (the same logic goes for uncheck)
public class Adapter extends ArrayAdapter<TripItem> {
private final Context context;
private final ArrayList<CommonExpenseItem> tripExpenseItems;
public TripsAdapter(Context context, ArrayList<TripItem> values,
ArrayList<CommonExpenseItem> tripExpenses) {
super(context, R.layout.expense_list_row, values);
this.context = context;
this.tripExpenseItems = tripExpenses;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.expense_list_row, parent,
false);
return rowView;
}
}
The above is a simlple custom adapter ,here i am passing values in a arrayList u can pass hashmap simply,
Initially load all the string values in a separate hashmap or pojo obj with another value named as checkBox value as "disabled", and set the adapter ,
Then in the getView method set the name in the text view and get the checkbox string and check the checkbox if the value is enabled or uncheck if the value is disabled.
and also set tag the position to the checkbox, and create oncheckchange listener for the checkbox item inside the getView() and inside that method get the checkbox tag and get the respective hash map or the obj from the arrayList.
And Change the chekcbox value as enabled and notify the data set to be changed.
Finally for ur problem. once the checkbox in main layout is checked get the arraylist and in a for loop get the hash map or the objs and set the checkbox values to "enabled" and notify dataset changed or set a new adapter and populate in the list view. like wise u can get the solution as u required.

Categories