Passing images from one adapter to another - java

I have a gridView on my mainScreen fragment which contains imageViews initialized by my ImageAdapter.java class. I also have another fragment which also has a gridView which follows the same initialization process. What i want is to pass the selected imaveView's icon(which is stored in an Integer[] array) to the other fragment's gridView.
Here are my classes:
MainFragment.java [the part that handles the image passing]:
// When an item in the context menu gets selected, call a method
#Override
public boolean onContextItemSelected(MenuItem item) {
// Get some extra info about the contextMenu
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position; // clicked view's position
if(item.getTitle().equals("Add Card to GLB")) {
addCardMessage(position, "added to GLB");
addSelectedCardToGlobalUserBox(position);
} else if (item.getTitle().equals("Add Card to JP")) {
addCardMessage(position , "added to JP");
} else
{
return false;
}
return false;
}
/**
* Creates a snackbar message, telling the user which card was added to which box
* #param id The position of the chosen card
* #param text Defines into which User Box the card was added
*/
private void addCardMessage(int id, String text) {
final Snackbar snackbar = Snackbar.make(gridView, id + " " + text ,Snackbar.LENGTH_LONG);
snackbar.setAction("Dismiss", new View.OnClickListener() {
#Override
public void onClick(View view) {
snackbar.dismiss();
}
});
snackbar.setActionTextColor(Color.MAGENTA);
snackbar.show();
}
private void addSelectedCardToGlobalUserBox(int position) {
ImageAdapter imageAdapter = new ImageAdapter(getContext());
UserBoxGlbImageAdapter userBoxGlbImageAdapter = new UserBoxGlbImageAdapter(getContext());
userBoxGlbImageAdapter.getGLBIconsList().add(imageAdapter.getmThumbIds(position));
int glbiconSize = userBoxGlbImageAdapter.getCount();
Toast.makeText(getActivity(), "Selected icon: " + imageAdapter.getmThumbIds(position), Toast.LENGTH_SHORT).show();
}
ImageAdapter.java [above fragment's adapter]:
public class ImageAdapter extends BaseAdapter {
Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer getmThumbIds(int index) {
return mThumbIds[index];
}
// References to our images
private Integer[] mThumbIds = {
R.mipmap.turvegitossj_phy,
R.mipmap.goget_ur_int,
R.mipmap.turgogetassj4_teq,
R.mipmap.turgotenksssj_uragl,
R.mipmap.lr_phy_trunks_ssj
};
}
SecondFragment.java:
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext()));
return view;
}
}
SecondFragmentAdapter[the one to receive the image]:
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
public UserBoxGlbImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mGLBIcons.get(position));
return imageView;
}
}
So far, when i long-press and the context menu opens, i click on add card to GLB but the image doesn't pass to the 2nd fragmnet's gridView. From what i understand, the Integer that i am using to add the imageResource to the 2nd grid does not work properly. What do i need to do? Do i need to use a different var type for my receiver list?

Related

Updating a GridView

I need to update my gridView when I click on an item. I've try a lot a things but nothing works.
I have the following code for my activity:
public class GameActivity extends AppCompatActivity implements IGameView{
public GridGame _gridGame = new GridGame();
public GamePresenter _presenter = new GamePresenter(this, _gridGame);
public ImageAdapter _imageAdapter = new ImageAdapter(this, _gridGame);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_help) {
Intent intent = new Intent(this, HelpActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final Context context = this;
final GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(_imageAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
_presenter.addPawn(position);
_imageAdapter.update(position, _presenter.actualPlayer);
Toast.makeText(context, "" + position,Toast.LENGTH_SHORT).show();
}
});
}
And imageAdapter's code :
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private GridGame _gridGame;
public ImageAdapter(Context c, GridGame grid) {
mContext = c;
_gridGame = grid;
}
public int getCount() {
return grid.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) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new ViewGroup.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
setGrid();
imageView.setImageResource(grid[position]);
return imageView;
}
private Integer[] grid = new Integer[42];
public void setGrid() {
for(int i = 0; i < 42; i++){
grid[i] = R.drawable.square;
}
}
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
}
When I click on a square (item on the gridview) i want that the view update a show an other image instead of the square. The update is done when I call update method on the ImageAdapter but the view don't update.
First you need to fix the methods to return the desired data for adapter to identify the item objects as
// return the new data from sourcein case of update
public Object getItem(int position) {
return grid[position];
}
// don't send 0 always
public long getItemId(int position) {
return position;
}
// invoke notifyDataSetChanged(); when there is a change in data source
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
notifyDataSetChanged();
}
You need to notify the adapter that a data element has changed. Try this update() method:
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
notifyDataSetChanged();
}
Ok, I've found the problem, I was setting the grid in the getView(int position, View convertView, ViewGroup parent); but it should be set in the constructor.
The problem was that it reset the value in the grid each time I click on an item, so the value didn't changed.

How to add value to a list dynamically in android?

I have a list in which i can assigned the values statically.
private List<ListData> mDataList = Arrays.asList(
new ListData("Arun"),
new ListData("Jega"),
new ListData("Kabilan"),
new ListData("Karthick"),
new ListData("Joushva"),
new ListData("Niranjana"),
new ListData("Paramesh"),
new ListData("Prabha"),new ListData("Test1"),new ListData("Test2") );
The problem is now i got a scenario where i should get these value dynamically from web apim and i have to set it to the List variable mDataList.
Please help me to clear this. Thanks in advance.
Here is my complete code.
public class ReportFragment extends Fragment {
View ParentView;
private static final int HIGHLIGHT_COLOR = 0x999be6ff;
// list of data items
private List<ListData> mDataList = Arrays.asList(
new ListData("Arun"),
new ListData("Jega"),
new ListData("Kabilan"),
new ListData("Karthick"),
new ListData("Joushva"),
new ListData("Niranjana"),
new ListData("Paramesh"),
new ListData("Prabha"),new ListData("Test1"),new ListData("Test2")
);
// declare the color generator and drawable builder
private ColorGenerator mColorGenerator = ColorGenerator.MATERIAL;
private TextDrawable.IBuilder mDrawableBuilder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ParentView= inflater.inflate(R.layout.report_fragment, container, false);
init();
return ParentView;
}
public void init(){
mDrawableBuilder = TextDrawable.builder()
.round();
// init the list view and its adapter
final ListView listView = (ListView) ParentView.findViewById(R.id.listView1);
listView.setAdapter(new SampleAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
private class SampleAdapter extends BaseAdapter {
#Override
public int getCount() {
return mDataList.size();
}
#Override
public ListData getItem(int position) {
return mDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(getActivity() , R.layout.list_item_layout, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListData item = getItem(position);
// provide support for selected state
updateCheckedState(holder, item);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// when the image is clicked, update the selected state
ListData data = getItem(position);
data.setChecked(!data.isChecked);
updateCheckedState(holder, data);
}
});
holder.textView.setText(item.data);
return convertView;
}
private void updateCheckedState(ViewHolder holder, ListData item) {
if (item.isChecked) {
holder.imageView.setImageDrawable(mDrawableBuilder.build(" ", 0xff616161));
holder.view.setBackgroundColor(HIGHLIGHT_COLOR);
holder.checkIcon.setVisibility(View.VISIBLE);
}
else {
TextDrawable drawable = mDrawableBuilder.build(String.valueOf(item.data.charAt(0)), mColorGenerator.getColor(item.data));
holder.imageView.setImageDrawable(drawable);
holder.view.setBackgroundColor(Color.TRANSPARENT);
holder.checkIcon.setVisibility(View.GONE);
}
}
}
private static class ViewHolder {
private View view;
private ImageView imageView;
private TextView textView;
private ImageView checkIcon;
private ViewHolder(View view) {
this.view = view;
imageView = (ImageView) view.findViewById(R.id.imageView);
textView = (TextView) view.findViewById(R.id.textView);
checkIcon = (ImageView) view.findViewById(R.id.check_icon);
}
}
private static class ListData {
private String data;
private boolean isChecked;
public ListData(String data) {
this.data = data;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
}
create a method to add items in your adapter class, this method will add item to
itemlist. this will add items dynamically on your list or grid.
e.g
public void addItem(Item item){
itemList.add(item);
notifydatasetchanged();}
create a adapter class and constructor, in constructor just initialize the item arraylist and create extra method called addItem() this method will add item to your arraylist. after that you just have to call notifyDatasetchanged and your new item will be added.

Android ListView items disappear when scrolling

I've loaded some pictures into a ListView using an adapter. When a user clicks on any row of the list I'm showing a checkmark at the end:
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
List<String> names,facebookbid;
String sent;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, List<String> n,List<String> fid,String s) {
activity = a;
names=n;
facebookbid=fid;
sent=s;
inflater = (LayoutInflater)activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),"p");
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
public int getCount() {
return facebookbid.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public class ViewHolder{
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
convertView=null;
final ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = inflater.inflate(R.layout.planners_friends_listrow, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView)convertView.findViewById(R.id.planner_friend_image);
holder.checkmark=(ImageView)convertView.findViewById(R.id.checkmark);
holder.friendsrow=(RelativeLayout)convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag( holder );
}
else
holder=(ViewHolder)convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if(sent.equals("planners"))
{link=facebookbid.get(position);
}
else
{
link="https://graph.facebook.com/"+facebookbid.get(position)+"/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a=isNetworkConnected();
if(a==true)
{
if(sender.equals("settings"))
{
}
else if(sender.equals("savethedate"))
{
if(sid.contains(facebookbid.get(position)))
{
if(sid.contains("_"))
{
sid=sid.replace("_"+facebookbid.get(position), "");
}
else
{
sid=sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size()-1);
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.GONE);
}
else
{
if(sid.isEmpty())
{
sid=sid+facebookbid.get(position);
}
else
{
sid=sid+"_"+facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.VISIBLE);
}
}
else
{
String friendname=names.get(position);
String friendid=facebookbid.get(position);
String friendgender=gender.get(position);
Intent resultIntent = new Intent(Friends.this,Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if(sender.equals("planner"))
{
resultIntent.putExtra("plannerid",friendid);
resultIntent.putExtra("imageurl","https://graph.facebook.com/"+friendid+"/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
else
{
resultIntent.putExtra("plannerid","");
resultIntent.putExtra("imageurl","");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet connection",Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The problem is: When the ListView is scrolled, the checkmark icon simply disappears. What am I doing wrong?
Looking at your code you set the Visibility of the checkmark when the user clicks on one of the items which then shows / hides the item. Now when the user scrolls the items are recycled and you dont have any code to check if the item has been checked or not.
So in short you need something that basically says
if (checked) {
//set visibility of the checkmark to visible
} else {
//set visibility of the checkmark to gone
}
First you need to change getView method as don't reinitialize convertView as null remove below line from getView
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
List<String> names, facebookbid;
String sent;
public ImageLoader imageLoader;
private int size = 0;
private HashMap<String, Boolean> mapClickStatus;
public LazyImageLoadAdapter(Activity a, List<String> n, List<String> fid, String s) {
activity = a;
names = n;
facebookbid = fid;
sent = s;
mapClickStatus = new HashMap<String, Boolean>();
if (facebookbid != null)
size = facebookbid.size();
// Give total size of the list item to getCount method
imageLoader = new ImageLoader(activity, "p");
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
/*********
* Create a holder Class to contain inflated xml file elements
*********/
public class ViewHolder {
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// convertView=null;
//It should not be null every time
final ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView) convertView.findViewById(R.id.planner_friend_image);
holder.checkmark = (ImageView) convertView.findViewById(R.id.checkmark);
holder.friendsrow = (RelativeLayout) convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if (sent.equals("planners")) {
link = facebookbid.get(position);
} else {
link = "https://graph.facebook.com/" + facebookbid.get(position) + "/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
// set the visibility of CheckMark ImageView based on the click status.
if (mapClickStatus.get(facebookbid.get(position)))
holder.checkmark.setVisibility(View.VISIBLE);
else
holder.checkmark.setVisibility(View.GONE);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a = isNetworkConnected();
/// I dont know about the unique ID field in this so i took facebookbid.get(position) as a key
// To set click status of row item in hashmap.
mapClickStatus.put(facebookbid.get(position),
mapClickStatus.containsKey(facebookbid.get(position)) ? false : true);
if (a == true) {
if (sender.equals("settings")) {
} else if (sender.equals("savethedate")) {
if (sid.contains(facebookbid.get(position))) {
if (sid.contains("_")) {
sid = sid.replace("_" + facebookbid.get(position), "");
} else {
sid = sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size() - 1);
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.GONE);
} else {
if (sid.isEmpty()) {
sid = sid + facebookbid.get(position);
} else {
sid = sid + "_" + facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.VISIBLE);
}
// TO refresh view with updated checkmark status
notifyDataSetChanged();
} else {
String friendname = names.get(position);
String friendid = facebookbid.get(position);
String friendgender = gender.get(position);
Intent resultIntent = new Intent(Friends.this, Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if (sender.equals("planner")) {
resultIntent.putExtra("plannerid", friendid);
resultIntent.putExtra("imageurl", "https://graph.facebook.com/" + friendid + "/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
} else {
resultIntent.putExtra("plannerid", "");
resultIntent.putExtra("imageurl", "");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
} else {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Suggestions
Inflate layout with parent attaching like below
.
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
Avoid mantaining status by using multiple collection(Arraylist or
like that to display data) use Model Class or JSON or Arraylist of
map etc.

How do i call a context menu on longclick in a ListView Item?

HomeFragment
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
I just need 3 items on the context menu: Like, Comment and Favorite. I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.
Here´s my adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Are the changes supposed to go in the adapter or the fragment? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick. Any help would be appreciated.
I managed to get one context menu working, right here:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
adapter = new ListViewAdapter(getActivity(), arraylist);
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Opções");
menu.add(0, v.getId(), 0, "Like");
menu.add(1, v.getId(), 0, "Comment");
menu.add(2, v.getId(), 0, "Favorite");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
addLike(item.getItemId());
} else if (item.getTitle() == "Comment") {
} else if (item.getTitle() == "Favorite") {
// code
} else {
return false;
}
return true;
}
public void addLike(int id){
}
Right after the return rootView in the HomeFragment. Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case).
first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setAdapter(adapter);
then register for MultiChoiceModeListener and override his methods in your liking :)
myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// here you will inflate your CAB
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Here is the link

Android java.lang.IllegalStateException on ListView

I use ListActivity with SpecialAdapter that show some log information.
I do not use background thread but I get an error when scroll list:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class ru.FoxGSM.ui.DebugActivity$SpecialAdapter)]
Please, help me.
(FoxLog is static class that get log information, perhaps from another thread. But in list a want show FoxLog snapshot)
public class DebugActivity extends ListActivity {
private class SpecialAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public SpecialAdapter(Context context) {
super();
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return FoxLog.count();
}
public long getItemId(int index) {
return index;
}
public Object getItem(int index) {
return FoxLog.get(FoxLog.count()-index-1);
}
// Get the type of View
public View getView(int position, View convertView, ViewGroup parent) {
TextView text;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.debug_list, null);
text = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(text);
} else
text = (TextView) convertView.getTag();
String s = (String) getItem(position);
if (s==null)
return convertView;
text.setText(s);
boolean isError = false;
if (s!=null && s.length()>0) {
String prefix = s.substring(0, 1);
if (prefix.equals("E") || prefix.equals("W"))
isError = true;
}
if (isError)
text.setBackgroundResource(R.color.red);
else
text.setBackgroundDrawable(null);
return convertView;
}
}
private void RefreshData() {
FoxLog.ReInit(this);
SpecialAdapter adapter = (SpecialAdapter)this.getListAdapter();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debug);
FoxLog.ReInit(this);
SpecialAdapter adapter = new SpecialAdapter(this);
setListAdapter(adapter);
Button mExit = (Button)findViewById(R.id.exit);
mExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}

Categories