GridView is not showing retrieved data from Json - java

I have a gridview which should show emojies that are retrieved from the server as urls, I was able to retrieve the urls and put it inside an arraylist, however using the gridview adapter, no images show at all, I've tried debugging by handcoding the url outside the for loop and it showed the image, which means that nothing is wrong with my adapter, also when I try to hardcode the url inside the for loop like arraylist.add("the url") no image appears, here's my code, please advise why the images are not showing, appreciate your assistance
BottomSheetDialog_Smiles.java
Communicator.getInstance().on("subscribe start", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONDictionary response = (JSONDictionary) args[0];
String str = response.get("emojiPack").toString();
JSONArray emojies = new JSONArray(str);
for (int i = 0; i < emojies.length(); i++) {
JSONObject response2 = (JSONObject)
emojies.getJSONObject(i);
emojiModel = new EmojiModel((String)
response2.get("urlFile"));
emojiUrl = emojiModel.getEmojiFile();
JSONDictionary t =
JSONDictionary.fromString(response2.toString());
emojiModel.init(t);
emojieModels.add(emojiModel);
}
ImageAdapter2 emojiAdapter = new
ImageAdapter2(getApplicationContext(), emojieModels);
gridView2.setAdapter(emojiAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
ImageAdapter2.java
public class ImageAdapter2 extends BaseAdapter {
private Context context;
private ArrayList<String> emojieImages = new ArrayList<String>();
// Constructor
public ImageAdapter2(Context context, ArrayList<String>
emojieImagesList) {
this.context = context;
this.emojieImages = emojieImagesList;
}
#Override
public int getCount() {
return emojieImages.size();
}
#Override
public Object getItem(int position) {
return emojieImages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
ImageView imageView;
}
#Override
public View getView(final int position, View convertView, ViewGroup
parent) {
Holder holder = new Holder();
LayoutInflater inflater = (LayoutInflater)
getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.smiles_items_layout, null);
holder.imageView = (ImageView)
grid.findViewById(R.id.smile_image_view);
Picasso.with(getApplicationContext())
.load(emojieImages.get(position))
.fit()
.centerInside()
.into(holder.imageView);
return grid;
}
}
EmojiModel.java
public class EmojiModel {
private int id;
private int price;
public String urlFile;
public EmojiModel(String urlFile) {
this.id=id;
this.price=price;
this.urlFile=urlFile;
}
public String getEmojiFile() {
return urlFile;
}
public void init(JSONDictionary data){
try{
urlFile = (String) data.get("urlFile");
id = Integer.parseInt((String) data.get("id"));
price = Integer.parseInt((String) data.get("price"));
}catch(Exception e){
e.printStackTrace();
}
}
}

Try this
Picasso.with(this)
.load(imageUrl)
.fit()
.centerInside()
.into(imageViewFromUrl, new Callback() {
#Override
public void onSuccess() {
Log.i(TAG, "succcess");
}
#Override
public void onError() {
Log.i(TAG, "error");
}
}
);

Related

How can I open a Activity from a ListView after SearchView filter using an ID stored on a JSON

Im new on java and im doing a app for finish my university. This app have a SearchView filtering on a ListView getting data from a JSON. Im almost finishing that but im stuck after the filter part.
After input on the SearchBar and filter returns the result I cant open a new intent getting the ID from the JSON. I only can open the intent using the position ListView number (that doesn't work for my necessity because of filter process).
The image below shows exactly the issue:
Image
So my necessity is: Open a intent using the ID stored on the JSON for avoid the issue of changing position ID after filter result.
I dont have any idea how I fix this.
Bean:
public class Model {
private String description;
private int id;
public Model(int id, String description) {
this.setId(id);
this.setDescription(description);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
Main:
public class MainActivity extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView list;
private ListViewAdapter adapter;
private SearchView editsearch;
public static ArrayList<Model> modelArrayList = new ArrayList<Model>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listview);
loadDataJSON();
adapter = new ListViewAdapter(this);
list.setAdapter(adapter);
editsearch = (SearchView) findViewById(R.id.search);
editsearch.setOnQueryTextListener(this);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int a = position;
Intent myIntent = new Intent(MainActivity.this, Info.class);
myIntent.putExtra("valor", a);
startActivity(myIntent);
}
});
}
public String loadJSON(String arq) {
String json = null;
try {
InputStream is = getAssets().open(arq);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void loadDataJSON() {
String arquivo = loadJSON("lista.json");
try {
JSONObject obj = new JSONObject(arquivo);
JSONArray a = obj.getJSONArray("locais");
for (int i = 0; i < a.length(); i++) {
JSONObject item = a.getJSONObject(i);
Model model = new Model(item.getInt("id"),item.getString("description"));
modelArrayList.add(model);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
adapter.filter(text);
return false;
}
#Override
public boolean onClose() {
// TODO Auto-generated method stub
return false;
}
Adapter:
public class ListViewAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
public ArrayList<Model> arraylist;
public ListViewAdapter(Context context ) {
mContext = context;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Model>();
this.arraylist.addAll(MainActivity.modelArrayList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return MainActivity.modelArrayList.size();
}
#Override
public Model getItem(int position) {
return MainActivity.modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.name.setText(MainActivity.modelArrayList.get(position).getDescription());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
MainActivity.modelArrayList.clear();
if (charText.length() == 0) {
MainActivity.modelArrayList.addAll(arraylist);
} else {
for (Model mp : arraylist) {
if (mp.getDescription().toLowerCase(Locale.getDefault()).contains(charText)) {
MainActivity.modelArrayList.add(mp);
}
}
}
notifyDataSetChanged();
}
Info:
public class Info extends Activity {
TextView aaa, bbb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
aaa = (TextView) findViewById(R.id.aaa);
bbb = (TextView) findViewById(R.id.bbb);
Intent mIntent = getIntent();
int id = mIntent.getIntExtra("valor",0);
String arquivo = loadJSON("lista.json");
try {
JSONObject obj = new JSONObject(arquivo);
JSONArray a = obj.getJSONArray("locais");
JSONObject item = a.getJSONObject(id);
aaa.setText(item.getString("id"));
bbb.setText("Base: "+item.getString("description"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String loadJSON(String arq) {
String json = null;
try {
InputStream is = getAssets().open(arq);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
JSON:
{ "locais": [{
"id": "1",
"description": "Text A"
}, {
"id": "2",
"description": "Text B"
}]}
use int a = modelArrayList.get(position).getId() instead. So you will get id from JSON
You need to use that intent in ListViewAdapter
Hope its works fine

How to filter data in a recycler view

I am fetching data from a server in a recycler view.In a layout file I have an EditText field on top and below it I have a recycler view.
I want to filter data based on what I have written in EditText field.
My problem is as I start typing in EditText field it shows no data in recycler and as I removes everything in EditText field it shows everything.
Why it is happening even if I have data present in recycler view with the same name I have entered in EditText field.
This is my code below:
Home.java
public class Home extends Fragment {
String myValue;
RecyclerView recycle;
ArrayList<LoadHomeBooks> list;
HomeBookAdapter adapter;
EditText search;
private static final String URL = "https://www.example.com";
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recycle = view.findViewById(R.id.recycle);
refresh = view.findViewById(R.id.refresh);
search = view.findViewById(R.id.search);
list = new ArrayList<>();
recycle.setHasFixedSize(true);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(22, TimeUnit.SECONDS)
.readTimeout(22, TimeUnit.SECONDS)
.writeTimeout(22, TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder().add("city", myValue).build();
Request request = new Request.Builder().url(URL).post(formBody).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
for (int i = jsonArray.length() - 1; i > -1; i--) {
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("Book_name");
LoadHomeBooks model = new LoadHomeBooks(str1);
list.add(model);
}
adapter = new HomeBookAdapter(list, getActivity());
recycle.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
#Override
public void onFailure(Call call, final IOException e) {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
TastyToast.makeText(getActivity(), e.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
}
});
}
}
});
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
ArrayList<LoadHomeBooks> filterBooks = new ArrayList<>();
for(LoadHomeBooks books: list){
String name = books.getbName().toLowerCase();
if(name.contains(s)){
filterBooks.add(books);
}
adapter.setFilter(filterBooks);
}
}
});
return view;
}
}
HomeBookAdapter.java
public class HomeBookAdapter extends RecyclerView.Adapter<HomeBookAdapter.ViewHolder> {
ArrayList<LoadHomeBooks> list;
Context context;
public HomeBookAdapter(ArrayList<LoadHomeBooks> list,Context context){
this.list = list;
this.context = context;
}
#NonNull
#Override
public HomeBookAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.home_book_layout,viewGroup,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull HomeBookAdapter.ViewHolder viewHolder, int i) {
LoadHomeBooks model = list.get(i);
viewHolder.homeBookName.setText(model.getbName());
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView homeBookName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
homeBookName = itemView.findViewById(R.id.homeBookName);
}
}
public void setFilter(ArrayList<LoadHomeBooks> filterBooks){
list = new ArrayList<>();
list.addAll(filterBooks);
notifyDataSetChanged();
}
}
LoadHomeBooks.java
public class LoadHomeBooks {
String bName;
public LoadHomeBooks(){
}
public LoadHomeBooks(String bName){
this.bName = bName;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
}
Someone please let me know what I am doing wrong. Any help would be appreciated.
THANKS
Move this code outside the for Loop
adapter.setFilter(filterBooks);
Because adapter is calling set Filter after each iteration.
Also I would request you to move network request to Activity instead of Fragment using interface.
for(LoadHomeBooks books: list){
String name = books.getbName().toLowerCase();
if(name.contains(s)){
filterBooks.add(books);
}
adapter.setFilter(filterBooks); //Place this line outside forloop
}

Converting Facebook post ID from String to int

I am making a news feed where I retrieve Facebook posts from a specific Facebook page. I retrieve those posts with help of the Facebook Graph API. I have a FeedItem which has an ID (int). The ID is also used to check which item is at the current position (Recyclerview).
The problem is that Facebook gives the posts a String ID. I have no idea how I can possibly convert this so that it will work with my application.
My Adapter:
public class FeedListAdapter extends RecyclerView.Adapter<FeedListAdapter.ViewHolder> {
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private List<FeedItem> mFeedItems;
private Context mContext;
public FeedListAdapter(List<FeedItem> pFeedItems, Context pContext) {
this.mFeedItems = pFeedItems;
this.mContext = pContext;
}
/* Create methods for further adapter use.*/
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
View feedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.feed_item, parent, false);
return new ViewHolder(feedView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.populateRow(getFeedItem(position));
}
#Override
public long getItemId(int position) {
return mFeedItems.get(position).getId();
}
#Override
public int getItemCount() {
return mFeedItems.size();
}
private FeedItem getFeedItem(int position) {
return mFeedItems.get(position);
}
class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
private ImageView mProfilePic;
private TextView mName;
private TextView mTimestamp;
private TextView mTxtStatusMsg;
private FeedImageView mFeedImage;
//initialize the variables
ViewHolder(View view) {
super(view);
mProfilePic = (ImageView) view.findViewById(R.id.feedProfilePic);
mName = (TextView) view.findViewById(R.id.feedName);
mTimestamp = (TextView) view.findViewById(R.id.feedTimestamp);
mTxtStatusMsg = (TextView) view.findViewById(R.id.feedStatusMessage);
mFeedImage = (FeedImageView) view.findViewById(R.id.feedImage);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
private void populateRow(FeedItem pFeedItem) {
getProfilePic(pFeedItem);
mName.setText(pFeedItem.getName());
mTimestamp.setText(pFeedItem.getTimeStamp());
mTxtStatusMsg.setText(pFeedItem.getStatus());
getStatusImg(pFeedItem);
}
private void getProfilePic(FeedItem pFeedItem) {
imageLoader.get(pFeedItem.getProfilePic(), new ImageListener() {
#Override
public void onResponse(ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
// load image into imageview
mProfilePic.setImageBitmap(response.getBitmap());
}
}
#Override
public void onErrorResponse(final VolleyError pVolleyError) {
}
});
}
private void getStatusImg(FeedItem pFeedItem) {
if (pFeedItem.getImage() != null) {
mFeedImage.setImageUrl(pFeedItem.getImage(), imageLoader);
mFeedImage.setVisibility(View.VISIBLE);
mFeedImage
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
mFeedImage.setVisibility(View.GONE);
}
}
}
My FeedFragment:
public class FeedFragment extends android.support.v4.app.Fragment {
private static final String TAG = FeedFragment.class.getSimpleName();
private FeedListAdapter mListAdapter;
private List<FeedItem> mFeedItems;
private RecyclerView mRecyclerView;
private String FACEBOOKURL = "**URL OF MY FB-POSTDATA**";
// newInstance constructor for creating fragment with arguments
public static FeedFragment newInstance() {
FeedFragment fragment = new FeedFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout resource file
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_feed, container, false);
initRecyclerView(view);
initCache();
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
private void initRecyclerView(View pView) {
mRecyclerView = (RecyclerView) pView.findViewById(R.id.fragment_feed_recyclerview);
LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mRecyclerView.setNestedScrollingEnabled(true);
}
mFeedItems = new ArrayList<>();
mListAdapter = new FeedListAdapter(mFeedItems, getActivity());
mRecyclerView.setAdapter(mListAdapter);
}
private void initCache() {
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(FACEBOOKURL);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
FACEBOOKURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(Integer.parseInt(feedObj.getString("id")));
item.setName("name of page");
// Image might be null sometimes
String image = feedObj.isNull("full_picture") ? null : feedObj
.getString("full_picture");
item.setImage(image);
// Status message might be null sometimes
String status = feedObj.isNull("message") ? null : feedObj
.getString("message");
item.setStatus(status);
item.setProfilePic("**profile picture url**");
item.setTimeStamp(feedObj.getString("created_time"));
mFeedItems.add(item);
}
// notify data changes to list adapter
mListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
} }
As I said; I have no idea how to handle this and I figured someone here would maybe have an idea on how to convert this, so that I can use the String that the graph api gives me, and use it as an integer.
If the id is all numeric, you should be able to do this: int id = Integer.valueOf(facebookId)
If you have an undescore you can try this:
public int getIdFromString(String postId) {
String finalId;
while (postId.indexOf("_") > 0) {
finalId = postId.substring(0, postId.indexOf("_"));
postId = finalId.concat(postId.substring(postId.indexOf("_") + 1));
}
return Integer.valueOf(postId);
}
If the value is numeric and you want an integer object, do
Integer id = Integer.valueOf(facebookId);
If you want the primitive type int, then do
int id = Integer.parseInt(facebookId);
or
int id = Integer.valueOf(facebookId);

How to load image in Viewholder of MovieAdapter?

Main Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie);
lv =(ListView)findViewById(R.id.lstMovieData);
moviename.clear();
// tv = (TextView) findViewById(R.id.tv);
Bundle b = getIntent().getExtras();
try {
Title = b.getString("MOVIE");
t = replace(Title);
} catch (Exception e) {
}
String API = "https://api.cinemalytics.com/v1/movie/title/?value=" + t + "&auth_token=<token>";
Toast.makeText(getApplicationContext(), Title, Toast.LENGTH_LONG).show();
OkHttpClient Client = new OkHttpClient();
Request request = new Request.Builder()
.url(API).build();
Call call = Client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(final Response response) throws IOException {
try {
String json = response.body().string();
Log.v(TAG, json);
if (response.isSuccessful()) {
getDATA(json);
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter = new MovieAdapter(getApplicationContext(),moviename);
lv.setAdapter(mAdapter);
}
});
} else {
}
} catch (Exception e) {
}
}
});
}
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
private void getDATA(String json) throws JSONException {
try {
moviename = new ArrayList<>();
Currentmovie c = new Currentmovie();
String story = "About The Story";
JSONArray values = new JSONArray(json);
for(int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
String movieTitle = jsonObject.getString("Title");
String disc = jsonObject.getString("Description");
Log.e(TAG,"GIRISH"+movieTitle);
c= new Currentmovie();
c.setTitle("Movie Name::"+movieTitle);
c.setDesc(story+"::\n"+disc);
if(jsonObject.getString("Description")==null)
{
c.setDesc(story+"::Not Available");
}
moviename.add(c);
}
}
catch (Exception e)
{
System.out.println("Error in Result as " + e.toString());
}
}
2.MovieAdapter.java
public class MovieAdapter extends BaseAdapter {
Context context;
private List<Currentmovie> movieData;
private static LayoutInflater inflater = null;
public MovieAdapter( Context context,List<Currentmovie> movieData)
{
this.context = context;
this.movieData = movieData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return movieData.size();
}
#Override
public Object getItem(int position) {
return movieData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView movieTitle,movieDesc;
public ImageView movieImage;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.movieTitle = (TextView) vi.findViewById(R.id.tv);
holder.movieDesc=(TextView)vi.findViewById(R.id.tv1);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.movieTitle.setText(movieData.get(position).getTitle());
holder.movieDesc.setText(movieData.get(position).getDesc());
return vi;
}
}
//i can successfully show all data except image
//image link comes with "posterpath" key
//tell me how to load image in viewholder of MovieAdapter
//currentmovie is just a getter and setter class
3.Currentmovie.java
public class Currentmovie {
private String mTitle;
private String Description;
public String getDesc() {
return Description;
}
public void setDesc(String desc) {
Description = desc;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
}
I am using this library and loading images by
first creating the Display options object by
DisplayImageOptions builder = new DisplayImageOptions.Builder()
.cacheOnDisk(true)
.showImageOnLoading(R.drawable.empty_photo)
.showImageForEmptyUri(R.drawable.empty_photo)
.build();
Then initialze the image loader by
ImageLoader imageLoader = ImageLoader.getInstance();
and load images by
imageLoader.displayImage(url, imageView, builder);
Hope this helps..
also add this to you gradle
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
Refer this first
EDIT: Add this to onCreate() of activity
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
...
.build();
ImageLoader.getInstance().init(config);
or this
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(Activity.this‌​));
Add getter and setter methods for your Image like
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imgUrl) {
imageUrl= imgUrl;
}
Add this code in your adapter class after adding Picasso library to your project:
String imageUrl = movieData.get(position).getImageUrl();
Picasso.with(getContext())
.load(imageUrl)
.into(holder.movieImage, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
}
});

How to correct download multiple images(thumbnails for videos)

I write client for kaltura media platform.
I have an activity "Video". In this activity I must display list of video with thumbnails
First of all, I download list of videos using kaltura api, and this works fine. Every video entry have a field thumbnailUrl, which point out to thumbnail for video.
When I download this thumbnails for videos, it's(thumbnails) downloads in incorrect order, some thumbnails not downloaded, some thumbnails repeated for other video, and some not downloaded.
This is code of callback if downloadind videos:
private void handleFetchvideoListTask(List<VideoObject> videoObjects){
LinearLayout videoListProgressBarContainer = (LinearLayout)mActivity.findViewById(R.id.videoListProgressBarContainer);
LinearLayout videoListViewContainer = (LinearLayout)mActivity.findViewById(R.id.videoListViewContainer);
videoListProgressBarContainer.setVisibility(View.GONE);
videoListViewContainer.setVisibility(View.VISIBLE);
ListView listView = (ListView)videoListViewContainer.findViewById(R.id.videoListView);
VideoListAdapter adapter = new VideoListAdapter((LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
adapter.setList(videoObjects);
listView.setAdapter(adapter);
DownloadThumbnailsTask task = new DownloadThumbnailsTask(videoObjects, adapter);
task.execute();
}
This is code of DownloadThumbnailsTask:
public class DownloadThumbnailsTask extends AsyncTask<List<VideoObject>, VideoObject, Void>{
private List<VideoObject> videoObjectList = null;
private List<VideoObject> toProcess = null;
private VideoListAdapter adapter = null;
public DownloadThumbnailsTask(List<VideoObject> videoObjectList, VideoListAdapter adapter){
this.videoObjectList = videoObjectList;
this.toProcess = new ArrayList<VideoObject>(videoObjectList);
this.adapter = adapter;
}
#Override
protected Void doInBackground(List<VideoObject>... lists) {
for(int i=0; i<toProcess.size(); i++){
VideoObject item = videoObjectList.get(i);
String urldisplay = item.getThumbnailUrl();
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
item.setThumbnail(mIcon11);
mIcon11 = null;
publishProgress(item);
}
return null;
}
#Override
protected void onProgressUpdate(VideoObject... values) {
if(values != null && values.length > 0){
VideoObject item = values[0];
videoObjectList.remove(item);
videoObjectList.add(item);
adapter.setList(videoObjectList);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onPostExecute(Void aVoid) {
this.toProcess.clear();
this.toProcess = null;
}
}
This is code of adapter:
public class VideoListAdapter extends BaseAdapter {
private List<VideoObject> list;
private LayoutInflater layoutInflater;
public VideoListAdapter(LayoutInflater layoutInflater){
this.layoutInflater = layoutInflater;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return list.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null){
view = layoutInflater.inflate(R.layout.list_item_video, viewGroup, false);
}
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
VideoObject item = getVideoObjectItem(i);
viewHolder.duration.setText(item.getFormattedDuration());
viewHolder.title.setText(item.getName());
if(item.getThumbnail() != null){
viewHolder.thumbnail.setImageBitmap(item.getThumbnail());
}
return view;
}
private VideoObject getVideoObjectItem(int position){
return (VideoObject) getItem(position);
}
public List<VideoObject> getList() {
return list;
}
public void setList(List<VideoObject> list) {
this.list = list;
}
public static class ViewHolder {
public final ImageView thumbnail;
public final TextView title;
public final TextView duration;
public ViewHolder(View view) {
this.thumbnail = (ImageView)view.findViewById(R.id.imgVideoThumbnail);
this.title = (TextView)view.findViewById(R.id.txtVideoName);
this.duration = (TextView)view.findViewById(R.id.txtVideoDuration);
}
}
}
And this is result of my code:
I noticed two things:
Inside doInBackground you are waiting
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
to complete before downloading the next image.
Try this:
protected Void doInBackground(List<VideoObject>... lists) {
for(final int i=0; i<toProcess.size(); i++){
try {
new Thread(){
#Override
public void run() {
VideoObject item = videoObjectList.get(i);
String urldisplay = item.getThumbnailUrl();
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
item.setThumbnail(mIcon11);
publishProgress(item);
}
}.start();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
}
return null;
}
#Override
protected void onProgressUpdate(VideoObject... values) {
adapter.notifyDataSetChanged();
}
I think this two lines is the problem:
videoObjectList.remove(item);
videoObjectList.add(item);
You're removing an item and adding again at the bottom. Just call notifyDataSetChanged after setting the bitmap.
Inside getView you're creating a new ViewHolder every time.
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = layoutInflater.inflate(R.layout.list_item_video, viewGroup, false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else{
viewHolder = view.getTag();
}
VideoObject item = getVideoObjectItem(i);
viewHolder.duration.setText(item.getFormattedDuration());
viewHolder.title.setText(item.getName());
if(item.getThumbnail() != null){
viewHolder.thumbnail.setImageBitmap(item.getThumbnail());
}
return view;
}
Do you get anything in your logcat? Maybe opening the stream or decoding fails. Are the images large?

Categories