Setting imageview using picasso in listview android java - android-arrayadapter

Im setting my imageview using picasso, because I just have url for my image. I have using listview to display. In custom adapter I'm setting imageview using picasso. But image is not displayed in listview. I doesn't know where the problem is... Anybody help out to solve this.... Thanks in advance
public class GetReportAdapter extends ArrayAdapter<NewsReport> {
private ArrayList<NewsReport> newsReports;
public GetReportAdapter(Context context, ArrayList<NewsReport> newsReportArrayList)
{
super(context, 0,newsReportArrayList);
this.newsReports=newsReportArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
NewsReport currentReport=getItem(position);
TextView titleTextView=(TextView) listItemView.findViewById(R.id.title_text_view);
titleTextView.setText(currentReport.getTitle());
TextView channelTextView=(TextView) listItemView.findViewById(R.id.news_channel_text_view);
channelTextView.setText(currentReport.getChannel());
ImageView pictureImageView=(ImageView) listItemView.findViewById(R.id.news_pic_image_view);
Log.e("image urlString",currentReport.getImage());
Picasso.with(listItemView.getContext()).load(currentReport.getImage()).into(pictureImageView);
return listItemView;
}
}
Here Im setting listview
public class MainActivity extends AppCompatActivity {
static final Uri CONTENT_URL = Uri.parse("content://com.example.newsreport/newsfeed");
ContentResolver resolver;
ArrayList<NewsReport> newsReportArrayList = new ArrayList<NewsReport>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
resolver = getContentResolver();
Log.e("resolver", "" + resolver);
getNewsFeed();
setAdapter();
}
public void getNewsFeed() {
String id = null;
String title = null;
String content = null;
String channel = null;
String image = null;
String[] projection = new String[]{BaseColumns._ID, "title", "channel", "image", "content"};
Cursor cursor = getContentResolver().query(CONTENT_URL, projection, null, null, null);
String newsFeed = "";
if (cursor.moveToNext()) {
do {
id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID));
title = cursor.getString(cursor.getColumnIndex("title"));
Log.e("title", title);
content = cursor.getString(cursor.getColumnIndex("content"));
Log.e("content", "" + content);
channel = cursor.getString(cursor.getColumnIndex("channel"));
Log.e("channel", "" + channel);
image = cursor.getString(cursor.getColumnIndex("image"));
Log.e("image", "" + image);
newsReportArrayList.add( new NewsReport(channel,title,image));
} while (cursor.moveToNext());
}
}
public void setAdapter()
{
ListView list=(ListView) findViewById(R.id.list);
GetReportAdapter adapter= new GetReportAdapter(this,newsReportArrayList);
list.setAdapter(adapter);
}
}

Related

Adding an image to Firebase

I have a firebase database where the user can add name and description. The name and description then appear in a list-view. I want to add a third element to this where the user can add a photo and display it in an image view.
I do not know how to add a photo to firebase can somebody help me.
Here is what I have so far :
my model class: (should I add the image here?)
public class Recipe {
private String recipeId;
private String recipeName;
private String recipeDescription;
public String getRecipeId() {
return recipeId;
}
public void setRecipeId(String recipeId) {
this.recipeId = recipeId;
}
public void setRecipeName(String recipeName) {
this.recipeName = recipeName;
}
public void setRecipeDescription(String recipeDescription) {
this.recipeDescription = recipeDescription;
}
public Recipe(String recipeId, String recipeName, String recipeDescription) {
this.recipeId = recipeId;
this.recipeName = recipeName;
this.recipeDescription = recipeDescription;
}
public String getRecipeName() {
return recipeName;
}
public String getRecipeDescription() {
return recipeDescription;
}
public Recipe(){
//this constructor is required
}
my listview class
public class RecipeList extends ArrayAdapter<Recipe> {
private Activity context;
List<Recipe> recipes;
public RecipeList(Activity context, List<Recipe> recipes) {
super(context, R.layout.layout_recipe_list, recipes);
this.context = context;
this.recipes = recipes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.layout_recipe_list, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewDescription = (TextView) listViewItem.findViewById(R.id.textViewDescription);
Recipe recipe = recipes.get(position);
textViewName.setText(recipe.getRecipeName());
textViewDescription.setText(recipe.getRecipeDescription());
return listViewItem;
}
}
my main fragment where i want to upload the image
public class AddRecipeFragment extends Fragment {
//we will use these constants later to pass the artist name and id to another activity
public static final String RECIPE_NAME = "net.simplifiedcoding.firebasedatabaseexample.artistname";
public static final String RECIPE_ID = "net.simplifiedcoding.firebasedatabaseexample.artistid";
//view objects
EditText editTextName;
EditText editTextDescription;
Button buttonAddRecipe;
ListView listViewRecipes;
ProgressBar progressBar;
FirebaseAuth mAuth;
//a list to store all the foods from firebase database
List<Recipe> recipes;
//our database reference object
DatabaseReference databaseRecipes;
public AddRecipeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment AddRecipeFragment.
*/
// TODO: Rename and change types and number of parameters
public static AddRecipeFragment newInstance(String param1, String param2) {
AddRecipeFragment fragment = new AddRecipeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//getting the reference of artists node
databaseRecipes = FirebaseDatabase.getInstance().getReference("recipes");
databaseRecipes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
recipes.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
Recipe recipe = postSnapshot.getValue(Recipe.class);
//adding artist to the list
// recipes.add(recipe);
}
//creating adapter
RecipeList recipeAdapter = new RecipeList(getActivity(), recipes);
//attaching adapter to the listview
listViewRecipes.setAdapter(recipeAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
//getting views
editTextName = (EditText) view.findViewById(R.id.editTextName);
editTextDescription= (EditText) view.findViewById(R.id.editTextDescription);
listViewRecipes = (ListView) view.findViewById(R.id.listViewRecipes);
buttonAddRecipe = (Button) view.findViewById(R.id.buttonAddRecipe);
//list to store artists
recipes = new ArrayList<>();
//adding an onclicklistener to button
buttonAddRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//calling the method addArtist()
//the method is defined below
//this method is actually performing the write operation
addRecipe();
}
});
}
private void addRecipe() {
//getting the values to save
String name = editTextName.getText().toString().trim();
String description = editTextDescription.getText().toString().trim();
//checking if the value is provided
if (!TextUtils.isEmpty(name)) {
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseRecipes.push().getKey();
//creating an Artist Object
Recipe recipe = new Recipe(id, name, description);
//Saving the Artist
databaseRecipes.child(id).setValue(recipe);
//setting edittext to blank again
editTextName.setText("");
//displaying a success toast
Toast.makeText(getActivity(), "recipe added", Toast.LENGTH_LONG).show();
} else {
//if the value is not given displaying a toast
Toast.makeText(getActivity(), "Please enter a recipe", Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_recipe, container, false);
}
}
}
Follow this tutorial, It will provide you a good start.
This contains the basic code that is required. You need to assign the file path of the image to "filepath" variable mentioned in the code segment and call upload image method.
//Firebase
FirebaseStorage storage;
StorageReference storageReference;
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
private void uploadImage() {
if(filePath != null)
{
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}

Why can't I access the Assets folder of my Xamarin.Android project this way?

I want to set the Typeface of the TextView to a font in the Assets folder. The problem-code is "var font = Typeface.CreateFromAsset(Assets, "Enter-The-Grid.ttf");," not the first use, but the second one towards the end of my code (the red squiggly line appears under "Assets").
namespace UndergroundSports.Android
{
[Activity]
public class CityPage : Activity
{
Sport[] sports = Sport.Sports;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.SetContentView(Resource.Layout.CityPage);
var font = Typeface.CreateFromAsset(Assets, "Enter-The-Grid.ttf");
Button bttJoin = FindViewById<Button>(Resource.Id.bttJoin);
bttJoin.Click += (sender, e) =>
{
gotoJoinPage();
};
bttJoin.Typeface = font;
ListView lstSports = FindViewById<ListView>(Resource.Id.lstSport);
lstSports.Adapter = new SportsAdapter(this, sports);
lstSports.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>
{
Sport selectedFromList = sports[e.Position];
Global.Instance.CurrentSport = selectedFromList;
gotoMembersPage();
};
}
private void gotoJoinPage()
{
var intent = new Intent(this, typeof(JoinPage));
StartActivity(intent);
}
private void gotoMembersPage()
{
var intent = new Intent(this, typeof(MembersPage));
StartActivity(intent);
}
public class SportsAdapter : BaseAdapter<Sport>
{
Sport[] items;
Activity context;
public SportsAdapter(Activity context, Sport[] items) : base()
{
this.context = context;
this.items = items;
}
public override long GetItemId(int position)
{
return position;
}
public override Sport this[int position]
{
get { return items[position]; }
}
public override int Count
{
get { return items.Length; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
view = context.LayoutInflater.Inflate(global::Android.Resource.Layout.SimpleListItem1, null);
TextView txtView = view.FindViewById<TextView>(global::Android.Resource.Id.Text1);
var font = Typeface.CreateFromAsset(Assets, "Enter-The-Grid.ttf");
txtView.Text = items[position].Name;
txtView.Gravity = GravityFlags.Center;
txtView.Typeface = font;
return view;
}
}
}
}
But when I tried to create a variable containing the font I got an error telling me:
Cannot access a nonstatic member of outer type Android.Content.Context' via nested typeUndergroundSports.Android.CityPage.SportsAdapter' (CS0038) (UndergroundSportsAndroid)"
From looking at related questions I think I need to either create an instance of the Assets object or make it static.
I'm pretty new to C# and don't really understand what's going on. I would appreciate it if someone could explain why I'm unable to access Assets in this part of my code. The part that confuses me the most is that I use the exact same line of code to access the font earlier within the same file without getting that error.
var font = Typeface.CreateFromAsset(context.Assets, "Enter-The-Grid.ttf");
Pass your activity's instance to your adapter via constructor, and use it to access Assests
public class SportsAdapter : BaseAdapter<Sport>
{
Sport[] items;
Activity context;
public SportsAdapter(Activity context, Sport[] items) : base()
{
this.context = context;
this.items = items;
}
....
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
view = context.LayoutInflater.Inflate(global::Android.Resource.Layout.SimpleListItem1, null);
TextView txtView = view.FindViewById<TextView>(global::Android.Resource.Id.Text1);
var font = Typeface.CreateFromAsset(context.Assets, "Enter-The-Grid.ttf");
txtView.Text = items[position].Name;
txtView.Gravity = GravityFlags.Center;
txtView.Typeface = font;
return view;
}
}
Also, make sure your .ttf file's build action is set to AndroidAssests. Right the .tff file > Build Action > AndroidAsset

Why is my recyclerview only displaying the content of the first item?

I am having a problem with my recyclerview, It only displays the content of the first item like this:
I have no idea what caused this, I'm really confused because I have never encountered something like this before. As you can see on the toast, the response return 3 data but I don't understand why the others are not being displayed.
Playlist.java
public class Playlist extends AppCompatActivity {
// inisiasi toolbar
private Toolbar toolbar;
// navigation drawer
public DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
RecyclerView recyclerView;
String[] id,title,dir, artists;
ArrayList<String> artist;
String navTitles[];
TypedArray navIcons;
RecyclerView.Adapter recyclerViewAdapter;
TextView textView;
String video;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.colorIcons), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
Intent intent = getIntent();
video = intent.getStringExtra("songs");
//textView = (TextView) findViewById(R.id.text);
//textView.setText(video);
getPlaylist();
// dir = PlaylistJson.dirs;
//artist = new ArrayList<String>(Arrays.asList(title));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
private void getPlaylist(){
final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://musicmania.hol.es/playlist/getSongsFromPlaylist",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//If we are getting success from server
Toast.makeText(Playlist.this, response, Toast.LENGTH_LONG).show();
loading.dismiss();
showPlaylistJSON(response);
id = PlaylistJson.ids;
title = PlaylistJson.titles;
artists = PlaylistJson.artists;
recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
RecyclerViewAdapter adapter=new RecyclerViewAdapter(id, title,artists, Playlist.this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(Playlist.this));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("playlist", video);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showPlaylistJSON(String json){
PlaylistJson pj = new PlaylistJson(json);
pj.parseJSON();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
LayoutInflater inflater;
Context context;
String[] id,title, artists;
public RecyclerViewAdapter(String[] id, String[] titles, String[] artists, Context context){
this.id = id;
this.title = titles;
this.artists = artists;
this.context = context;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
RecyclerViewHolder viewHolder = null;
if(Integer.parseInt(id[0]) != 0){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}else{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(Integer.parseInt(id[0]) != 0) {
holder.item2.setText(title[position]);
holder.imageView2.setTag(holder);
holder.artist.setText(artists[position]);
}else{
holder.item2.setText(title[position]);
}
}
#Override
public int getItemCount() {
return title.length;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView item;
ImageView imageView;
TextView item2;
TextView artist;
ImageView imageView2;
ImageButton addtoplaylist;
Context context;
public RecyclerViewHolder(final View itemView, final Context context) {
super(itemView);
this.context = context;
item = (TextView) itemView.findViewById(R.id.tv_NavTitle);
imageView = (ImageView) itemView.findViewById(R.id.iv_NavIcon);
item2 = (TextView) itemView.findViewById(R.id.list_title);
imageView2 = (ImageView) itemView.findViewById(R.id.list_avatar);
artist = (TextView) itemView.findViewById(R.id.list_artist);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Video.class);
intent.putExtra("video", ParseJson.dirs[getAdapterPosition()]);
v.getContext().startActivity(intent);
}
});
}
}
}
PlaylistJson.java
package com.example.rendell.musicmaniajukebox.json_model;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PlaylistJson {
public static String[] ids;
public static String[] titles;
public static String[] artists;
public static String[] dirs;
public static final String JSON_ARRAY = "result";
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_ARTIST = "artist";
public static final String KEY_DIR = "dir";
private JSONArray users = null;
private String json;
public PlaylistJson(String json){
this.json = json;
}
public void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
titles = new String[users.length()];
artists = new String[users.length()];
dirs = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
titles[i] = jo.getString(KEY_TITLE);
artists[i] = jo.getString(KEY_ARTIST);
dirs[i] = jo.getString(KEY_DIR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So the problem was in my PlaylistJson.java file. My volley response only returns 3 items per set e.g. {"id":1, "title": "song", "artist":"artist"} but I am also initialing for the dir which doesn't receive any json so maybe the bug came from that. Anyway, removed that and it worked.

How can I show Video List properly?

I've been searching everywhere for the solution, but it has come to a dead end.
Please help!
I record and save the video as the follow:
File DirectoryFile = new File(VideoPath);
recorder.setOutputFile(DirectoryFile.getAbsolutePath());
I load all the videos and set the ListView adapter from the userPath as follow:
private File[] getNewImageFilesWithFilters() {
File directory = new File(UserSavedDirectoryPATH);
return directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase(Locale.getDefault()).endsWith(".mp4")
|| name.toLowerCase(Locale.getDefault()).endsWith(".mkv");
}
});
}
public void LoadListView() {
for (File file : listFile){
mVideoListViewObject = new VideoListViewObject();
mVideoListViewObject.setName(file.getName());
mVideoListViewObject.setVideoUrl(file.getAbsolutePath());
VideoListViewObject_List.add(mVideoListViewObject);
}
mVideoListViewAdapter = new VideoListAdapter(this, VideoListViewObject_List);
mListView.setAdapter(mVideoListViewAdapter);
}
The ListView Adapter:
public class VideoListAdapter extends BaseAdapter {
private List<VideoListViewObject> VideoObjectList;
private Context mContext;
public VideoListAdapter(Context context, List<VideoListViewObject> newList){
this.mContext = context;
this.VideoObjectList = newList;
}
#Override
public int getCount() {
return VideoObjectList.size();
}
#Override
public VideoListViewObject getItem(int position) {
return VideoObjectList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_layout, parent, false);
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.ListViewImage);
viewHolder.layout = (RelativeLayout)convertView.findViewById(R.id.ListViewLayout);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)convertView.getTag();
}
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
viewHolder.imageView.setImageBitmap(bmThumbnail);
The problem is the list is slow to load, especially when there are a lot of videos.
This causes my VideoaAtivity to start very slow.
I love Piscasso and Universal Image Loader, but they only support images.
Does anyone know a better solution or a library that would help with the performance?
Thank you very much.
I just modified my own application to do similar logic to pre-create the thumbnails which made the list scroll very fast at the start, Add the thumbnail bitmap to the videoListViewObject and create the thumbnail
when loading the video list. this way you do not have to create it every time getView is called in your adapter.
public class VideoListViewObject{
private Bitmap bitmap = null;
............................
public void setBitmap(Bitmap bitmap)
{
this.bitmap = bitmap;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
public void LoadListView() {
for (File file : listFile){
mVideoListViewObject = new VideoListViewObject();
mVideoListViewObject.setName(file.getName());
mVideoListViewObject.setVideoUrl(file.getAbsolutePath());
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
mVideoListViewObject.setBitmap(bmThumbnail);
VideoListViewObject_List.add(mVideoListViewObject);
}
mVideoListViewAdapter = new VideoListAdapter(this, VideoListViewObject_List);
mListView.setAdapter(mVideoListViewAdapter);
}
then change your BaseAdapter code to only create the thumbnail if it is null,
public class VideoListAdapter extends BaseAdapter {
private List<VideoListViewObject> VideoObjectList;
private Context mContext;
public VideoListAdapter(Context context, List<VideoListViewObject> newList){
this.mContext = context;
this.VideoObjectList = newList;
}
#Override
public int getCount() {
return VideoObjectList.size();
}
#Override
public VideoListViewObject getItem(int position) {
return VideoObjectList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_layout, parent, false);
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.ListViewImage);
viewHolder.layout = (RelativeLayout)convertView.findViewById(R.id.ListViewLayout);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)convertView.getTag();
}
VideoListViewObject mVideoListViewObject = getItem(position);
Bitmap bmThumbnail = mVideoListViewObject.getBitmap();
if(bmThumbnail==null)
{
bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
}
viewHolder.imageView.setImageBitmap(bmThumbnail);

Getting wrong position in custom ListView while scrolling

I am getting wrong position in custom ListView while scrolling.
I have tried the ViewHolder pattern and an ArrayAdapter but both giving the same problem.
If I reproduce the code using Java then I am getting the proper position while scrolling.
So is it Xamarin architecture bug ?
Below is my sample code:
Activity Class
namespace ArrayAdapterDemoApp
{
[Activity(Label = "ArrayAdapterDemoApp", MainLauncher = true,
Icon ="#drawable/icon")]
public class MainActivity : Activity
{
private static List<DataBean> _ItemsList = new List<DataBean>();
private static CustomAdapter _adapter;
private ListView _listview;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
_listview = FindViewById<ListView>(Resource.Id.mylist);
DataBean obj1 = new DataBean();
obj1.Name = "AA";
obj1.City = "11";
_ItemsList.Add(obj1);
DataBean obj2 = new DataBean();
obj2.Name = "BB";
obj2.City = "22";
_ItemsList.Add(obj2);
DataBean obj3 = new DataBean();
obj3.Name = "CC";
obj3.City = "33";
_ItemsList.Add(obj3);
...
DataBean obj15 = new DataBean();
obj15.Name = "OO";
obj15.City = "1010";
_ItemsList.Add(obj15);
_adapter = new CustomAdapter(this, _ItemsList);
_listview.Adapter = _adapter;
}
}
}
Custom Adapter
namespace ArrayAdapterDemoApp
{
public class CustomAdapter : ArrayAdapter<DataBean>
{
private class TaskViewHolder : Java.Lang.Object
{
public TextView tvName;
public TextView tvCity;
}
List<DataBean> listData;
Activity _context;
int _position;
public CustomAdapter(Activity context, List<DataBean> dataList)
: base(context, Resource.Layout.adapter_row, dataList)
{
this._context = context;
this.listData = dataList;
}
public override long GetItemId(int position)
{
return position;
}
public override int Count
{
get { return listData.Count; }
}
//With View Holder
public override View GetView(int position, View convertView, ViewGroup parent)
{
DataBean data = listData[position];
TaskViewHolder viewHolder= null; // view lookup cache stored in tag
if (convertView == null)
{
viewHolder = new TaskViewHolder();
LayoutInflater inflater = LayoutInflater.From(_context);
convertView = inflater.Inflate(Resource.Layout.adapter_row, parent, false);
viewHolder.tvName = convertView.FindViewById<TextView>(Resource.Id.text1);
viewHolder.tvCity = convertView.FindViewById<TextView>(Resource.Id.text2);
convertView.Tag = viewHolder;
}
if(viewHolder==null)
{
viewHolder = (TaskViewHolder)convertView.Tag;
}
viewHolder.tvName.Text = data.Name;
viewHolder.tvCity.Text = data.City;
return convertView;
}
}
}
DataBean Class
namespace ArrayAdapterDemoApp
{
public class DataBean
{
public string Name { get; set; }
public string City { get; set; }
}
}
I had also same issue so I resolved it by just Tag the position to the view.for example.
//iv_delete is a imageview
holder.iv_delete.Tag = position;
and get the position from the Tag
For me it was like that
int finalPosition = (Integer)holder.iv_delete.Tag.IntValue();
Enjoy!!!!!
Add in your adapter class this method:
public DataBean GetItemAtPosition(int position)
{
return this.listData[position];
}
You can tag the position of each row to the control to get the correct position or
Another method is by using action event binding to each view row. This also solves duplicate method call issue.
this might be helpful: http://appliedcodelog.blogspot.in/2015/07/working-on-issues-with-listview-in.html#WrongPosition

Resources