This is my app when I start it:
When I click one of the item in the list view it will open a new activity and display some data.
When I search for something it looks like this:
And when I click an item in the list it starts a new activity. But the activity it starts is not accurate.
Here's my code:
HomeActivity.class
package com.thesis.herbalmedicines.activity;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends BaseActivity implements
SearchView.OnQueryTextListener {
ListView lv;
SearchView search;
String[] herb_names, sample_arr; //= ["Boils","",""];//, iso_codes;
TypedArray herb_pics;
ArrayList<Home> homelist;
HomeAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.home_layout, frameLayout);
mDrawerList.setItemChecked(position, true);
setTitle(listArray[position]);
android.app.ActionBar ab = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#50B222"));
ab.setBackgroundDrawable(colorDrawable);
lv = (ListView) findViewById(R.id.list_view);
search = (SearchView) findViewById(R.id.search_view);
herb_names = getResources().getStringArray(R.array.herb_names);
//iso_codes = getResources().getStringArray(R.array.iso_Code);
herb_pics = getResources().obtainTypedArray(R.array.herb_pics);
homelist = new ArrayList<Home>();
for (int i = 0; i < herb_names.length; i++) {
Home home = new Home(herb_names[i], //iso_codes[i],
herb_pics.getResourceId(i, -1));
homelist.add(home);
}
adapter = new HomeAdapter(getApplicationContext(), homelist);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent a = new Intent(HomeActivity.this, Boils.class);
startActivity(a);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
else if (position == 1) {
Intent b = new Intent(HomeActivity.this, Cystitis.class);
startActivity(b);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
else if (position == 2) {
Intent c = new Intent(HomeActivity.this, Asthma.class);
startActivity(c);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
else if (position == 3) {
Intent d = new Intent(HomeActivity.this, Feet.class);
startActivity(d);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
});
search.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
Home.java
package com.thesis.herbalmedicines.activity;
public class Home {
String name;
int pics;
Home(String name, int pics) {
this.name = name;
this.pics = pics;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPics() {
return pics;
}
public void setPics(int pics) {
this.pics = pics;
}
}
HomeAdapter.java
package com.thesis.herbalmedicines.activity;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class HomeAdapter extends BaseAdapter implements Filterable {
Context context;
ArrayList<Home> homelist;
ArrayList<Home> mStringFilterList;
ValueFilter valueFilter;
HomeAdapter(Context context, ArrayList<Home> homelist) {
this.context = context;
this.homelist = homelist;
mStringFilterList = homelist;
}
#Override
public int getCount() {
return homelist.size();
}
#Override
public Object getItem(int position) {
return homelist.get(position);
}
#Override
public long getItemId(int position) {
return homelist.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
TextView name_tv = (TextView) convertView.findViewById(R.id.name);
ImageView iv = (ImageView) convertView.findViewById(R.id.pic);
Home home = homelist.get(position);
name_tv.setText(home.getName());
iv.setImageResource(home.getPics());
}
return convertView;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Home> filterList = new ArrayList<Home>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
Home home = new Home(mStringFilterList.get(i)
.getName(), mStringFilterList.get(i)
.getPics());
filterList.add(home);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
homelist = (ArrayList<Home>) results.values;
notifyDataSetChanged();
}
}
}
Add a field that holds the class to be loaded inside the Home class. (The id field is optional)
public class Home {
int id;
String name;
int pics;
Class clazz;
Home(int id, String name, int pics, Class clazz) {
this.id = id;
this.name = name;
this.pics = pics;
this.clazz = clazz;
}
// getters and setters
}
During initialization of the homelist add the id,
// the classed to load
Class[] classes = {
Boils.class,
Cystitis.class,
Asthma.class,
Feet.class
};
for (int i = 0; i < herb_names.length; i++) {
Home home = new Home(i, herb_names[i], herb_pics.getResourceId(i, -1), classes[i]);
homelist.add(home);
}
Inside the setOnItemClickListener,
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Home item = (Home) adapter.getItem(position);
Intent d = new Intent(HomeActivity.this, item.getClazz());
startActivity(d);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
});
Couple of changes should be made in your adapter as well.
Inside the getView you are forcing the convertView to null. It is bad for performance. (Consider using a ViewHolder too)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
}
TextView name_tv = (TextView) convertView.findViewById(R.id.name);
ImageView iv = (ImageView) convertView.findViewById(R.id.pic);
Home home = homelist.get(position);
name_tv.setText(home.getName());
iv.setImageResource(home.getPics());
return convertView;
}
Inside publishResults you are creating a new reference for the dataset. You should update the existing dataset.
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
homelist.clear();
homelist.addAll((ArrayList<Home>) results.values);
notifyDataSetChanged();
}
Set adpter to listview on every onSerch
Why do you use position to navigate to different activity ?
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent a = new Intent(HomeActivity.this, Boils.class);
startActivity(a);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
else if (position == 1) {
Intent b = new Intent(HomeActivity.this, Cystitis.class);
startActivity(b);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
else if (position == 2) {
Intent c = new Intent(HomeActivity.this, Asthma.class);
startActivity(c);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
else if (position == 3) {
Intent d = new Intent(HomeActivity.this, Feet.class);
startActivity(d);
/** Fading Transition Effect */
HomeActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
});
search.setOnQueryTextListener(this);
}
This will always reset your position whenever you adapter refresh from search result.
To do this in better way. Just create custom listener like following in your adapter.
Public interface ListViewClick{
void onListClick(Object type)
}
Register your receiver in activity and pass type of activity to launch from adapter
private ListViewClick callback;
HomeAdapter(Context context, ArrayList<Home> homelist,ListViewClick callback) {
this.context = context;
this.homelist = homelist;
mStringFilterList = homelist;
this.callback = callback;
}
and on click listener of convertView pass callback.onListClick(//type of activity to launch).
Just keep reference of 'type of activity to launch in Home enitity'. so you can recognize which activity is ti be launch when clicking on particular row of list view.
Related
Long post, thanks for taking the time to look through this
I have been struggling with this issue for a while now. I have an SQLiteDatabase which stores a shoe's brand name, name of shoe, and a byte image of the shoe. I was able to load all of the information to a recyclerview via a content provider. But it seems when I try and load the information to the details of each item in the recycler view, the details activity is filled with the wrong information, it returns a completely different entry other than the one I selected.
The solutions I've seen in many youtube videos have contained me creating ArrayLists to store the information, but I find that very hard to do using my SQLiteDatabase information.
Here are the classes I have...
My Closet.java class(with my getter methods)
package com.example.android.myshoecloset;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by man on 12/21/2017.
*/
public class Closet
{
private static final String TAG = Closet.class.getSimpleName();
//Brand name
private final String brandName;
//Shoe Name
private final String shoeName;
//Image of the shoe
private final String shoeImage;
public Closet(String brandName, String shoeName, String shoeImage)
{
this.brandName = brandName;
this.shoeName = shoeName;
this.shoeImage = shoeImage;
}
public Closet(Cursor cursor)
{
this.brandName = null;
this.shoeName = null;
this.shoeImage = null;
}
public String getShoeImageName()
{
return shoeImage;
}
public String getBrandName()
{
return brandName;
}
public String getShoeName()
{
return shoeName;
}
}
My Adapter Class(CustomAdapter.java)
package com.example.android.myshoecloset.data;
/*Assume appropriate imports*/
/**
* Created by man on 11/23/2017.
*/
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.TaskHolder> {
private Cursor mCursor;
private Context mContext;
public static String shoeName;
public static String brandName;
public static byte[] byteArray;
public CustomAdapter(Context mContext) {
this.mContext = mContext;
}
public CustomAdapter()
{
mContext = null;
}
/* ViewHolder for each task item */
public class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView shoeBrandName;
public TextView shoeName;
public ImageView shoeImage;
public LinearLayout linearLayout;
public TaskHolder(final View itemView) {
super(itemView);
itemView.setOnClickListener(this);
shoeBrandName = (TextView) itemView.findViewById(R.id.textBrandName);
shoeImage = (ImageView) itemView.findViewById(R.id.shoeImage);
shoeName = (TextView) itemView.findViewById(R.id.textShoeName);
linearLayout = (LinearLayout) itemView.findViewById(R.id.linear_closet);
}
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), ShoeDetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(i);
}
}
#Override
public TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemView = inflater
.inflate(R.layout.text_row_item, parent, false);
return new TaskHolder(itemView);
}
#Override
public void onBindViewHolder(TaskHolder holder, int position) {
int idIndex = mCursor.getColumnIndex(DatabaseContract.ShoeColumns._ID);
int imgValue = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_IMAGE);
int shoeBrandName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_BRAND);
int shoeName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_NAME);
mCursor.moveToPosition(position);
final int id = mCursor.getInt(idIndex);
byte[] shoeImg = mCursor.getBlob(imgValue);
String brandNameStr = mCursor.getString(shoeBrandName);
String shoeNameStr = mCursor.getString(shoeName);
Bitmap bmp = BitmapFactory.decodeByteArray(shoeImg, 0, shoeImg.length);
holder.itemView.setTag(id);
holder.shoeImage.setImageBitmap(Bitmap.createScaledBitmap(bmp, 100, 100, false));
holder.shoeBrandName.setText(brandNameStr);
holder.shoeName.setText(shoeNameStr);
holder.getAdapterPosition();
CustomAdapter.shoeName = shoeNameStr;
CustomAdapter.brandName = brandNameStr;
CustomAdapter.byteArray = mCursor.getBlob(imgValue);
}
#Override
public int getItemCount() {
return (mCursor != null) ? mCursor.getCount() : 0;
}
public void swapCursor(Cursor cursor) {
if (mCursor != null) {
mCursor.close();
}
mCursor = cursor;
notifyDataSetChanged();
}
}
My ClosetFragment, which loads the information on a Loader and to the fragments recyclerview.
package com.example.android.myshoecloset;
/*Assume appropriate imports*/
public class ClosetFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "ClosetFragment";
protected RecyclerView mRecyclerView;
protected CustomAdapter mAdapter;
private static final int CUSTOM_LOADER_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_closet, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
mAdapter = new CustomAdapter(getActivity().getApplicationContext());
mRecyclerView.setAdapter(mAdapter);
getActivity().getSupportLoaderManager().initLoader(CUSTOM_LOADER_ID, null, this);
return rootView;
}
#Override
public void onResume()
{
super.onResume();
getActivity().getSupportLoaderManager().restartLoader(CUSTOM_LOADER_ID, null, this); }
#Override
public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {
return new AsyncTaskLoader<Cursor>(getActivity().getApplicationContext()) {
Cursor mTaskData = null;
#Override
protected void onStartLoading()
{
if(mTaskData != null)
{
deliverResult(mTaskData);
}
else
{
forceLoad();
}
}
public Cursor loadInBackground()
{
try
{
return getActivity().getApplicationContext().getContentResolver().query(DatabaseContract.CONTENT_URI,
null,
null,
null,
null);
} catch(Exception e)
{
Log.e("", "Failed to asynchronously load data.");
e.printStackTrace();
return null;
}
}
public void deliverResult(Cursor data)
{
mTaskData = data;
super.deliverResult(data);
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader)
{
mAdapter.swapCursor(null);
}
}
Finally here is my DetailsActivity(when the recyclerview item is clicked this is where the click will take you)
package com.example.android.myshoecloset;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.myshoecloset.data.CustomAdapter;
public class ShoeDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoe_detail);
ImageView imgShoe = (ImageView) findViewById(R.id.shoeImgDetails);
TextView brandShoe = (TextView) findViewById(R.id.shoeBrandDetails);
TextView nameShoe = (TextView) findViewById(R.id.shoeNameDetails);
byte[] b = getIntent().getByteArrayExtra("ImageBit");
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
imgShoe.setImageBitmap(bmp);
brandShoe.setText(getIntent().getStringExtra("ShoeName"));
nameShoe.setText(getIntent().getStringExtra("BrandName"));
}
}
Thanks!
As far as I can tell, the relevant pieces of your code are the onClick method in your view holder:
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), ShoeDetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(i);
}
And the onCreate method in your details activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
byte[] b = getIntent().getByteArrayExtra("ImageBit");
...
brandShoe.setText(getIntent().getStringExtra("ShoeName"));
nameShoe.setText(getIntent().getStringExtra("BrandName"));
}
In the details activity, you're trying to pull information out of the intent extras... but you've never provided that information in the first place. Making this information available to your view holder will require re-thinking how you've implemented the view holder itself.
I believe you should be able to use the viewholder's "adapter position" to get the necessary info out of your cursor at click time. Maybe something like this:
#Override
public void onClick(View v) {
int position = getAdapterPosition();
mCursor.moveToPosition(position);
Intent i = new Intent(v.getContext(), ShoeDetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
int imgValue = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_IMAGE);
int shoeBrandName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_BRAND);
int shoeName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_NAME);
i.putExtra("ImageBit", mCursor.getBlob(imgValue));
i.putExtra("ShoeName", mCursor.getString(shoeBrandName));
i.putExtra("BrandName", mCursor.getString(shoeName));
v.getContext().startActivity(i);
}
(Note that "ShoeName" and "BrandName" appear to be swapped, but they're also swapped in your details activity so I left them that way.)
If this getAdapterPosition() + mCursor method doesn't work for you, you can always pass the necessary information to the view holder at bind time, and update the onClick() method when binding.
Let me know if this works for you. If it doesn't, we can try to figure it out from here.
I have one custom list view adapter loading contact list. When I open app, contacts are loading perfectly , but once I came back after scrolling to Preference Fragment, listview is empty. Though Data is collected by calling Inner class LoadContact but nothing in listview. There are three fragments. pls guide.
Code for Fragment (tab1). If u see I added adapter initialization in oncreatview as otherwise on back tab I m getting Null point exception. m I did correct here?
public class Requestor extends Fragment {
EditText targetdevice;
ListView recentlist;
List<String> recentlistarray = new ArrayList<>();
ArrayAdapter arrayAdapter;
Dialog dialog;
String targetmobile, requesttype;
private TextView tex1, remotelocation;
int deviceid;
LinearLayout contactlayout;
RadioButton radiorecent, radiocontact;
ArrayList<ContactListSelectUser> contactListSelectUsers;
List<ContactListSelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;
// Pop up
ContentResolver resolver;
SearchView search;
ContactListAdapter adapter;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LoadContact loadContact = new LoadContact();
loadContact.execute();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) throws NullPointerException{
View view = inflater.inflate(R.layout.autolocationrequester, container, false);
targetdevice = (EditText) view.findViewById(R.id.targetdevice);
recentlist = (ListView) view.findViewById(R.id.targetlist);
remotelocation = (TextView) view.findViewById(R.id.remotelocationreq);
tex1 = (TextView) view.findViewById(R.id.tex1);
requesttype = "Location";
radiorecent = (RadioButton) view.findViewById(R.id.radiorecent);
radiocontact = (RadioButton) view.findViewById(R.id.radiocontact);
contactlayout = (LinearLayout) view.findViewById(R.id.contactlayout);
tex1 = (TextView) view.findViewById(R.id.tex1);
recentlist.setVisibility(View.GONE);
contactlayout.setVisibility(View.GONE);
tex1.setVisibility(View.GONE);
contactListSelectUsers = new ArrayList<ContactListSelectUser>();
resolver = getActivity().getApplicationContext().getContentResolver();
listView = (ListView) view.findViewById(R.id.contacts_list);
adapter = new ContactListAdapter(contactListSelectUsers, getActivity().getApplicationContext());
phones = getActivity().getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
LoadContact loadContact = new LoadContact();
loadContact.execute();
search = (SearchView) view.findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
adapter.filter(newText);
return false;
}
});
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
deviceid = Integer.parseInt(sharedPreferences.getString("deviceid", ""));
remotelocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
arrayAdapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, recentlistarray);
recentlist.setAdapter(arrayAdapter);
targetmobile = targetdevice.getText().toString();
new sendreqloc().execute();
targetdevice.setText("");
// Popup.smallpopup("hi", getApplicationContext());
}
});
radiorecent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recentlist.setVisibility(View.VISIBLE);
tex1.setVisibility(View.VISIBLE);
contactlayout.setVisibility(View.GONE);
targetdevice.setText("");
}
});
radiocontact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recentlist.setVisibility(View.GONE);
contactlayout.setVisibility(View.VISIBLE);
tex1.setVisibility(View.GONE);
targetdevice.setText("");
LoadContact loadContact = new LoadContact();
loadContact.execute();
}
});
return view;
}
public class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
// Toast.makeText(Requestor.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
}
while (phones.moveToNext()) {
Log.d("Contact Class Called","");
Bitmap bit_thumb = null;
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
Log.e("No Image Thumb", "--------------");
}
} catch (IOException e) {
e.printStackTrace();
}
ContactListSelectUser contactListSelectUser = new ContactListSelectUser();
contactListSelectUser.setThumb(bit_thumb);
contactListSelectUser.setName(name);
contactListSelectUser.setPhone(phoneNumber);
contactListSelectUser.setEmail(id);
// contactListSelectUser.setCheckedBox(false);
// if (!contactListSelectUsers.contains(contactListSelectUser.getPhone())) {
contactListSelectUsers.add(contactListSelectUser);
//}
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
//System.out.println(contactListSelectUsers.size());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new ContactListAdapter(contactListSelectUsers, getActivity());
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("search", "here---------------- listener");
ContactListSelectUser data = contactListSelectUsers.get(i);
targetdevice.setText(data.getPhone());
}
});
listView.setFastScrollEnabled(true);
}
}
/* #Override
protected void onStop() {
super.onStop();
phones.close();
}*/
}
Custom Adapter class code:
public class ContactListAdapter extends BaseAdapter implements Filterable {
public List<ContactListSelectUser> _data;
private ArrayList<ContactListSelectUser> arraylist;
Context _c;
ViewHolder v;
RoundImage roundedImage;
private Filter filter = new CustomFilter();
public ContactListAdapter(List<ContactListSelectUser> contactListSelectUsers, Context context) {
_data = contactListSelectUsers;
_c = context;
this.arraylist = new ArrayList<ContactListSelectUser>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.contact_info, null);
Log.e("Inside", "here--------------------------- In view1");
} else {
view = convertView;
Log.e("Inside", "here--------------------------- In view2");
}
v = new ViewHolder();
v.title = (TextView) view.findViewById(R.id.name);
// v.check = (CheckBox) view.findViewById(R.id.check);
v.phone = (TextView) view.findViewById(R.id.no);
v.imageView = (ImageView) view.findViewById(R.id.pic);
final ContactListSelectUser data = (ContactListSelectUser) _data.get(i);
v.title.setText(data.getName());
// v.check.setChecked(data.getCheckedBox());
v.phone.setText(data.getPhone());
// Set image if exists
try {
if (data.getThumb() != null) {
v.imageView.setImageBitmap(data.getThumb());
} else {
v.imageView.setImageResource(R.mipmap.ic_launcher);
}
// Seting round image
Bitmap bm = BitmapFactory.decodeResource(view.getResources(), R.mipmap.ic_launcher); // Load default image
roundedImage = new RoundImage(bm);
v.imageView.setImageDrawable(roundedImage);
} catch (OutOfMemoryError e) {
// Add default picture
v.imageView.setImageDrawable(this._c.getDrawable(R.mipmap.ic_launcher));
e.printStackTrace();
}
Log.e("Image Thumb", "--------------" + data.getThumb());
/*// Set check box listener android
v.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
if (checkBox.isChecked()) {
data.setCheckedBox(true);
} else {
data.setCheckedBox(false);
}
}
});*/
view.setTag(data);
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
_data.clear();
if (charText.length() == 0) {
_data.addAll(arraylist);
} else {
for (ContactListSelectUser wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
_data.add(wp);
}
}
}
notifyDataSetChanged();
}
#Override
public Filter getFilter() {
return filter;
}
static class ViewHolder {
ImageView imageView;
TextView title, phone;
CheckBox check;
}
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
_data.clear();
FilterResults filterResults = new FilterResults();
filterResults.values = _data;
filterResults.count = _data.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if (filterResults.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
below is logcat where u can see data is fetched while I choose back fragment but not set to listview.
E/Inside: here--------------------------- In view1
E/Image Thumb: --------------null
E/Inside: here--------------------------- In view1
E/Image Thumb: --------------null
I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
E/count: 2
E/No Image Thumb: --------------
E/No Image Thumb: --------------
E/count: 2
E/count: 2
implements Filterable in BaseAdapter
public class ContactListAdapter extends BaseAdapter implements Filterable
and add value :
private Filter filter = new CustomFilter();
and create class in your baseAdapter:
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
_data.clear();
if (arraylist != null && constraint != null) {
for (int i = 0; i < arraylist.size(); i++) {
if (arraylist.get(i).toString().toLowerCase().contains(constraint)) {
_data.add(arraylist.get(i));
}
}
}
FilterResults results = new FilterResults();
results.values = _data;
results.count = _data.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
add in your baseAdapter class:
#Override
public Filter getFilter() {
return filter;
}
my adapter for example:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CustomArrayAdapter extends BaseAdapter implements Filterable{
private LayoutInflater mInflater;
private final Context context;
private List<String> mItems;
private Filter filter = new CustomFilter();
private ArrayList<String>mItemsSuggestion = new ArrayList<String>();
public CustomArrayAdapter(Context context, String[] values) {
this.context = context;
mItems = Arrays.asList(values);
}
#Override
public int getCount() {
return mItemsSuggestion.size();
}
#Override
public Object getItem(int position) {
return mItemsSuggestion.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View oneView = mInflater.inflate(R.layout.towar_list, parent, false);
TextView text = (TextView)oneView.findViewById(R.id.towaryAllList);
text.setText(mItemsSuggestion.get(position).toString());
return oneView;
}
#Override
public Filter getFilter() {
return filter;
}
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
mItemsSuggestion.clear();
if (mItems != null && constraint != null) {
for (int i = 0; i < mItems.size(); i++) {
if (mItems.get(i).toString().toLowerCase().contains(constraint)) {
mItemsSuggestion.add(mItems.get(i));
}
}
}
FilterResults results = new FilterResults();
results.values = mItemsSuggestion;
results.count = mItemsSuggestion.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
I solved it now. The issue was only placing search view code in radiocontact on click listeners instead of in createview method directly.
I have a Listview with two adapters. They receive an Array with some data and when scrolled to bottom of the listview more data is loaded into the Array and here the listview should add the new data.
Question:
How can I make the listview reflect the new data and why isn't it updated when I call adAdapter.notifyDataSetChanged(); ?
Fragments inner class where I download data & update UI in onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
// list.setAdapter(adapter); this works when adapter.notifyDataSetChanged(); also is in the else statement but here I don't use the BannerAdListView2 adapter which i want to?
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
// adapter.notifyDataSetChanged(); // Here the listview should get refresh with the new data
adAdapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
// Attach the listener to the AdapterView onCreate
list.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if(pageNumberInt < totalPagesInt){
++incre;
new DownloadJSON().execute();
}
}
});
}
Here is my SearchListViewAdapter:
public class SearchListViewAdapter extends BaseAdapter{
Context context;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> mylist = new HashMap<>();
static String url;
static String title;
public SearchListViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row
final ViewHolder holder;
/*
* If convertView is not null, reuse it directly, no inflation
* Only inflate a new View when the convertView is null.
*/
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder();
holder.poster = (ImageView) convertView.findViewById(R.id.list_image);
holder.textForTitle = (TextView) convertView.findViewById(R.id.search_title);
holder.textForTitle.setTag(position);
convertView.setTag(holder);
}
else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
holder.textForTitle.setTag(data.get(position));
}
mylist = data.get(position);
final String mediaType = mylist.get("media_type");
if (mediaType.equals("movie")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("title");
} else if (mediaType.equals("tv")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("original_name");
} else {
String posterPath = mylist.get("profile_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("name");
}
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
// load image url into poster
Picasso.with(context).load(url).into(holder.poster);
// set title to textview
holder.textForTitle.setText(title);
return convertView;
}
class ViewHolder {
ImageView poster;
TextView textForTitle;
}
}
And my BannerAdListView2 adapter:
public class BannerAdListView2 extends BaseAdapter
{
Activity activity;
Context context;
BaseAdapter delegate;
int k = 7;
int baseItems;
int noAds;
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// Total count includes list items and ads.
return baseItems + noAds;
}
#Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return delegate.getItem(getOffsetPosition(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return delegate.getViewTypeCount() + noAds;
}
#Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return delegate.getViewTypeCount();
} else {
return delegate.getItemViewType(getOffsetPosition(position));
}
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && delegate.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
if (position < k) return false;
// Calculate current offset caused by ads already embedded
if (position==k){
return true;
}
else {
return isItemAnAd(position-k);
}
}
// Get the position that is offset by the insertion of the ads
private int getOffsetPosition(int position) {
int currentNoAds = position / k;
return position - currentNoAds;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Display every n list items
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
// Don’t instantiate new AdView, reuse old one
return convertView;
} else {
// Create a new AdView
AdView adView = new AdView(activity);
adView.setAdSize(AdSize.BANNER);
String bannerId = "My unit id";
adView.setAdUnitId(bannerId);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Convert the default layout parameters so that they play nice with
// ListView.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest bannerIntermediateReq = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("d9e108ab") //means that a test ad is shown on my phone
.build();
adView.loadAd(bannerIntermediateReq);
return adView;
}
} else {
// Offload displaying other items to the delegate
return delegate.getView(getOffsetPosition(position) ,
convertView, parent);
}
}
}
Edit:
Changed the constructor of BannerAdListView2
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, final BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
delegate.registerDataSetObserver(new DataSetObserver() {
public void onChanged() {
baseItems = delegate.getCount();
noAds = baseItems / k;
}
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
And in fragment
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
adapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
}
Try this solution ... DecorerAdapter:
public static abstract class DecorerAdapter extends BaseAdapter {
public int DECORER_ITEM_TYPE;
private final BaseAdapter mInnerAdapter;
private final int mRepeatAfterEvery;
private int mCount;
public DecorerAdapter(BaseAdapter innerAdapter, int repeatAfterEvery) {
mInnerAdapter = innerAdapter;
mRepeatAfterEvery = repeatAfterEvery;
mInnerAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
setupAdapter();
}
#Override
public void notifyDataSetChanged() {
setupAdapter();
super.notifyDataSetChanged();
}
private void setupAdapter(){
mCount = mInnerAdapter.getCount();
mCount += (mCount + mRepeatAfterEvery - 2) / (mRepeatAfterEvery - 1);
DECORER_ITEM_TYPE = mInnerAdapter.getViewTypeCount();
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(int position) {
if(position % mRepeatAfterEvery == 0)
return null;
return mInnerAdapter.getItem(calculateInnerPosition(position));
}
private int calculateInnerPosition(int position) {
return position - (position + mRepeatAfterEvery - 1) / mRepeatAfterEvery;
}
#Override
public long getItemId(int position) {
if(position % mRepeatAfterEvery == 0)
return -1;
return mInnerAdapter.getItemId(calculateInnerPosition(position));
}
#Override
public int getItemViewType(int position) {
if(position % mRepeatAfterEvery == 0)
return DECORER_ITEM_TYPE;
return mInnerAdapter.getItemViewType(calculateInnerPosition(position));
}
#Override
public boolean hasStableIds() {
return mInnerAdapter.hasStableIds();
}
#Override
public int getViewTypeCount() {
return mInnerAdapter.getViewTypeCount() + 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position % mRepeatAfterEvery == 0)
return getDecorerView((position + mRepeatAfterEvery - 1) / mRepeatAfterEvery, convertView, parent);
return mInnerAdapter.getView(calculateInnerPosition( position), convertView, parent);
}
public abstract View getDecorerView(int position, View convertView, ViewGroup parent);
}
code with usage:
package pl.selvin.decoreradapter;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
/*** paste the DecorerAdapter class here ***/
public static class MyListFragment extends ListFragment{
final ArrayList<String> strings = new ArrayList<>();
private BaseAdapter innerAdapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add("Add rnd(10) more");
super.onCreateOptionsMenu(menu, inflater);
}
final Random rnd = new Random();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final String[] toAdd = new String[rnd.nextInt(10)];
int start = strings.size();
for(int i = 0; i < toAdd.length; i++)
toAdd[i] = (start + i) + "";
Collections.addAll(strings, toAdd);
Toast.makeText(getActivity(), "Added " + toAdd.length + " count: " + strings.size(), Toast.LENGTH_SHORT).show();
innerAdapter.notifyDataSetChanged();
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
for(int i = 0; i < 4; i++) {
strings.add(i + "");
}
innerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, strings);
setListAdapter(new DecorerAdapter(innerAdapter, 5) {
#Override
public View getDecorerView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = new TextView(getActivity());
convertView.setBackgroundColor(Color.RED);
}
((TextView)convertView).setText("AdView: " + position);
return convertView;
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String)l.getItemAtPosition(position);
Toast.makeText(getActivity(), "Item click: " + (item == null ? "ADVIEW" : item), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new MyListFragment(), "LIST").commit();
}
}
}
It repeats decorer view at every element passed to the constructor ...
all you need to do is implement getDecorerView in the similar way as getView in normal adapter
I've a problem with listview in android, I've created a list view that takes data from SQLite database with a custom ArrayAdapter
I want to display an image view when user choose an item, but when I click on an item, the image (check mark) shows in 3 other items
I don't know where is the problem exactly, here is my code for adapter :
import info.androidhive.tabsswipe.R;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.itdinamik.tabswipe.CompareVehicle;
import com.itdinamik.vcompare.MySQLiteHelper;
import com.itdinamik.vcompare.Vehicle;
public class ComperAdapter extends ArrayAdapter<Vehicle>{
List<Vehicle> data;
Context context;
int layoutResID;
Vehicle itemdata;
MySQLiteHelper dbhelper;
public ComperAdapter(Context context, int layoutResourceId, List<Vehicle> data) {
super(context, layoutResourceId, data);
this.data=data;
this.context=context;
this.layoutResID=layoutResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final NewsHolder holder;
View row = convertView;
dbhelper = new MySQLiteHelper(context);
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResID, parent, false);
holder = new NewsHolder();
holder.itemNameTitle = (TextView)row.findViewById(R.id.VehicleTxt);
holder.itemNameScore = (TextView)row.findViewById(R.id.Score);
holder.CheckedMark=(ImageView)row.findViewById(R.id.Checked);
holder.Vehicle=(ImageView)row.findViewById(R.id.Vehicle);
holder.RL = (RelativeLayout)row.findViewById(R.id.Rv);
row.setTag(holder);
}
else
{
holder = (NewsHolder)row.getTag();
}
//Toast.makeText(getContext(), String.valueOf(position +" - " + CompareVehicle.ClickedItem), Toast.LENGTH_SHORT).show();
if(CompareVehicle.ItemClieckd) {
if(position == CompareVehicle.ClickedItem) {
Log.w("Position", String.valueOf(position));
holder.CheckedMark.setVisibility(View.VISIBLE);
holder.RL.setBackgroundColor(Color.rgb(201, 50, 39));
}
}
itemdata = data.get(position);
holder.itemNameTitle.setText(itemdata.getTitle() + " - " + itemdata.getKraj() + " - "+ String.valueOf(position) + " - " + CompareVehicle.ClickedItem);
double totaldefault = itemdata.getOhranjenost()*0.25+itemdata.getPrevozeni()*0.16+
itemdata.getServis()*0.14+ itemdata.getCena()*0.13+
itemdata.getPoraba()*0.11+ itemdata.getStarost()*0.08+
itemdata.getDodatna()*0.07+ itemdata.getCenaZav()*0.06;
holder.itemNameScore.setText(String.format("%.1f",totaldefault));
return row;
}
static class NewsHolder{
TextView itemNameTitle;
TextView itemNameScore;
ImageView CheckedMark, Vehicle;
RelativeLayout RL;
}
}
and this one is for my fragment that i use to show my list view
import info.androidhive.tabsswipe.R;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.itdinamik.tabswipe.adapter.ComperAdapter;
import com.itdinamik.vcompare.MySQLiteHelper;
import com.itdinamik.vcompare.Vehicle;
public class CompareVehicle extends Fragment{
ViewPager mViewPager;
ArrayList<Vehicle> DataList;
static MySQLiteHelper dbhelper;
ComperAdapter adapter;
List<Vehicle> itemData;
ListView lv;
Button CompareButton;
int ClickedNum = 0;
public static int ClickedItem;
public static boolean ItemClieckd = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_compare_vehicle, container, false);
lv = (ListView)rootView.findViewById(R.id.CompareList);
CompareButton = (Button)rootView.findViewById(R.id.CompareButton);
dbhelper = new MySQLiteHelper(getActivity());
// get all vehicles
itemData = dbhelper.getAllVehicles();
adapter=new ComperAdapter(getActivity(),R.layout.list_single,itemData);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
ClickedItem = position;
ItemClieckd = true;
ClickedNum += 1;
adapter.notifyDataSetChanged();
/*RelativeLayout Rl = (RelativeLayout)arg1.findViewById(R.id.Rv);
ImageView CheckImg = (ImageView)arg1.findViewById(R.id.Checked);
Rl.setBackgroundColor(Color.rgb(201, 50, 39));
CheckImg.setVisibility(View.VISIBLE);*/
//Toast.makeText(getActivity(), String.valueOf(mSelectedItem), Toast.LENGTH_LONG).show();
}
});
CompareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (ClickedNum < 2) {
Toast.makeText(getActivity(), "Please mark at least 2 items to compare them", Toast.LENGTH_LONG).show();
}
}
});
return rootView;
}
}
thank you
To avoid issues with view recycling in ListViews etc, I include a boolean for checked state in the item data List supplied to the constructor of the ArrayAdapter. I also provide my own interface for handling things like click events on child Views contained in my custom list item layout.
In my example below we handle a checkbox which can be clicked and also a label which can be long clicked:
public class MyListAdapter extends ArrayAdapter<MyItem> {
// interface for handling item child view events
public interface MyListAdapterListener {
void onItemCheckClicked(int index);
void onItemLabelLongClicked(int index);
}
private MyListAdapterListener mMyListAdapterListener;
int layoutResID;
// Constructor
public MyListAdapter(Context context, int resource, List<MyItem> myItems) {
super(context, resource, myItems);
layoutResID = resource;
}
public void setMyListAdapterListener(MyListAdapterListener listener) {
this.mMyListAdapterListener = listener;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setup the row
View row;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
row = inflater.inflate(layoutResID, null);
} else {
row = convertView;
}
// setup the ViewHolder for this item
ViewHolder holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
// setup this item's label view
holder.label.setText(getItem(position).label);
// tag this item's label view with position so it can be retrieved in the onLongClick
holder.label.setTag(position);
// set the OnLongClickListener for the this item's label view
holder.label.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mActivityListListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemLabelLongClicked method
mActivityListListener.onItemLabelLongClicked((Integer)v.getTag());
}
return false;
}
});
// setup this item's checkbox view
holder.checkbox.setChecked(getItem(position).myItemCheckBoolean);
// tag this item's checkbox view with position so it can be retrieved in the onClick
holder.checkbox.setTag(position);
// set the OnClickListener for the this item's checkbox view
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mMyListAdapterListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemCheckClicked method
mMyListAdapterListener.onItemCheckClicked((Integer) v.getTag());
}
}
});
return row;
}
class ViewHolder {
CheckBox checkbox = null;
TextView label = null;
ViewHolder(View row) {
this.checkbox = (CheckBox) row.findViewById(R.id.check_box);
this.label = (TextView) row.findViewById(R.id.item_label);
}
}
}
The MyItem class:
public class MyItem {
public String label;
public boolean myItemCheckBoolean;
}
Using the ArrayAdapter:
public class MyFragment extends Fragment {
....
private List<MyItem> myItems = new ArrayList<MyItem>();
....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment__my_list, container, false);
lv = (ListView)rootView.findViewById(R.id.my_list);
// For example purposes, fill myItems with dummy data setting all checkboxes initially to false
for (int i = 0; i < 10; i++) {
MyItem myItem = new MyItem();
myItem.label = "Item " + i;
myItem.myItemCheckBoolean = false;
myItems.add(myItem);
}
MyListAdapter adapter = new MyListAdapter(getActivity(), R.layout.my_list_item, myItems);
adapter.setMyListAdapterListener( new MyListAdapter.MyListAdapterListener() {
#Override
public void onItemCheckClicked(int index) {
Log.d("MyFragment", "Item " + index + " Check Clicked");
// toggle the item's boolean
myItems.get(index).myItemCheckBoolean = !myItems.get(index).myItemCheckBoolean;
}
#Override
public void onItemLabelLongClicked(int index) {
Log.d("MyFragment", "Item " + index + " Label LongClicked");
}
}
lv.setAdapter(adapter);
....
return rootView;
}
Additional:
In response to your comment, you can use the adapter to customize the display of your list items as you wish. The version below shows how you might modify the adapter to use an ImageView instead of a CheckBox, and also changes the background color:
public class MyListAdapter extends ArrayAdapter<MyItem> {
// interface for handling item child view events
public interface MyListAdapterListener {
void onItemCheckClicked(int index);
void onItemLabelLongClicked(int index);
}
private MyListAdapterListener mMyListAdapterListener;
int layoutResID;
// Constructor
public MyListAdapter(Context context, int resource, List<MyItem> myItems) {
super(context, resource, myItems);
layoutResID = resource;
}
public void setMyListAdapterListener(MyListAdapterListener listener) {
this.mMyListAdapterListener = listener;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setup the row
View row;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
row = inflater.inflate(layoutResID, null);
} else {
row = convertView;
}
// setup the ViewHolder for this item
ViewHolder holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
// setup this item's label view
holder.label.setText(getItem(position).label);
// tag this item's label view with position so it can be retrieved in the onLongClick
holder.label.setTag(position);
// set the OnLongClickListener for the this item's label view
holder.label.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mActivityListListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemLabelLongClicked method
mActivityListListener.onItemLabelLongClicked((Integer)v.getTag());
}
return false;
}
});
// setup this item's image view based on the current state of the boolean
if (getItem(position).myItemCheckBoolean) {
holder.image.setImageResource(R.drawable.image_a);
} else {
holder.image.setImageResource(R.drawable.image_b);
}
// tag this item's image view with position so it can be retrieved in the onClick
holder.image.setTag(position);
// set the OnClickListener for the this item's image view
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mMyListAdapterListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemCheckClicked method
mMyListAdapterListener.onItemCheckClicked((Integer) v.getTag());
}
}
});
// setup this item's background based on the current state of the boolean
if (getItem(position).myItemCheckBoolean) {
holder.layout.setBackgroundColor(Color.red);
} else {
holder.layout.setBackgroundColor(Color.white);
}
return row;
}
class ViewHolder {
ImageView image = null;
TextView label = null;
RelativeLayout layout = null;
// constructor
ViewHolder(View row) {
this.image = (ImageView) row.findViewById(R.id.item_image);
this.label = (TextView) row.findViewById(R.id.item_label);
this.layout = (RelativeLayout) row.findViewById(R.id.item_layout)
}
}
}
I need yout help. How to add Ad Unit (NativeAd) within a List of Articles, using Facebook Audience Network https://developers.facebook.com/docs/audience-network/android/native-api. Im not programmer and need all code how it should be. The ads have to be between posts (listview)Thanks
import com.facebook.ads.*;
public class Posts extends Fragment{
ArrayList<Post> mPosts;
private static final String KEY_CONTENT = "PostsFragment:array";
boolean isLoadMore = false;
int mPageCount = 0;
int mCurrectPage = 1;
PullToRefreshListView mListView;
MyAdapter mListViewAdapter;
View mLoadingFooter;
private Tracker tracker;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.tracker = EasyTracker.getInstance(this.getActivity());
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mPosts = (ArrayList<Post>) savedInstanceState.getSerializable(KEY_CONTENT);
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
#Override
public void onResume() {
super.onResume();
this.tracker.set(Fields.SCREEN_NAME, "Article");
this.tracker.send( MapBuilder.createAppView().build() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_CONTENT, mPosts);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View _result = inflater.inflate(R.layout.list, null);
mLoadingFooter = inflater.inflate(R.layout.loading_footer, null);
mLoadingFooter.setVisibility(View.GONE);
if (mPosts == null)
{
mPosts = new ArrayList<Post>();
loadPostsList();
}
mListView = (PullToRefreshListView) _result.findViewById(R.id.listView);
mListViewAdapter = new MyAdapter(getActivity(), mPosts);
mListView.addFooterView(mLoadingFooter);
mListView.setAdapter(mListViewAdapter);
mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
});
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (totalItemCount > Constant.MIN_ITEM_COUNT && lastInScreen >= (totalItemCount - Constant.MIN_ITEM_COUNT_HALF) && !isLoadMore && mCurrectPage <= mPageCount)
{
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
});
return _result;
}
public void loadPostsList() {
isLoadMore = true;
mLoadingFooter.setVisibility(View.VISIBLE);
new AsynckRequestGet().execute(getActivity(), TYPE_GET_OPERATION.POSTS, CodeRequestManager.codePosts(TempData.getInstance().getToken(), mCurrectPage));
}
private class AsynckRequestGet extends AbstractAsyncRequestGet {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
isLoadMore = false;
if(!isDetached()) {
mLoadingFooter.setVisibility(View.GONE);
mListView.onRefreshComplete();
}
if(result == null) return;
int[] t = JsonParser.parsePageCountResponse(result);
mPageCount = t[0];
mCurrectPage = t[1] +1;
ArrayList<Post> temp = JsonParser.parsePostsResponse(result);
if(temp == null || isDetached())
return;
mPosts.addAll(temp);
mListViewAdapter.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<Post> {
private LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Post> objects) {
super(context, R.layout.post_item, objects);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.post_item, null);
final Post post = getItem(position);
final TextView postLikes = ((TextView) convertView.findViewById(R.id.post_likes));
final TextView postComments = ((TextView) convertView.findViewById(R.id.post_comments));
postComments.setText(post.getCountComment() + "");
postLikes.setText(post.getCountLike() + "");
if(post.isMyLike()) {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_my_icon, 0, 0, 0);
} else {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_icon, 0, 0, 0);
}
postLikes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AbstractAsyncRequestGet().execute(getActivity(), TYPE_GET_OPERATION.LIKE, CodeRequestManager.codeLike(TempData.getInstance().getToken(), post.getId(), post.isMyLike()? 0 : 1));
post.setCountLike((post.getCountLike()) + (post.isMyLike()? -1 : 1));
post.setMyLike(post.isMyLike()? 0 : 1);
postLikes.setText(post.getCountLike() + "");
mListViewAdapter.notifyDataSetChanged();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
((TrainingFragment) getParentFragment().getParentFragment()).showPostDetails(mPosts.get(arg2-1), new DetailListener() {
#Override
public void onRefresh() {
if(!isDetached())
mListViewAdapter.notifyDataSetChanged();
}
})
;}
});
((TextView) convertView.findViewById(R.id.post_title)).setText(post.getTitle());
((TextView) convertView.findViewById(R.id.post_content)).setText(post.getContent());
return convertView;
}
}
}
If you get the latest Facebook Android SDK, you can find the NativeAdSample project updated with how to display native ads in a list view. Code copied from the sample:
package com.facebook.samples.NativeAdSample;
import java.util.ArrayList;
import java.util.List;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.NativeAd;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class NativeAdListActivity extends ListActivity implements AdListener {
private ListView listView;
private ListViewAdapter adapter;
private NativeAd listNativeAd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listNativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
listNativeAd.setAdListener(this);
listNativeAd.loadAd();
listView = getListView();
adapter = new ListViewAdapter(getApplicationContext());
listView.setAdapter(adapter);
}
#Override
public void onAdClicked(Ad ad) {
Toast.makeText(this, "Ad Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdLoaded(Ad ad) {
adapter.addNativeAd((NativeAd) ad);
}
#Override
public void onError(Ad ad, AdError error) {
Toast.makeText(this, "Ad failed to load: " + error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
class ListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Object> list;
private NativeAd ad;
private static final int AD_INDEX = 2;
public ListViewAdapter(Context context) {
list = new ArrayList<Object>();
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 1; i <= 35; i++) {
list.add("ListView Item #" + i);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == AD_INDEX && ad != null) {
// Return the native ad view
return (View) list.get(position);
} else {
TextView view; // Default item type (non-ad)
if (convertView != null && convertView instanceof TextView) {
view = (TextView) convertView;
} else {
view = (TextView) inflater.inflate(R.layout.list_item, parent, false);
}
view.setText((String) list.get(position));
return view;
}
}
public synchronized void addNativeAd(NativeAd ad) {
if (ad == null) {
return;
}
if (this.ad != null) {
// Clean up the old ad before inserting the new one
this.ad.unregisterView();
this.list.remove(AD_INDEX);
this.ad = null;
this.notifyDataSetChanged();
}
this.ad = ad;
View adView = inflater.inflate(R.layout.ad_unit, null);
NativeAdSampleActivity.inflateAd(ad, adView, NativeAdListActivity.this);
list.add(AD_INDEX, adView);
this.notifyDataSetChanged();
}
}
}