I'm making a ListView with text and images. Everything is okay but when I click on one of the list item the application is terminated and it shows the following:
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! E/AndroidRuntime:
Error reporting crash
android.os.TransactionTooLargeException
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:496)
at android.app.ActivityManagerProxy.handleApplicationCrash(ActivityManagerNative.java:4716)
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:95)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
Here's the code:
public class RowItem {
private String title ;
private String descreption;
private int pic_id;
public RowItem(String title, String descreption, int pic_id) {
this.title = title;
this.descreption = descreption;
this.pic_id = pic_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescreption() {
return descreption;
}
public void setDescreption(String descreption) {
this.descreption = descreption;
}
public int getPic_id() {
return pic_id;
}
public void setPic_id(int pic_id) {
this.pic_id = pic_id;
}
}
public class CustomAdapter extends BaseAdapter{
Context context;
List<RowItem> rowItems;
public CustomAdapter(Context context, List<RowItem> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItemId(position));
}
private class ViewHolder{
ImageView imageView ;
TextView Title;
TextView descrip;
}
#Override
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView==null){
convertView = inflater.inflate(R.layout.list_item,null);
holder=new ViewHolder();
holder.Title= (TextView)convertView.findViewById(R.id.title);
holder.imageView=(ImageView)convertView.findViewById(R.id.pic1);
holder.descrip=(TextView)convertView.findViewById(R.id.descrption);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();}
RowItem row_po = rowItems.get(position);
holder.imageView.setImageResource(row_po.getPic_id());
holder.Title.setText(row_po.getTitle());
holder.descrip.setText(row_po.getDescreption());
return convertView;
}
}
public class ExploreActivity extends Activity {
String[] Title;
TypedArray pics;
String[] description;
List<RowItem> rowItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore);
poplatelistview();
mylistview = (ListView) findViewById(R.id.list);
CustomAdapter adapter = new CustomAdapter(this, rowItems);
mylistview.setAdapter(adapter);
rgistercalback();
}
private void poplatelistview() {
rowItems = new ArrayList<RowItem>();
Title = getResources().getStringArray(R.array.Title);
pics = getResources().obtainTypedArray(R.array.pics);
description = getResources().getStringArray(R.array.Descrpsions);
for (int i = 0; i < Title.length; i++) {
RowItem item = new RowItem(Title[i], description[i], pics.getResourceId(i, -1));
rowItems.add(item);
}
}
private void rgistercalback() {
ListView list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title = rowItems.get(position).getTitle();
Toast.makeText(getApplicationContext(),""+title,Toast.LENGTH_LONG).show();
}
});
}
}
Please try this in your custom adapter class
#Override
public int getCount() {
return rowItems.size();
}
#Override
public RowItem getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
Hope it will work.
Related
I'm creating a Movie Catalog app using themoviedb API. How can I implement search using EditText?
I have a list view that contains the movie info.
App screenshot:
Now I want to use the EditText to find another movie, and the list view updated. How do I do that?
My loader:
public class MyAsyncTaskLoader extends AsyncTaskLoader<ArrayList<MovieItem>> {
public ArrayList<MovieItem> mData;
public boolean hasResult = false;
public MyAsyncTaskLoader(final Context context) {
super(context);
onContentChanged();
Log.d("INIT ASYNCLOADER","1");
}
#Override
protected void onStartLoading() {
Log.d("Content Changed","1");
if (takeContentChanged())
forceLoad();
else if (hasResult)
deliverResult(mData);
}
#Override
public void deliverResult(final ArrayList<MovieItem> data) {
mData = data;
hasResult = true;
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
if (hasResult) {
onReleaseResources(mData);
mData = null;
hasResult = false;
}
}
public static String Search = "Avengers";
public static String API_KEY = "f00e74c69ff0512cf9e5bf128569f6b5";
#Override
public ArrayList<MovieItem> loadInBackground() {
Log.d("LOAD BG","1");
SyncHttpClient client = new SyncHttpClient();
final ArrayList<MovieItem> movieItemses = new ArrayList<>();
final String url = "https://api.themoviedb.org/3/search/movie?api_key="+API_KEY+"&language=en-US&query="+Search;
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
setUseSynchronousMode(true);
}
#Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
try {
String result = new String(responseBody);
JSONObject responseObject = new JSONObject(result);
JSONArray list = responseObject.getJSONArray("results");
for (int i = 0 ; i < list.length() ; i++){
JSONObject movie = list.getJSONObject(i);
MovieItem movieItems = new MovieItem(movie);
movieItemses.add(movieItems);
}
Log.d("REQUEST SUCCESS","1");
}catch (Exception e){
e.printStackTrace();
Log.d("REQUEST FAILED","1");
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
for (int i = 0 ; i< movieItemses.size() ; i++){
Log.d("Title",movieItemses.get(i).getTitle());
}
Log.d("BEFORE RETURN","1");
return movieItemses;
}
protected void onReleaseResources(ArrayList<MovieItem> data) {
//nothing to do.
}
public ArrayList<MovieItem> getResult() {
return mData;
}
}
My adapter:
public class MovieAdapter extends BaseAdapter {
private ArrayList<MovieItem> mData = new ArrayList<>();
private LayoutInflater mInflater;
private Context context;
Activity activity;
private String urlConfig ;
public MovieAdapter(Context context) {
this.context = context;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(ArrayList<MovieItem> items){
mData = items;
notifyDataSetChanged();
}
public void clearData(){
mData.clear();
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MovieItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_row_film, null);
holder.textViewuJudul= (TextView)convertView.findViewById(R.id.tv_judul);
holder.textViewDescription = (TextView)convertView.findViewById(R.id.tv_deskripsi);
holder.textViewRate = (TextView)convertView.findViewById(R.id.tv_rate);
holder.imgPoster = (ImageView) convertView.findViewById(R.id.img_poster);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewuJudul.setText(mData.get(position).getTitle());
holder.textViewDescription.setText(mData.get(position).getDescription());
holder.textViewRate .setText(mData.get(position).getRate());
Picasso.with(context).load(mData.get(position).getImgurl()).into(holder.imgPoster);
return convertView;
}
private class ViewHolder {
public TextView textViewuJudul;
public TextView textViewDescription;
public TextView textViewRate;
public ImageView imgPoster;
}}
The item:
public class MovieItem {
public static String POSTER_BASE_URL = "http://image.tmdb.org/t/p/";
private int id;
private String title;
private String description;
private String rate;
private String imgurl;
public MovieItem(JSONObject object){
try {
String title = object.getString("title");
String description = object.getString("overview");
double movieRatet = object.getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
String releaseDate = object.getString("release_date");
String posterUrl = object.getString("poster_path");
posterUrl = POSTER_BASE_URL + "w185" + posterUrl;
description = description.length() > 64 ? description.substring(0,64)+"...":description;
Log.d("movie poster", posterUrl);
Log.d("movie title ", title);
Log.d("movie description ", description);
Log.d("movie release ", releaseDate);
this.title = title;
this.description = description;
this.rate = releaseDate;
this.imgurl = posterUrl;
}catch (Exception e){
e.printStackTrace();
}
}
My MainActivity:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<MovieItem>>
,View.OnClickListener{
ListView listView;
MovieAdapter adapter;
MyAsyncTaskLoader myAsyncTaskLoader;
private TextView edt_cari;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_cari = (TextView) findViewById(R.id.edt_cari);
adapter = new MovieAdapter(this);
adapter.notifyDataSetChanged();
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<ArrayList<MovieItem>> onCreateLoader(int id, Bundle args) {
Log.d("Create Loader", "1");
return new MyAsyncTaskLoader(this);
}
#Override
public void onLoadFinished(Loader<ArrayList<MovieItem>> loader, ArrayList<MovieItem> data) {
Log.d("Load Finish","1");
adapter.setData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<MovieItem>> loader) {
Log.d("Load Reset","1");
adapter.setData(null);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_cari){
SearchMovieTask searchMovie = new SearchMovieTask();
searchMovie.execute(edt_cari.getText().toString().trim());
}
}
private class SearchMovieTask extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}}
Replace your MovieAdapter to this ...!
public class MovieAdapter extends BaseAdapter implements Filterable {
private ArrayList<MovieItem> mData = new ArrayList<>();
private ArrayList<MovieItem> mSearchData = new ArrayList<>();
private ArrayList<MovieItem> categoryListOne = new ArrayList<>();
private LayoutInflater mInflater;
private Context context;
Activity activity;
ItemFilter mFilter = new ItemFilter();
private String urlConfig;
public MovieAdapter(Context context) {
this.context = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(ArrayList<MovieItem> items) {
mData = items;
mSearchData = items;
notifyDataSetChanged();
}
public void clearData() {
mData.clear();
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MovieItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_row_film, null);
holder.textViewuJudul = (TextView) convertView.findViewById(R.id.tv_judul);
holder.textViewDescription = (TextView) convertView.findViewById(R.id.tv_deskripsi);
holder.textViewRate = (TextView) convertView.findViewById(R.id.tv_rate);
holder.imgPoster = (ImageView) convertView.findViewById(R.id.img_poster);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewuJudul.setText(mData.get(position).getTitle());
holder.textViewDescription.setText(mData.get(position).getDescription());
holder.textViewRate.setText(mData.get(position).getRate());
Picasso.with(context).load(mData.get(position).getImgurl()).into(holder.imgPoster);
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
public class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase().replace(" ", "");
Log.v("DataAdapter", "constratinst : " + constraint);
FilterResults result = new FilterResults();
if (constraint.toString().length() > 0) {
ArrayList<Sticker> filteredItems =
new ArrayList<>();
for (int i = 0, l = mData.size(); i < l; i++) {
// ArrayList<HashMap<String, String>> p =
// originalList.get(i);
String p = mData.get(i).getName().toLowerCase().replace(" ", "");
if (p.toLowerCase().startsWith(String.valueOf(constraint)))
filteredItems.add(mData.get(i));
// if (p.toLowerCase().contains(constraint))
// filteredItems.add(categoryListSearch.get(i));
}
Log.v("DataAdapter", "not blank");
result.count = filteredItems.size();
result.values = filteredItems;
} else {
synchronized (this) {
result.count = categoryListOne.size();
result.values = categoryListOne;
// result.values = dataList;
// result.count = dataList.size();
}
}
return result;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// users = (List<GraphUser>) results.values;
//filteredData = (ArrayList<String>) results.values;
mData = (ArrayList<MovieItem>) results.values;
notifyDataSetChanged();
// for (int i = 0, l = mData.size(); i < l; i++)
// mSearchData.get(i);
//add(productList.get(i));
notifyDataSetInvalidated();
}
}
private class ViewHolder {
public TextView textViewuJudul;
public TextView textViewDescription;
public TextView textViewRate;
public ImageView imgPoster;
}
}
And your activity set EditText Listener to this..!
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
adapter.getFilter().filter(charSequence.toString());
}
});
i hope it's helpful to you ..!
Implement addTextChangedListener() on your search EditText and as the text changes filter your list data and update MovieAdapter with filtered data.
check this post on how to update custom list adapter
Im working on download images and from web and lazy load in ListView from this website - http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134.
However, I want to customize the textview on the listview. I want my textview extract the string from string-array in string.xml instead of code holder.text.setTexr("Title " + position)
Please help me as I am a beginner. I am Appreciated. Thanks.
XML:
<string-array name="titles">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
<item>8</item>
<item>9</item>
<item>10</item>
<item>11</item>
<item>12</item>
</string-array>
Here is my main activity
public class IngredientCategoryMain extends Activity {
ListView list;
CategoryImageAdapter adapter;
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredient_category_main);
list=(ListView)findViewById(R.id.listView);
adapter=new CategoryImageAdapter(this, mStrings);
list.setAdapter(adapter);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
public View.OnClickListener listener=new View.OnClickListener() {
#Override
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition) {
String tempValues = mTitles[mPosition];
Toast.makeText(IngredientCategoryMain.this, tempValues, Toast.LENGTH_LONG).show();
}
private String[] mStrings={
"https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Ic_cake_48px.svg/2000px-Ic_cake_48px.svg.png",
"https://pixabay.com/static/uploads/photo/2013/04/01/21/30/can-99137_960_720.png",
"http://publicdomainvectors.org/photos/Gerald_G_Fast_Food_Drinks_(FF_Menu)_9.png",
"https://pixabay.com/static/uploads/photo/2014/03/25/16/59/apple-297775_960_720.png",
"https://pixabay.com/static/uploads/photo/2012/04/16/11/14/mortar-35544_960_720.png",
"https://pixabay.com/static/uploads/photo/2013/07/13/10/05/cattle-156498_960_720.png",
"https://pixabay.com/static/uploads/photo/2013/07/12/15/39/acorn-150258_960_720.png",
"http://publicdomainvectors.org/photos/johnny_automatic_bread_with_knife.png",
"https://pixabay.com/static/uploads/photo/2015/09/13/00/12/chicken-937584_960_720.jpg",
"http://publicdomainvectors.org/photos/bowl-of-steaming-soup-01.png",
"https://pixabay.com/static/uploads/photo/2014/04/02/10/38/fish-304097_960_720.png",
"http://publicdomainvectors.org/photos/Erbsen-lineart.png"
};
Adapter:
public class CategoryImageAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public CategoryImageAdapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void onClick(View v) {
}
public static class ViewHolder {
public TextView text;
public ImageButton imageButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView == null){
vi = inflater.inflate(R.layout.ingcategoryrow, null);
holder = new ViewHolder();
holder.text = (TextView)vi.findViewById(R.id.textView2);
holder.imageButton=(ImageButton)vi.findViewById(R.id.imageButton2);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("Title " + position);
ImageButton imageButton = holder.imageButton;
imageLoader.DisplayImage(data[position], imageButton);
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View arg0) {
IngredientCategoryMain sct = (IngredientCategoryMain)activity;
sct.onItemClick(mPosition);
}
}
}
Here is working my code please use this code:
String.xml
<string-array name="titles">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
<item>8</item>
<item>9</item>
<item>10</item>
<item>11</item>
<item>12</item>
</string-array>
.java file
public class MainActivity extends Activity {
ListView lv;
String[] title;
CategoryImageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listView1);
title=getResources().getStringArray(R.array.titles);
adapter=new CategoryImageAdapter(MainActivity.this, title);
lv.setAdapter(adapter);
}
public class CategoryImageAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
private String[] data;
private LayoutInflater inflater = null;
public CategoryImageAdapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void onClick(View v) {
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView == null){
vi = inflater.inflate(R.layout.row_lv, null);
holder = new ViewHolder();
holder.text = (TextView)vi.findViewById(R.id.textView1);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("Title " + data[position]);
return vi;
}
}
public class ViewHolder {
public TextView text;
}
}
First get the array as
String[] mTestArray = getResources().getStringArray(R.array.titles);
Then use it as
holder.text.setText(mTestArray[position] + position);
Get your array in constructor like:
public CategoryImageAdapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
mTestArray = getResources().getStringArray(R.array.testArray);
}
I have a RecyclerViewAdapter which fill my List with StoreName,image etc, I had model for listitems.ok, I'm migrating from a ListView to recylerview. i want to click on any item and get that items data(like Store name) and intent to another activity, now problem is that when i click on item it give wrong storename. but when i was using onItemclickListener that provide correct input. i will show u..
This my RecyclerViewAdapter.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<StoresItem> mDataset;
private static MyClickListener myClickListener;
Context context;
Bitmap xx;
public MyRecyclerViewAdapter(Context context, List<StoresItem> myDataset)
{
mDataset = myDataset;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtStoreName,txtDeliveryTime;
ImageView storeImg;
RatingBar ratingBar;
public DataObjectHolder(View itemView)
{
super(itemView);
txtStoreName = (TextView) itemView.findViewById(R.id.txtStoreName);
txtDeliveryTime = (TextView) itemView.findViewById(R.id.txtDeliveryTime);
storeImg = (ImageView) itemView.findViewById(R.id.storeImg);
ratingBar=(RatingBar)itemView.findViewById(R.id.ratingBar);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
myClickListener.onItemClick(getLayoutPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener)
{
this.myClickListener = myClickListener;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.storelist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position)
{
ImageView storeImg;
holder.txtStoreName.setText(mDataset.get(position).gettxtStoreName().toString());
holder.txtDeliveryTime.setText(mDataset.get(position).gettxtDeliveryTime().toString());
holder.ratingBar.setFocusable(false);
int loader = R.drawable.image;
String url = mDataset.get(position).getstoreImg().toString();
ImageLoader imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(url,loader,holder.storeImg);
}
public void addItem(StoresItem dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener
{
public void onItemClick(int position, View v);
}
public Object getItem(int position)
{
return mDataset.get(position);
}
#Override
public long getItemId(int position)
{
return mDataset.indexOf(getItem(position));
}
#Override
public int getItemViewType(int position)
{
return super.getItemViewType(position);
}
}
This is my StoreModel.
public class StoresItem
{
private String txtStoreName, txtDeliveryTime, storeImg;
public StoresItem(String txtStoreName, String txtDeliveryTime,String storeImg)
{
this.txtStoreName = txtStoreName;
this.txtDeliveryTime = txtDeliveryTime;
this.storeImg = storeImg;
}
public String gettxtStoreName()
{
return txtStoreName;
}
public void settxtStoreName(String txtStoreName)
{
this.txtStoreName = txtStoreName;
}
public String gettxtDeliveryTime()
{
return txtDeliveryTime;
}
public void settxtDeliveryTime(String txtDeliveryTime)
{
this.txtDeliveryTime = txtDeliveryTime;
}
public String getstoreImg()
{
return storeImg;
}
public void setstoreImg(String storeImg)
{
this.storeImg = storeImg;
}
}
And this is my Fragment where i using onclickListner.
public class RecylerFragment extends Fragment
{
ListView storeListView;
List<StoresItem> storesItem;
StoresListAdaptor adapter;
String selectedStore;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static final String[] storeNameGrocery = new String[]
{
"Value Store", "Grocery Mart", "Wild Water-Sadar Bazar", "Store99","Coco-Buzz", "Wild Water - Sector 46"
};
public static final String[] storeNameFresh = new String[]
{
"Mother's Love", "The Flower Shop", "Flower N Emotions"
};
public static final String[] storeNameElectronics = new String[]
{
"Molife-Sheetla Mata Road", "Apple Store- Shona Road", "Vandana Communication", "Samsung Store","JMD Mobile - Sector 14", "Sterling - Gurgaon"
};
public static final String[] storeNameVegetable = new String[]
{
"Fortune Store", "Best Food - Mega Mall", "Sadar Bazar", "MTR Store","Coco-Buzz"
};
public static final String[] deliveryTime = new String[]
{
"20min", "10min", "9min", "15min","30min", "1hr","20min","20min", "10min", "9min", "15min","30min", "1hr","20min" };
private static final String KEY_POSITION="position";
public static final String[] iconsUrl = new String[]
{
"http://icons.iconarchive.com/icons/femfoyou/angry-birds/96/angry-bird-icon.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/96/grimace-icon.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
};
public RecylerFragment() {
// Required empty public constructor
}
#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.activity_recycler_view, container, false);
Bundle bundle = this.getArguments();
String myString = bundle.getString("page_position");
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
storesItem = new ArrayList<StoresItem>();
if(myString.equals("999")) {
for (int i = 0; i < storeNameGrocery.length; i++) {
StoresItem item = new StoresItem(storeNameGrocery[i], "Delivery Time " + deliveryTime[i],iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("888")) {
for (int i = 0; i < storeNameFresh.length; i++) {
StoresItem item = new StoresItem(storeNameFresh[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("777")) {
for (int i = 0; i < storeNameElectronics.length; i++) {
StoresItem item = new StoresItem(storeNameElectronics[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("666")) {
for (int i = 0; i < storeNameVegetable.length; i++) {
StoresItem item = new StoresItem(storeNameVegetable[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
mAdapter = new MyRecyclerViewAdapter(getActivity(), storesItem);
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
**#Override
public void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v)
{
System.out.println(" Clicked on Item " + position);
StoresItem storesItems = (StoresItem) ((MyRecyclerViewAdapter) mAdapter).getItem(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
}**
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
okk...there is something wrong with recyclerviews-onItemclicklister because listviews - onItemCLicklistner()
provide Adapterview and i can simply get Item by using parent.getItematposition(position) like this.
storeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
StoresItem storesItems = (StoresItem) parent.getItemAtPosition(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
Can Any one tell me whats the reason why getWrong StoreName.??
You are using myClickListener.onItemClick(getLayoutPosition(), v); you have to use myClickListener.onItemClick(getAdapterPosition(), v);
I am trying to create an android application using a database from Parse.com. I am using a custom adapter to create a listview. I don't find any errors with the code and yet the listeview is not showing up. Nothing there in the logcat as well. Just the listview does not show up.
lv = (ListView)findViewById(R.id.listView);
mProgress = (ProgressBar)findViewById(R.id.check_progress);
mProgress.setVisibility(View.VISIBLE);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Sellers");
query.orderByAscending("Name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
studentsList = new ArrayList<Sellers>();
for (ParseObject ob : parseObjects) {
s = new Sellers();
s.setName(ob.getString("Name").toString());
s.setAddress1(ob.getString("Address1").toString());
s.setAddress2(ob.getString("Address2").toString());
s.setShopName(ob.getString("ShopName").toString());
s.setEmail(ob.getString("Email").toString());
s.setPhone(ob.getString("Phone").toString());
s.setZipcode(ob.getString("Zipcode").toString());
studentsList.add(s);
}
adapter = new ListviewAdapter(CheckStatus.this, studentsList);
lv.setAdapter(adapter);
mProgress.setVisibility(View.GONE);
} else {
mProgress.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
This is the activity where I am invoking the listview.
public class ListviewAdapter extends BaseAdapter{
private final static String TAG = ListviewAdapter.class.getSimpleName();
private Context activity;
private LayoutInflater inflater = null;
private List<Sellers> sellers;
int layout;
public ListviewAdapter(Context activity, List<Sellers> sellers) {
this.activity = activity;
this.sellers = sellers;
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView name ;
TextView shop ;
TextView address1 ;
TextView address2;
TextView phone;
TextView email;
RelativeLayout rl;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v =view;
ViewHolder holder = new ViewHolder();
if (view == null) {
LayoutInflater li = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.list_item_layout,null);
holder.name = (TextView)v.findViewById(R.id.seller_name);
holder.shop = (TextView)v.findViewById(R.id.shop_name);
holder.address1 = (TextView)v.findViewById(R.id.address1);
holder.address2 = (TextView)v.findViewById(R.id.address2);
holder.phone = (TextView)v.findViewById(R.id.phone);
holder.email = (TextView)v.findViewById(R.id.emailID);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Sellers s = sellers.get(position);
// String a = s.Name;
// Log.d(TAG, a);
holder.name.setText(s.getName());
holder.shop.setText(s.getShopName());
holder.address1.setText(s.getAddress1());
holder.address2.setText(s.getAddress2());
holder.phone.setText(s.getPhone());
holder.email.setText(s.getEmail());
Log.d("CustomAdapter.class", "CustomAdapter");
// imageView.setImageDrawable(s.getPic());
return v;
}
}
And this is the custom adapter. There are no null pointer exceptions showing up in the logcat. I can't determine why the listview is not getting populated.
Try this;
#Override
public int getCount() {
return sellers.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position:
}
You have to implement your code on getCount() by return number of item listview will be created.
When end items in a ListView, i upload new, and after update adapter:
ListView lvMain = (ListView) findViewById(R.id.list);
boxAdapter = null;
boxAdapter = new BoxAdapter(this, products);
lvMain.setAdapter(boxAdapter);
But after this, elements are loaded but the scroll position the top. Ie the position of ListView is lost, and look again at the beginning of all
How fix it?
BoxAdapter code:
public class BoxAdapter extends BaseAdapter {
private final Context ctx;
private final LayoutInflater lInflater;
private final ArrayList<ItemInfo> objects;
private final int loadCount = 10;
private int count = 10;
private String name, desc;
BoxAdapter(Context context, ArrayList<ItemInfo> products) {
this.ctx = context;
this.objects = products;
this.lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
#Override
public int getCount() {
//return objects.size();
return this.count;
}
// элемент по позиции
#Override
public ItemInfo getItem(int position) {
return objects.get(position);
}
// id по позиции
#Override
public long getItemId(int position) {
return position;
}
public void loadAdditionalItems() {
this.count += this.loadCount;
if (this.count > this.objects.size()) {
this.count = this.objects.size();
}
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = lInflater.inflate(R.layout.item, parent, false);
ItemInfo p = getItem(position);
TextView desc_id = (TextView) view.findViewById(R.id.desc);
if (p.username.contains("null"))
{
name = "Автор: Неизвестен";
}
else
{
name = "Автор: " + p.username;
}
if(!p.description.contains("null"))
{
desc = p.description.replaceAll("<br />", "");
desc = desc.replaceAll(""", "");
}
else
{
desc = "";
desc_id.setVisibility(View.GONE);
}
((TextView) view.findViewById(R.id.name)).setText(name);
((TextView) view.findViewById(R.id.desc)).setText(desc);
return view;
}
}
P.S setOnScrollListener code:
lvMain.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
ListView lvMain = (ListView) findViewById(R.id.list);
if(firstVisibleItem + visibleItemCount >= totalItemCount) {
boxAdapter.loadAdditionalItems();
loading = false;
}
if (!loading && (lvMain.getLastVisiblePosition() + 10) >= (60))
{
new LoadLastestPost().execute();
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
});
The best solution would be to create a setProducts method in your boxAdapter and then just call boxAdapter.notifyDataSetChanged(). For example:
boxAdapter.setProducts(products);
boxAdapter.notifyDataSetChanged();
If you implement this method, there is no need to call lvMain.setAdapter(boxAdapter) more than once.
To add the setProducts() method to your adapter:
public BoxAdapter extends BaseAdapter {
Context mContext;
ArrayList<ItemInfo> objects;
public BoxAdapter(Context context, ArrayList<ItemInfo> products) {
mContext = context;
objects = products;
}
public View getView(int position, View convertView, ViewGroup parent) {
// inflate and adjust view
}
public int getCount() {
return objects.size();
}
public Object getItem(int position) {
return objects.get(position);
}
public void setProducts(ArrayList<ItemInfo> newData) {
objects = newData;
}
}
Also, I wouldn't use a count variable. I would just use the size method in the ArrayList. I would remove count altogether.