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);
}
Related
I am working on a android project, here i have a class CategoryProvider which extends ContentProvider class and i also implements LoaderManager.LoaderCallbacks<Cursor> in my main Activity and I also have CategoryAdapter class which extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>. I have 3 records in my Sqlite database, now after initialization of Loader in main Activity when data is loading in the adapter it loads each record twice so how to fix that.
CategotyAdapter.java
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
Cursor dataCursor;
Context context;
String global_lang = "English";
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.titleText);
imageView = (ImageView) itemView.findViewById(R.id.icons);
}
}
public CategoryAdapter(Activity mContext, Cursor cursor) {
dataCursor = cursor;
context = mContext;
}
#Override
public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View cardview = LayoutInflater.from(parent.getContext())
.inflate(R.layout.option_layout, parent, false);
return new ViewHolder(cardview);
}
#Override
public void onBindViewHolder(CategoryAdapter.ViewHolder holder, int position) {
dataCursor.moveToPosition(position);
String imagePath = dataCursor.getString(dataCursor.getColumnIndex(CategoryContract.CategoryEntry.COLUMN_IMAGE_PATH));
String cEn_name = dataCursor.getString(dataCursor.getColumnIndex(CategoryContract.CategoryEntry.COLUMN_CONTENT_EN));
String cHi_name = dataCursor.getString(dataCursor.getColumnIndex(CategoryContract.CategoryEntry.COLUMN_CONTENT_HI));
if(global_lang.equals("English"))
holder.name.setText(cEn_name);
else
holder.name.setText(cHi_name);
Glide.with(context)
.load(imagePath)
.apply(new RequestOptions()
.placeholder(R.drawable.loading))
.into(holder.imageView);
}
public Cursor swapCursor(Cursor cursor) {
if(dataCursor == cursor) {
return null;
}
Cursor oldCursor = dataCursor;
this.dataCursor = cursor;
if(cursor != null) {
this.notifyDataSetChanged();
}
return oldCursor;
}
#Override
public int getItemCount() {
if(dataCursor != null)
Log.d("datacursor count", " " +dataCursor.getCount());
else
Log.d("datacursor count", "datacursor is null");
return (dataCursor == null) ? 0 : dataCursor.getCount();
}
public void changeLang(String lang) {
this.global_lang = lang;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstTimeUser();
ActivityToolbar = (Toolbar) findViewById(R.id.toolbar);
ActivitySpinner = (Spinner) findViewById(R.id.spinner);
ActivityToolbar.setTitle(R.string.app_name);
ActivityAdapter = ArrayAdapter.createFromResource(this, R.array.languages, R.layout.drop_menu);
ActivityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ActivitySpinner.getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
ActivitySpinner.setAdapter(ActivityAdapter);
listeners();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
}
categoryAdapter = new CategoryAdapter(this, null);
recyclerView.setAdapter(categoryAdapter);
getLoaderManager().initLoader(CATEGORY_LOADER, null, this);
}
public void listeners() {
ActivitySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
categoryAdapter.changeLang(ActivitySpinner.getSelectedItem().toString());
getLoaderManager().restartLoader(CATEGORY_LOADER, null, MainActivity.this);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] data = {
CategoryContract.CategoryEntry._ID,
CategoryContract.CategoryEntry.COLUMN_IMAGE_PATH,
CategoryContract.CategoryEntry.COLUMN_CONTENT_EN,
CategoryContract.CategoryEntry.COLUMN_CONTENT_HI
};
return new CursorLoader(
this,
CategoryContract.CategoryEntry.CONTENT_URI,
data,
null,
null,
null
);
}
#Override
protected void onResume() {
super.onResume();
loader_flag = 0;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
categoryAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
categoryAdapter.swapCursor(null);
}
Thanks!!
Ok, I got it after a lot of debugging. Here I am using Sync Adapter framework in my App which syncs the data at the background, when it trying to reload data the duplicate data is synced rapidly with new ID and it was rendered by recyclerView. so now I am using some constraints and changing my Database structure.
I really don't know how to do this. I have tried some tutorial but not worked for me ... i've already done the this with many Methods but unable to do this.
Here is my RecyclerView Holder
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView countryName;
public ImageView countryPhoto;
String s;
Bitmap image;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
countryPhoto = (ImageView)itemView.findViewById(R.id.country_photo);
}
#Override public void onClick(View view) {
Intent imageIntent = new Intent(view.getContext(),GalleryFullImage.class);
imageIntent.putExtra("id",getAdapterPosition());
view.getContext().startActivity(imageIntent);
Toast.makeText(view.getContext(), "Clicked Country Position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}}
Here is my Recyclerview Adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private ArrayList<String> arrayList;
private Context context;
public RecyclerViewAdapter(Context context, ArrayList<String> itemList) {
this.arrayList = itemList;
this.context = context;
}
#Override
public long getItemId(int position) {
return position;
}
#Override public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_item, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override public void onBindViewHolder(RecyclerViewHolders holder, int position) {
Bitmap bitmap = BitmapFactory.decodeFile(arrayList.get(position));
holder.countryPhoto.setImageBitmap(bitmap);
}
#Override public int getItemCount() {
return this.arrayList.size();
}}
Here is my GalleryActivity
public class GalleryActivity extends AppCompatActivity {
ArrayList<String> stringList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_gallery);
setTitle("Gallery");
stringList = new ArrayList<>();
// Be sure that this file is exist !!
String targetPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Country";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
try
{
Arrays.sort( files, new Comparator()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (File file : files) {
stringList.add(file.getAbsolutePath());
}
}catch (Exception e)
{
Log.e("Sort Error", e.getMessage());
}
RecyclerView rView = (RecyclerView)findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
rView.setAdapter(rcAdapter);
}
}
You just have to apply onClickListener in you viewholder, take the clicked adapter position in integer and pass it in next your fullscreen activity
Here is the full code, hope it helps
MainActivity
public class MainActivity extends AppCompatActivity {
private final Integer image_ids[] = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),gridColumnlayout);
recyclerView.setLayoutManager(layoutManager);
ArrayList<CreateList> createLists = prepareData();
MyAdapter adapter = new MyAdapter(getApplicationContext(), createLists);
recyclerView.setAdapter(adapter);
}
private ArrayList<CreateList> prepareData(){
ArrayList<CreateList> theimage = new ArrayList<>();
for(int i = 0; i< 5; i++){
CreateList createList = new CreateList();
createList.setImage_ID(image_ids[i]);
theimage.add(createList);
}
return theimage;
}
}
CreateList Class
public class CreateList {
private Integer image_id;
public Integer getImage_ID() {
return image_id;
}
public void setImage_ID(Integer android_image_url) {
this.image_id = android_image_url;
}
}
MyAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<CreateList> galleryList;
private Context context;
public final static String EXTRA_MESSAGE = "FullScreen Image";
public MyAdapter(Context context, ArrayList<CreateList> galleryList) {
this.galleryList = galleryList;
this.context = context;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item, parent, false));
}
#Override
public void onBindViewHolder(final MyAdapter.ViewHolder viewHolder, int i) {
CreateList currentList = galleryList.get(i);
Glide.with(context).load(currentList.getImage_ID()).centerCrop().crossFade().into(viewHolder.img);
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = viewHolder.getAdapterPosition();
String stringID = Integer.valueOf(pos).toString();
Intent intent = new Intent(MyAdapter.this.context, FullScreen.class);
intent.putExtra(EXTRA_MESSAGE, stringID);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView img;
public ViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.image);
}
}
}
FullScreen Activity
public class FullScreen extends AppCompatActivity {
private final Integer image_ids[] = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
Intent intent = getIntent();
String message = intent.getStringExtra(MyAdapter.EXTRA_MESSAGE);
int position = Integer.parseInt(message);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
imageView.setImageResource(image_ids[position]);
}
}
list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="170dp"
android:scaleType="fitXY"
android:id="#+id/image"/>
</RelativeLayout>
Since you are loading the bitmap from file in onBindViewHolder, you can just pass the path instead in onClick and decode it again in your next activity. This may require a bit of work in your case since your ViewHolder is defined separately from your RecyclerView so it does not have access to your dataset. For starters, move your ViewHolder so it can be a static nested class of your RecyclerView. Something like this:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolders>
private ArrayList<String> arrayList;
....
public static class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
....
#Override
public void onClick(View view) {
Intent intent = new Intent(...);
intent.putExtra("path",arrayList.get(getAdapterPosition());
/* send intent*/
}
}
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.
I'm trying to add an Object to this RecycleView. When I add the objects to the initial ArrayList they all show up. However, when I try to add an object and call notifyDataSetChanged from HomeFragment, nothing happens on the UI.
HomeFragment.java
public class HomeFragment extends Fragment {
View myView;
private RecyclerView mRecyclerView;
private HomeAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<Note> myNotes;
private Activity activity;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
myView = inflater.inflate(R.layout.first_layout, container, false);
mRecyclerView = (RecyclerView) myView.findViewById(R.id.list12313);
//linear layout manager
mLayoutManager = new LinearLayoutManager(activity);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//adapter
myNotes = new ArrayList<Note>();
myNotes.add(new Note("Welcome to WITS Mobile", "Logged in as: " + LoginActivity.witsName));
myNotes.add(new Note("Version 0.1 ALPHA", "- Early Internal Alpha"));
//myNotes.add(new Note());
mAdapter = new HomeAdapter(myNotes, activity);
mRecyclerView.setAdapter(new SlideInBottomAnimationAdapter(mAdapter));
setHasOptionsMenu(true);
return myView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.first, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.action_add:
addItem();
return true;
case R.id.action_CLR:
clear();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addItem()
{
Note e = new Note("New Title", "New Body");
mAdapter.addItem(e);
}
public void clear()
{
mAdapter.clear();
}
}
HomeAdapter.java
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder>
{
private ArrayList<Note> mNotes;
private int lastPosition = -1;
private Context context;
public HomeAdapter(ArrayList<Note> list, Context context)
{
this.mNotes = list;
this.context = context;
}
public void clear()
{
mNotes.clear();
notifyDataSetChanged();
}
public void addItem(Note n)
{
System.out.println("add");
mNotes.add(n);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder
{
public View view;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
}
}
public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
//create new view
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_card, viewGroup, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
public TextView title;
public TextView subtext;
#Override
public void onBindViewHolder(HomeAdapter.ViewHolder viewHolder, int i)
{
//Replace contents of a view, called by layout manager
title = (TextView) viewHolder.view.findViewById(R.id.title);
subtext = (TextView) viewHolder.view.findViewById(R.id.subtext);
title.setText(mNotes.get(i).getTitle());
subtext.setText(mNotes.get(i).getBody());
setAnimation(viewHolder.view, i);
}
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return mNotes.size();
}
}
Take out this line:
mRecyclerView.setHasFixedSize(true);
Fixed size means the count of the items, not the layout size
I'm trying to create a 2-line list view in my activity but I've come across one error that I don't know how to fix. How can I achieve this the AppCompat way? I want to achieve something like in the screenshot attached. My error is on line 52.
public class WCLineActivity extends ActionBarActivity {
private class Sample {
private CharSequence title;
private CharSequence summary;
private Class<? extends Activity> activityClass;
public Sample(int titleResId, int summaryResId, Class<? extends Activity> activityClass) {
this.activityClass = activityClass;
this.title = getResources().getString(titleResId);
this.summary = getResources().getString(summaryResId);
}
#Override
public String toString() { return title.toString(); }
public String getSummary(){ return summary.toString(); }
}
private static Sample[] mSamples;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc_line);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.bank, R.string.zone_1, MainActivity.class),
new Sample(R.string.waterloo, R.string.zone_1, MainActivity.class)
};
setListAdapter(new MyAdapter(this, mSamples));
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView title;
TextView summary;
}
LayoutInflater inflater;
Sample[] mSamples;
public MyAdapter(Context contexts, Sample[] samples) {
this.mSamples = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mSamples.length;
}
#Override
public Object getItem(int position) {
return mSamples[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_dualline, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_title);
viewHolder.summary = (TextView) convertView.findViewById(R.id.list_item_subtitle);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(mSamples[position].title);
viewHolder.summary.setText(mSamples[position].getSummary());
return convertView;
}
}
}
setListAdapter is a method of ListActivity, and it is not available in Activity. To overcame it, you can declare a ListView in your layout, retrieve the ListView with findViewById and call setAdapter, on that object. E.g.
ListView listView = (ListView) findViewById(R.id.id_list);
listView.setAdapter(new MyAdapter(this, mSamples));
I tried with your code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc_line);
ListView listView = (ListView) findViewById(R.id.listView);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.bank, R.string.zone_1, MainActivity.class),
new Sample(R.string.waterloo, R.string.zone_1, MainActivity.class)
};
listView.setAdapter(new MyAdapter(this, mSamples));
}