Passing LinkedList between activities - java

I'am trying to learn how to pass a LinkedList<PassedObject> from MainActivity to SecondActivity.
So I created a listview in each activity to check if the objects are passed. The SecondActivity displays in a textview if the list is empty. I also made a PassedObject class which implements Parcelable. The problem is that when i get the List from Intent it is null. In the code below i changed LinkedList with ArrayList because i thought that's the problem. What i did wrong?
public class MainActivity extends AppCompatActivity {
private ArrayList<PassedObject> mainList;
private ListView listView;
private CustomArrayAdapter adapter;
Button test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(mainList == null){
mainList = new ArrayList<PassedObject>();
}
mainList.add(new PassedObject("Passed"));
mainList.add(new PassedObject("Passed"));
mainList.add(new PassedObject("Passed"));
mainList.add(new PassedObject("Passed"));
listView = (ListView) findViewById(R.id.listViewMain);
adapter = new CustomArrayAdapter(getBaseContext(),R.layout.item_list,mainList);
listView.setAdapter(adapter);
Button test = (Button) findViewById(R.id.button_id);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putParcelableArrayListExtra("list",mainList);
startActivity(intent);
}
});
}
public class CustomArrayAdapter extends android.widget.ArrayAdapter<PassedObject>{
Context _context;
int layoutRestId;
ArrayList<PassedObject> data;
public CustomArrayAdapter(Context context, int resource, ArrayList<PassedObject> objects) {
super(context, resource, objects);
_context = context;
layoutRestId = resource;
data = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutRestId, parent, false);
}
TextView tv = (TextView) convertView.findViewById(R.id.textViewItem);
tv.setText(data.get(position).getName());
return convertView;
}
}
}
public class SecondActivity extends AppCompatActivity {
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tv = (TextView) findViewById(R.id.seocndListText);
ArrayList<PassedObject> list =(ArrayList<PassedObject>) getIntent().getParcelableExtra("list");
tv.setText(list.isEmpty()+"");
}
}
public class PassedObject implements Parcelable{
private String _name;
PassedObject(String name){
_name = name;
}
public String getName(){
return _name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_name);
}
public PassedObject(Parcel in){
_name = in.readString();
}
public static final Parcelable.Creator<PassedObject> CREATOR = new Parcelable.Creator<PassedObject>() {
#Override
public PassedObject createFromParcel(Parcel source) {
return new PassedObject(source);
}
#Override
public PassedObject[] newArray(int size) {
return new PassedObject[size];
}
};
}

Change the following line
ArrayList<PassedObject> list =(ArrayList<PassedObject>) getIntent().getParcelableExtra("list");
To be
ArrayList<PassedObject> list = getIntent().getParcelableArrayListExtra("list");

Use this
Bundle bdl = getIntent().getExtras();
mArraylist1 = bdl.getParcelableArrayList("your list name");

Related

RecyclerView onClick returns false item

i have a RecyclerView and an EditText, when the search is typed it will filter out the items. but when the search is clicked it just passes the first unfiltered search. here is my code.
here is the FoodAdapter..
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ProductViewHolder> {
private Context mCtx;
private static List<FoodModel> productList;
private OnNoteListener monNoteListener;
//getting the context and product list with constructor
public FoodAdapter(Context mCtx, List<FoodModel> productList, OnNoteListener onNoteListener) {
this.mCtx = mCtx;
this.productList = productList;
this.monNoteListener = onNoteListener;
}
public void filteredList(List<FoodModel> filteredList) {
productList = filteredList;
notifyDataSetChanged();
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.sam_layout_products, null);
return new ProductViewHolder(view,monNoteListener);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
//getting the product of the specified position
FoodModel product = productList.get(position);
//binding the data with the viewholder views
holder.txtFoodName.setText(product.getFoodName());
holder.txtFoodDesc.setText(product.getFoodDesc());
holder.txtFoodPrice.setText(product.getFoodPrice());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getFoodImage()));
}
#Override
public int getItemCount() {
return productList.size();
}
public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtFoodName, txtFoodDesc, txtFoodPrice;
ImageView imageView;
OnNoteListener onNoteListener;
public ProductViewHolder(View itemView, OnNoteListener onNoteListener) {
super(itemView);
txtFoodName = itemView.findViewById(R.id.txtFood);
txtFoodDesc = itemView.findViewById(R.id.txtFoodDesc);
txtFoodPrice = itemView.findViewById(R.id.txtFoodPrice);
imageView = itemView.findViewById(R.id.imageView);
this.onNoteListener = onNoteListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onNoteListener.onNoteClick(getAdapterPosition());
}
}
public interface OnNoteListener{
void onNoteClick(int position);
}
}
and here is the activity FoodActivity
public class FoodsActivity extends AppCompatActivity implements FoodAdapter.OnNoteListener {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
static List<FoodModel> FoodList;
static List<FoodModel> filteredList;
//the recyclerview
RecyclerView recyclerView;
String NameString;
FoodAdapter foodAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foods_layout);
setTitle("Foods");
RecyclerViewFood();
EditText txtFoodSearch = findViewById(R.id.txtFoodSearch);
txtFoodSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence query, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
SearchFilter(editable.toString());
}
});
}
#Override
public void onNoteClick(int position) {
Intent intent = new Intent(this, sample_layout.class);
intent.putExtra("foods", FoodList.get(position));
startActivity(intent);
}
private void SearchFilter(String text){
recyclerView = (RecyclerView) findViewById(R.id.FoodRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
filteredList = new ArrayList<>();
for(FoodModel item: FoodList){
if(item.getFoodName().toLowerCase().contains(text.toLowerCase())){
filteredList.add(item);
}
}
foodAdapter = new FoodAdapter(this,filteredList,this);
// what can i do to pass the correct item to the next intent
recyclerView.setAdapter(foodAdapter);
}
public void RecyclerViewFood() {
recyclerView = (RecyclerView) findViewById(R.id.FoodRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FoodList = new ArrayList<>();
String food_name[] = getResources().getStringArray(R.array.food_name);
String food_desc[] = getResources().getStringArray(R.array.food_desc);
String food_price[] = getResources().getStringArray(R.array.food_price);
int food_image[] = {R.drawable.pic_chickenpizza, R.drawable.pic_dorowot, R.drawable.pic_genfo, R.drawable.pic_kitfo, R.drawable.pic_tibs};
for (int i = 0, j = 0, k = 0, l = 0; i < food_name.length; i++, j++, k++, l++) {
FoodList.add(new FoodModel(2, food_name[i], food_desc[j], food_price[k], food_image[l]));
}
//creating recyclerview adapter
foodAdapter= new FoodAdapter(this, FoodList, this);
//setting adapter to recyclerview
recyclerView.setAdapter(foodAdapter);
}
when the search is entered, it works but when the filteredList is clicked its passing the wrong item to the next intent.
First, your adapter implements Filterable.
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ProductViewHolder> implements Filterable {
// Filtered list
private List<FoodModel> filterList;
// Normal list
private List<FoodModel> productList;
In your constructor:
this.filterList = productList;
productList = new ArrayList<>(productList);
Implementing Filterable requires overriding the getFilter() method.
Filtering the list:
#Override
public Filter getFilter() {
return MyFilter;
}
private Filter MyFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<FoodModel> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(productList);
} else {
String filterPattern = constraint.toString().trim();
for (FoodModel item : productList) {
if (item.getFoodName().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList.clear();
filterList.addAll((List) results.values);
notifyDataSetChanged();
}
};
This is important that you use the filtered list inside onBindViewHolder:
FoodModel product = filterList.get(position);
Now in your activity:
#Override
public void afterTextChanged(Editable editable) {
String newText = editable.toString();
adapter.getFilter().filter(newText);
}
Edit: get size of the filtered list instead of normal list:
#Override
public int getItemCount() {
return filterList.size();
}
In your adapter's onClick:
startMyActivity ( mCtx , filterList.get(getAdapterPosition() ).getId() );
// method
private void startMyActivity ( Activity activity , long id ) {
Intent intent = new Intent( activity , sample_layout.class);
intent.putExtra("foods", id );
activity.startActivity(intent);
}
This is in continuation for the errors you might be facing in #Prince Ali's code. Make these changes to have context passed to your intent
public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtFoodName, txtFoodDesc, txtFoodPrice;
ImageView imageView;
OnNoteListener onNoteListener;
View mView; //Add this line
public ProductViewHolder(View itemView, OnNoteListener onNoteListener) {
super(itemView);
txtFoodName = itemView.findViewById(R.id.txtFood);
txtFoodDesc = itemView.findViewById(R.id.txtFoodDesc);
txtFoodPrice = itemView.findViewById(R.id.txtFoodPrice);
imageView = itemView.findViewById(R.id.imageView);
this.onNoteListener = onNoteListener;
itemView.setOnClickListener(this);
mView = itemView; // Add this line
}
Now in your onClick method
Context mCtx = holder.mView.getContext();
startMyActivity ( mCtx , filterList.get(getAdapterPosition() ).getId() );
// method
private void startMyActivity ( Context context , long id ) {
Intent intent = new Intent( context , sample_layout.class);
intent.putExtra("foods", id );
context.startActivity(intent);
}
Nevermind, i removed the old setOnClickListener and made a new one in the onBindViewHolder with the following code
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mCtx, sample_layout.class);
intent.putExtra("foods", productList.get(position));
mCtx.startActivity(intent);}
});
and now its working.
thank you all for your answers :)

How to Pass Image or path from Recyclerview to next Activity onClick so that i can display Image Full View?

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*/
}
}

ListView Adapter and MainActivity

I have a list view which brings numbers from a database. I need to multiply those numbers and get total of all numbers from my listview. But the problem is that the TextView where I have to set total is in the main activity and not on the adapter. How I can send the total from an adapter to the main activity?
Have I to use a loader ?
I have this in ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
int contador = 0;
public ListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView name;
TextView marc, cant, prec;}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null){
convertView = inflater.inflate(R.layout.list_colum, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.marc = (TextView) convertView.findViewById(R.id.marc);
holder.cant = (TextView) convertView.findViewById(R.id.cant);
holder.prec = (TextView) convertView.findViewById(R.id.prec);
convertView.setTag(holder);
}
else{
holder=(ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.name.setText(map.get(FIRST_COLUMN));
holder.marc.setText(map.get(SECOND_COLUMN));
holder.prec.setText(map.get(THIRD_COLUMN));
holder.cant.setText(map.get(FOURTH_COLUMN));
return convertView;
}
And this in MainActivity
public class MAinActivity extends AppCompatActivity {
private ArrayList<HashMap<String, String>> list;
HashMap<String, String> temp = new HashMap<String, String>();
private Button scanBtn;
private TextView total;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<HashMap<String, String>>();
setContentView(R.layout.MainActivity);
total = (TextView)findViewById(R.id.total); //this is the TextView where I have to put the result coming from the adapter.
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
listView = (ListView)findViewById(R.id.listacompras);
ListViewAdapter adapter = new ListViewAdapter(this,list);
listView.setAdapter(adapter);
}
you can achieve it in this way.
Create a method in your main activity like this
public updateTextView(String text){
totla.setText(text);
}
and from adapter you can set text like this
((MAinActivity ) activity).updateTextView("New text From Adapter");
Or, you can add an interface in your ListViewAdapter
public class ListViewAdapter ...{
public interface Listener{
public void updateTotal(int total);
}
// also add a setter method for mListener
Listener mListener;
....
// call mListener.updateTotal() to show updated total
}
Then implement the listener interface in your MainActivity
public class MainActivity extends AppCompatActivity implements ListViewAdapter.Listener {
...
protected void onCreate(Bundle savedInstanceState) {
...
listViewAdapter.setListener(this);
}
public void updateTotal(int total){
// set total here
}
}
This is the skeleton of the code. You will need to adapt it to your code in order for it to work.
Good luck :)

2-line list view not appearing

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));
}

Add imageUrl while running Universal Image Loader?

I have implemented the Universal Image Loader into my app with a gridview layout.
When I press a button I want to add a new imageUrl to the Array of Urls.
I managed to do that, but when I refresh my imageList, I still only see the images that were in the Array on StartUp.
How can I update the gridView with the new Array?
EDIT
MainActivity
public class MainActivity extends Activity {
Button btnView;
private ListView listView;
Socket client;
PrintWriter printwriter;
EditText textField;
Button button;
String messsage;
ObjectInputStream input;
ObjectOutputStream output;
int counter = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.ac_home);
//startRunning();
}
public void onImageGridClick(View view) {
Intent intent = new Intent(this, ViewImages.class);
startActivity(intent);
}
public void onTakeImageClick(View view) throws IOException {
ViewImages.addImg();
}
}
And here is the ViewImage class
public class ViewImages extends Activity {
private ListView listView;
ImageLoader loader;
private static ImageListAdapter adapter;
private static List<String> mItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mItems = new ArrayList<String>();
mItems.add("http://195.178.234.228/images/image8.jpg");
mItems.add("http://195.178.234.228/images/image7.jpg");
adapter = new ImageListAdapter(this, mItems);
//
listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
}
public static void addImg(){
mItems.add("http://195.178.234.228/images/image10.jpg");
adapter.notifyDataSetChanged();
}
}
ImageListAdapter
public class ImageListAdapter extends BaseAdapter {
List<String> list;
int size;
private Context context;
private ImageLoader imageLoader;
public ImageListAdapter(Context context,List<String> list) {
this.context = context;
this.list = list;
imageLoader = ImageLoader.getInstance();
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View v = convertView;
ViewHolder vh = null;
if (v == null) {
v = View.inflate(context, R.layout.list_item, null);
vh = new ViewHolder();
vh.imageView = (ImageView) v.findViewById(R.id.imageView);
v.setTag(vh);
}
else {
vh = (ViewHolder)v.getTag();
}
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.build();
imageLoader.displayImage(list.get(position), vh.imageView, options);
return v;
}
private class ViewHolder {
ImageView imageView;
}
}
Use notifyDataSetChanged on gridView Adapter to reflect changes in the gridview. Whenever there is a new imageUrl added to array of URL's refresh the adapter by :
adapter.notifyDataSetChanged();

Categories

Resources