How to load image in Viewholder of MovieAdapter? - java

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

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

GridView is not showing retrieved data from Json

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

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

Use Picasso to load images in RecyclerView with DataObject

I want to use picasso lib in a "RecyclerViewAdapter". I want to display different images for each entry. It worked for my when I only use text...
I parse a JSON file with the data I use in getDataSet().
At the moment I have no idea how I can use the picasso function to add the images to the dataSet.
WRONG => int imageUrl = Picasso.
CardViewActivity.java
public class CardViewActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
// url to make request - Hole fixe Coupons (max. 100)
private static String url = "http://json.file";
// JSON Node names
private static final String TAG_FIXES = "result";
private static final String TAG_TITEL = "titel";
private static final String TAG_BESCHREIBUNG = "beschreibung";
// contacts JSONArray
JSONArray fixes = null;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
/*
image = (ImageView) findViewById(R.id.image_view);
Picasso.with(getApplicationContext())
.load("http://1UVZ8A9DRLH/bild.jpg")
.placeholder(R.drawable.logo)
.fit().centerCrop().into(image);
*/
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
}
#Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<DataObject>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of fixes
fixes = json.getJSONArray(TAG_FIXES);
// looping through All Contacts
for(int i = 0; i < fixes.length(); i++){
JSONObject f = fixes.getJSONObject(i);
// Storing each json item in variable
String titel = f.getString(TAG_TITEL);
String description = f.getString(TAG_BESCHREIBUNG);
int imageUrl = Picasso.with(getApplicationContext())
.load("http://1UVZ8A9DRLH/bild.jpg")
.placeholder(R.drawable.logo)
.fit().centerCrop().into(image);
DataObject obj = new DataObject(
titel,
description,
imageUrl
);
results.add(i, obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
return results;
}
}
DataObject.java
public class DataObject {
private String mText1;
private String mText2;
private int imageUrl;
DataObject(String text1, String text2, int imageUrl){
mText1 = text1;
mText2 = text2;
imageUrl = imageUrl;
}
public String getmText1() { return mText1; }
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) { this.mText2 = mText2; }
public int getImageUrl() { return imageUrl; }
public void getImageUrl(int imageUrl) {
this.imageUrl = imageUrl;
}
}
MyRecyclerViewAdapter
public class MyRecyclerViewAdapter extends RecyclerView
.Adapter<MyRecyclerViewAdapter
.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView label;
ImageView imgViewIcon;
TextView description;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
imgViewIcon = (ImageView) itemView.findViewById(R.id.image_view);
description = (TextView) itemView.findViewById(R.id.textView2);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_row, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
holder.imgViewIcon.setImageResource(mDataset.get(position).getImageUrl());
holder.description.setText(mDataset.get(position).getmText2());
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
Firts set the imageUrl as a DataObject attribute:
...
String titel = f.getString(TAG_TITEL);
String description = f.getString(TAG_BESCHREIBUNG);
int imageUrl = f.getString(TAG_IMAGE); //Assuming TAG_IMAGE is the name of the Json attribute with the image url
DataObject obj = new DataObject(
titel,
description,
imageUrl);
...
Then on your adapter do the following:
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
Picasso.with(context).load(mDataset.get(position).getImageUrl()).into(holder.imgViewIcon);
holder.description.setText(mDataset.get(position).getmText2());
}
In your onBindViewHolder call Picasso to load an image to your ImageView. Like this:
Picasso.with(context).load("url").into(imageView);

Android XML Parser Displays Duplicate Data

I've built a SAX based XML parser for android however I'm getting duplicate data when I attempt to execute it. I'm not sure exactly what I've done wrong (I had a similar issue once before and the issue lied with a problem on the line: if (qName.equalsIgnoreCase("Video")) { however I've looked the code over several times so I'm not sure exactly what I can do to resolve the issue and or how to prevent the duplicate data.
Screenshot
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Cmd> videos;
private String tempVal;
// to maintain context
private Cmd cmd;
public SAXXMLHandler() {
videos = new ArrayList<Cmd>();
}
public List<Cmd> getResponse() {
return videos;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("Video")) {
// create a new instance of cmd
cmd = new Cmd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("videos")) {
// add it to the list
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setSuccess(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setNumberOfVideos(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setVideos(videos);
} else if (qName.equalsIgnoreCase("video")) {
cmd.setVideo(tempVal);
} else if (qName.equalsIgnoreCase("videoname")) {
cmd.setVideoName(tempVal);
} else if (qName.equalsIgnoreCase("videourl")) {
cmd.setVideoURL(tempVal);
videos.add(cmd); //You only need store an instance of your Cmd
}
}
}
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<Cmd> {
Activity context;
List<Cmd> videos;
public CustomListViewAdapter(Activity context, List<Cmd> videos) {
super(context, R.layout.list_item2, videos);
this.context = context;
this.videos = videos;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtSuccess;
TextView txtCmd;
TextView txtPrice;
}
public void run() {
Intent intent = new Intent(context, ViewVideo.class);
String txt=Cmd.getVideoURL();
intent.putExtra("videofilename", txt);
context.startActivity(intent);
}
public Cmd getItem(int position) {
return videos.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item2, null);
holder = new ViewHolder();
holder.txtSuccess = (TextView) convertView
.findViewById(R.id.success);
holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.imageView = (ImageView) convertView
.findViewById(R.id.thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Cmd cmd = (Cmd) getItem(position);
holder.txtSuccess.setText(cmd.getVideoName());
holder.txtSuccess.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
holder.txtCmd.setText(cmd.getCmd());
holder.txtCmd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
holder.txtPrice.setText(cmd.getVideoURL() + "");
holder.txtPrice.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
holder.imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
return convertView;
}
}
SAXParserAsyncTaskActivity.java
public class SAXParserAsyncTaskActivity extends Activity implements
OnClickListener, OnItemClickListener {
ListView listView;
List<Cmd> videos = new ArrayList<Cmd>();
CustomListViewAdapter listViewAdapter;
static final String URL = "http://mobile.example.com/api/xmlrpc.php?cmd=getVideos&username=fake&password=fake";
public static final String LIBRARY = "Library";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
findViewsById();
listView.setOnItemClickListener(this);
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[] { URL });
}
private void findViewsById() {
listView = (ListView) findViewById(R.id.cmdList);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
}
// private inner class extending AsyncTask
private class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
protected void onPostExecute(List<Cmd> videos) {
listViewAdapter = new CustomListViewAdapter(context, videos);
listView.setAdapter(listViewAdapter);
}
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<Cmd> doInBackground(String... urls) {
List<Cmd> videos = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
videos = SAXXMLParser.parse(stream);
for (Cmd cmd : videos) {
String videoName = cmd.getVideoName();
}
}
return videos;
}
}
}
Cmd.java
public class Cmd implements ListAdapter {
private String success;
private String cmd;
List<Cmd> videos;
private String video;
private String numberofvideos;
private static String videoname;
private static String videourl;
private LayoutInflater mInflater;
Button fav_up_btn1;
Button fav_dwn_btn1;
Context my_context;
Bitmap imageBitmap;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If convertView wasn't null it means we have already set it to our
// list_item_user_video so no need to do it again
if (convertView == null) {
// This is the layout we are using for each row in our list
// anything you declare in this layout can then be referenced below
convertView = mInflater.inflate(R.layout.list_item_user_video,
parent, false);
}
// We are using a custom imageview so that we can load images using urls
ImageView thumb = (ImageView) convertView
.findViewById(R.id.userVideoThumbImageView);
//thumb.setScaleType(ScaleType.FIT_XY);
TextView title = (TextView) convertView
.findViewById(R.id.userVideoTitleTextView);
TextView uploader = (TextView) convertView
.findViewById(R.id.userVideouploaderTextView);
TextView viewCount = (TextView) convertView
.findViewById(R.id.userVideoviewsTextView);
uploader.setText(videos.get(position).getTitle());
viewCount.setText(videos.get(position).getviewCount() + " views");
fav_up_btn1 = (Button) convertView.findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(my_context.getResources()
.getDrawable(R.drawable.fav_up_btn1)
.getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
// Get a single video from our list
final Cmd video = videos.get(position);
// Set the image for the list item
// / thumb.setImageDrawable(video.getThumbUrl());
//thumb.setScaleType(ScaleType.FIT_XY);
// Set the title for the list item
title.setText(video.getTitle());
uploader.setText("by " + video.getUploader() + " | ");
return convertView;
}
public String getUploader() {
// TODO Auto-generated method stub
return null;
}
public String getviewCount() {
// TODO Auto-generated method stub
return null;
}
public CharSequence getTitle() {
// TODO Auto-generated method stub
return null;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getNumberOfVideos() {
return numberofvideos;
}
public void setNumberOfVideos(String numberofvideos) {
this.numberofvideos = numberofvideos;
}
public List<Cmd> getVideos() {
return videos;
}
public void setVideos(List<Cmd> videos) {
this.videos = videos;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public static String getVideoName() {
return videoname;
}
public void setVideoName(String videoname) {
this.videoname = videoname;
}
public static String getVideoURL() {
return videourl;
}
public void setVideoURL(String videourl) {
this.videourl = videourl;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public boolean areAllItemsEnabled() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
return false;
}
public String getId() {
// TODO Auto-generated method stub
return null;
}
}
XML
<response>
<cmd>getVideos</cmd>
<success>1</success>
<NumberOfVideos>4</NumberOfVideos>
<Videos>
<Video>
<VideoName>sample_iPod</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_mpeg4</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_sorenson</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_iTunes</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov
</VideoUrl>
<VideoTags/>
</Video>
</Videos>
</response>
1) You don´t need to declare your object Cmd as an Adapter, why 2 adapters :P!
2) your variables videoname and videourl are static!, thats the reason for what you are gettin the same values,change to:
private String videoname;
private String videourl;
you only need an object Cmd as follows:
public class Cmd {
private String success;
private String cmd;
List<Cmd> videos;
private String video;
private String numberofvideos;
private String videoname;
private String videourl;
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getNumberOfVideos() {
return numberofvideos;
}
public void setNumberOfVideos(String numberofvideos) {
this.numberofvideos = numberofvideos;
}
public List<Cmd> getVideos() {
return videos;
}
public void setVideos(List<Cmd> videos) {
this.videos = videos;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getVideoName() {
return videoname;
}
public void setVideoName(String videoname) {
this.videoname = videoname;
}
public String getVideoURL() {
return videourl;
}
public void setVideoURL(String videourl) {
this.videourl = videourl;
}
}

Categories