I'm trying to visualize a toast inside a fragment by pressing an item of a recycling but I can not see it
Note: There is no error in the log attached to my class
This is my fragment
public class FotoFragment extends Fragment
{
private Cursor cursor;
private int columnIndex;
private static final String TAG = "RecyclerViewExample";
private List<DataPictures> mediaList = new ArrayList<>();
private RecyclerView mRecyclerView;
private MediaRVAdapter adapter;
String type = "";
public FotoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
type = "images";
new MediaAsyncTask().execute(type);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
return view;
}
public class MediaAsyncTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
String type = params[0];
try {
mediaList = new ArrayList<>();
if (type.equalsIgnoreCase("images")) {
result = 1;
}
} catch (Exception e) {
e.printStackTrace();
result = 0;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
adapter = new MediaRVAdapter(getActivity(), mediaList);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Click pressed",Toast.LENGTH_SHORT).show();
}
});
} else {
Log.e(TAG, "Failed to show list");
}
}
}
}
This is my adapter
public class MediaRVAdapter extends RecyclerView.Adapter<MediaListRowHolder> {
private List<DataPictures> itemList;
private Context mContext;
public MediaRVAdapter(Context context, List<DataPictures> itemList) {
this.itemList = itemList;
this.mContext = context;
}
#Override
public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
MediaListRowHolder mh = new MediaListRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
try{
DataPictures item = itemList.get(i);
Uri uri = Uri.fromFile(new File(item.getFilePath()));
if(item.getFileType().equalsIgnoreCase("video")) {
Bitmap bmThumbnail = ThumbnailUtils.
extractThumbnail(ThumbnailUtils.createVideoThumbnail(item.getFilePath(),
MediaStore.Video.Thumbnails.FULL_SCREEN_KIND), 90, 60);
if(bmThumbnail != null) {
mediaListRowHolder.thumbnail.setImageBitmap(bmThumbnail);
}
} else if (item.getFileType().equalsIgnoreCase("audio")) {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(item.getFilePath());
try{
if (mmr != null) {
byte[] art = mmr.getEmbeddedPicture();
Bitmap bmp = BitmapFactory.decodeByteArray(art,0,art.length);
if(bmp != null) {
bmp= ThumbnailUtils.extractThumbnail(bmp,90,60);
mediaListRowHolder.thumbnail.setImageBitmap(bmp);
}
}
}catch (Exception e){
e.printStackTrace();
}
}else {
Picasso.with(mContext).load(uri)
.error(R.drawable.logo_slogan)
.placeholder(R.drawable.logo_slogan)
.centerCrop()
.resize(90, 60)
.into(mediaListRowHolder.thumbnail);
}
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return (null != itemList ? itemList.size() : 0);
}
}
Adapter class adapter
public class MediaListRowHolder extends RecyclerView.ViewHolder {
protected ImageView thumbnail;
protected TextView title;
public MediaListRowHolder(View view) {
super(view);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
this.title = (TextView) view.findViewById(R.id.title);
}
}
solution:
public class MediaListRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView thumbnail;
protected TextView title;
public MediaListRowHolder(View view) {
super(view);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
this.title = (TextView) view.findViewById(R.id.title);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
I think you can do this, such as the following code:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Author:Administrator on 2016/9/2 0002 20:37
* Contact:289168296#qq.com
*/
public abstract class OnItemSelectedListener implements RecyclerView.OnItemTouchListener{
private final GestureDetector mGestureDetector;
public OnItemSelectedListener(Context context){
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener(){
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
public abstract void onItemSelected(RecyclerView.ViewHolder holder, int position);
#Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
if (mGestureDetector.onTouchEvent(e)) {
View touchedView = rv.findChildViewUnder(e.getX(), e.getY());
onItemSelected(rv.findContainingViewHolder(touchedView),
rv.getChildAdapterPosition(touchedView));
}
return false;
}
#Override public void onTouchEvent(RecyclerView rv, MotionEvent e) {
throw new UnsupportedOperationException("Not implemented");
}
#Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
throw new UnsupportedOperationException("Not implemented");
}
}
And then to the RecycleView registration event, the event can be handled:
private RecyclerView grid;
grid.setAdapter(new PhotoAdapter(this, relevantPhotos));
grid.addOnItemTouchListener(new OnItemSelectedListener(MainActivity.this) {
#Override public void onItemSelected(RecyclerView.ViewHolder holder, int position) {
if (!(holder instanceof PhotoViewHolder)) {
return;
}
PhotoItemBinding binding = ((PhotoViewHolder) holder).getBinding();
final Intent intent = getDetailActivityStartIntent(MainActivity.this, relevantPhotos, position, binding);
final ActivityOptions activityOptions = getActivityOptions(binding);
MainActivity.this.startActivityForResult(intent, IntentUtil.REQUEST_CODE,
activityOptions.toBundle());
}
});
PhotoAdapter.java:
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.googlesamples.unsplash.R;
import com.googlesamples.unsplash.data.model.Photo;
import com.googlesamples.unsplash.databinding.PhotoItemBinding;
import com.googlesamples.unsplash.ui.ImageSize;
import java.util.ArrayList;
public class PhotoAdapter extends RecyclerView.Adapter<PhotoViewHolder> {
private final ArrayList<Photo> photos;
private final int requestedPhotoWidth;
private final LayoutInflater layoutInflater;
public PhotoAdapter(#NonNull Context context, #NonNull ArrayList<Photo> photos) {
this.photos = photos;
requestedPhotoWidth = context.getResources().getDisplayMetrics().widthPixels;
layoutInflater = LayoutInflater.from(context);
}
#Override
public PhotoViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
return new PhotoViewHolder((PhotoItemBinding) DataBindingUtil.inflate(layoutInflater,
R.layout.photo_item, parent, false));
}
#Override
public void onBindViewHolder(final PhotoViewHolder holder, final int position) {
PhotoItemBinding binding = holder.getBinding();
Photo data = photos.get(position);
binding.setData(data);
binding.executePendingBindings();
Glide.with(layoutInflater.getContext())
.load(holder.getBinding().getData().getPhotoUrl(requestedPhotoWidth))
.placeholder(R.color.placeholder)
.override(ImageSize.NORMAL[0], ImageSize.NORMAL[1])
.into(holder.getBinding().photo);
}
#Override
public int getItemCount() {
return photos.size();
}
#Override
public long getItemId(int position) {
return photos.get(position).id;
}
}
Related
I want to make a dashboard in android studio.I use two xml for making dashboard main_activity and list_item activity.In the coding session i used model class adapter and also main class.
public class MainActivity extends AppCompatActivity {
ArrayList<DashModel> dashModelArrayList;
DashAdapter dashAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rv1);
dashModelArrayList = new ArrayList<>();
String heads[] = {"Jobs", "My Profile", "Messages", "Applied Jobs", "Resume", "Settings"};
String subs[] = {"12 new jobs found", "75% complete", "2 new messages", "3 applies jobs", "Edit resume", "Set preferences"};
int images[] = {R.drawable.find_jobs, R.drawable.profile, R.drawable.messages, R.drawable.applied_jobs,
R.drawable.resume, R.drawable.settings};
for (int count = 0; count < heads.length; count++) {
DashModel dashModel = new DashModel();
dashModel.setHead(heads[count]);
dashModel.setSub(subs[count]);
dashModel.setImage(images[count]);
dashModelArrayList.add(dashModel);
//this should be retrieved in our adapter
}
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));
dashAdapter = new DashAdapter(dashModelArrayList);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(dashAdapter);
}}
Adapter class :
public class DashAdapter extends RecyclerView.Adapter<DashAdapter.ViewHolder> {
ArrayList<DashModel> dashModelArrayList;
public DashAdapter(ArrayList<DashModel> dashModelArrayList) {
this.dashModelArrayList = dashModelArrayList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String ret_head = dashModelArrayList.get(position).getHead();
holder.setheader(ret_head);
String ret_sub = dashModelArrayList.get(position).getSub();
holder.set_sub(ret_sub);
int ret_image = dashModelArrayList.get(position).getImage();
holder.set_image(ret_image);
}
#Override
public int getItemCount() {
return dashModelArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView header,sub_header;
ImageView images;
View myView;
public ViewHolder(View itemView) {
super(itemView);
myView = itemView;
}
public void setheader(String h)
{
header = myView.findViewById(R.id.header);
header.setText(h);
}
public void set_sub(String s)
{
sub_header = myView.findViewById(R.id.sub_header);
sub_header.setText(s);
}
public void set_image(int i)
{
images = myView.findViewById(R.id.dash_image);
images.setImageResource(i);
}
}}
How can i add onItemclickListener here?
I expect and want to add OnItemclickListener in the icon but i can't and don't know how to add.
To create a onClickListener for RecyclerView you have to create a class which implements the RecyclerView.OnItemTouchListener
import android.support.v7.widget.*;
import android.view.*;
import android.content.*;
public class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerViewTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
}
After that you can attach it to your RecyclerView to listen for clicks.
recyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(getActivity(), recyclerView, new RecyclerViewTouchListener.ClickListener(){
#Override
public void onClick(View view, int position)
{
// TODO: Implement this method
}
#Override
public void onLongClick(View view, int position)
{
// TODO: Implement this method
}
}));
I have RecyclerView that contains my data from newest to oldest. Before I sorting the data by date, this onclick RecyclerView doing really well. It will send some variable to another intent.
But after I sorting the RecyclerView by date, the RecyclerView sort well but the addOnItemTouchListener send the wrong data position which is data before the RecyclerView is sorted.
I mean addOnItemTouchListener send the position before RecyclerView is sorted.
mRecycleView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecycleView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
DaftarTugas tugas = listTugas.get(position);
Intent intent = new Intent(getActivity(), PengumumanTugasDetail.class);
Log.e("idtugasput","asd"+idTugasPut.get(position));
daftarTugasRef.child(idTugasPut.get(position)).child("flag").setValue("o");
intent.putExtra("flag", "tugas");
intent.putExtra("namamatkultugas", namaMatkulPut.get(position));
intent.putExtra("deskripsitugas", deskripsiTugasPut.get(position));
intent.putExtra("judultugas", judulTugasPut.get(position));
intent.putExtra("tanggalkumpul", tanggalKumpulPut.get(position));
intent.putExtra("tanggaltugas", tanggalTugasPut.get(position));
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
and this when list is added
DaftarTugas tugas = new DaftarTugas();
tugas = dataSnapshot3.getValue(DaftarTugas.class);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
try {
Date mDate = sdf.parse(tugas.getTanggal_tugas());
long timeInMilliseconds = mDate.getTime();
tugas.setDate_milisecond(timeInMilliseconds);
//store this timeInMilliseconds in your POJO object
Log.e("timestamp2","asd"+tugas.getDate_milisecond());
} catch (ParseException e) {
e.printStackTrace();
}
listTugas.add(tugas);
idTugasPut.add(idTugas);
namaMatkulPut.add(tugas.getNama_tugas());
deskripsiTugasPut.add(tugas.getDeskripsi_tugas());
tanggalKumpulPut.add(tugas.getTanggal_kumpul());
tanggalTugasPut.add(tugas.getTanggal_tugas());
judulTugasPut.add(tugas.getJudul_tugas());
Collections.sort(listTugas, new Comparator<DaftarTugas>() {
public int compare(DaftarTugas o1, DaftarTugas o2) {
if (o1.getDate_milisecond() > o2.getDate_milisecond()) {
return -1;
} else if (o1.getDate_milisecond() < o2.getDate_milisecond()) {
return 1;
} else {
return 0;
}
}
});
mAdapter.notifyDataSetChanged();
RecyclerTouchListenerClass
package com.example.yehezkiel.eclassapp;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
myAdapter
package com.example.yehezkiel.eclassapp;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
/**
* Created by Yehezkiel on 7/15/2018.
*/
public class myAdapterTugas extends RecyclerView.Adapter<myAdapterTugas.MyViewHolder> {
private List<DaftarTugas> listTugas;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tanggal_tugas,judul_tugas,tanggal_kumpul,nama_matkul;
public MyViewHolder(View view) {
super(view);
nama_matkul = (TextView) view.findViewById(R.id.judul_p);
judul_tugas = (TextView) view.findViewById(R.id.deskripsi_p);
tanggal_tugas = (TextView) view.findViewById(R.id.tanggal_tugas);
}
}
public myAdapterTugas(List<DaftarTugas> listTugas) {
this.listTugas = listTugas;
}
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.costume_row_tugas, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
DaftarTugas tugas = listTugas.get(position);
holder.nama_matkul.setText(tugas.getNama_tugas());
holder.judul_tugas.setText(tugas.getJudul_tugas());
holder.tanggal_tugas.setText(tugas.getTanggal_tugas());
if(tugas.getFlag().equals("a")){
holder.nama_matkul.setTextColor(Color.BLUE);
}else{
holder.nama_matkul.setTextColor(Color.BLACK);
}
}
#Override
public int getItemCount() {
return listTugas.size();
}
}
I found the solution from #pskink, I move the OnClickListener to the adapter like this:
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final DaftarTugas tugas = listTugas.get(position);
holder.nama_matkul.setText(tugas.getNama_tugas());
holder.judul_tugas.setText(tugas.getJudul_tugas());
holder.tanggal_tugas.setText(tugas.getTanggal_tugas());
if(tugas.getFlag().equals("a")){
holder.nama_matkul.setTextColor(Color.BLUE);
}else if(tugas.getFlag().equals("o")){
holder.nama_matkul.setTextColor(Color.BLACK);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), PengumumanTugasDetail.class);
intent.putExtra("flag", "tugas");
intent.putExtra("namamatkultugas", tugas.getNama_tugas());
intent.putExtra("deskripsitugas", tugas.getDeskripsi_tugas());
intent.putExtra("judultugas", tugas.getJudul_tugas());
intent.putExtra("tanggalkumpul", tugas.getTanggal_kumpul());
intent.putExtra("tanggaltugas", tugas.getTanggal_tugas());
view.getContext().startActivity(intent);
}
});
I'm trying to read everything in my external text file and put it into an array list that is send to another class via a parcel class. Although I can get the strings set on textview, but not the image.
One of the lines in my external text file looks like:
McDonalds| Any McDonalds outlet| Applicable to any lunch meal set| Buy 1 get 1 free| 1 Aug - 31 Aug| RM 32.00| RM 16.00| icon_nandos.png
MainActivity.java:
public class MainActivity extends AppCompatActivity implements listAdapter.sendInfo{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_fragment lf = new list_fragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.mainAct, lf);
fragmentTransaction.commit();
}
#Override
public void detailInfo(outletData outDat, int pos) {
fragmentDetail fd = fragmentDetail.newInstance(outDat);
getSupportFragmentManager().beginTransaction()
.replace(R.id.mainAct, fd)
.addToBackStack(null)
.commit();
}
}
list_fragment.java:
public class list_fragment extends Fragment {
ArrayList<outletData> outletDatas = new ArrayList<outletData>();
BufferedReader bufferedReader = null;
String food;
public View onCreateView( LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
RecyclerView recyclerView = view.findViewById(R.id.fragRecycler);
outletDatas.clear();
try{
bufferedReader = new BufferedReader(new
InputStreamReader(getContext().getAssets().open("food_catalog.txt")));
while ((food = bufferedReader.readLine())!=null) {
if (!food.equals("")) {
String[] foodInfo = food.split("\\|");
outletDatas.add(new outletData(foodInfo[0], foodInfo[1], foodInfo[2], foodInfo[3], foodInfo[4], foodInfo[5], foodInfo[6], foodInfo[7]));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
listAdapter mylistAdapter = new listAdapter(outletDatas, getContext());
recyclerView.setAdapter(mylistAdapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}
outletData.java:
package com.example.user.assignmentthreethree;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Parcel;
import android.os.Parcelable;
public class outletData implements Parcelable {
private String name, location, details, deals, offerPeriod, normalPrice, discountPrice, imagePath;
public outletData(String name, String location, String details, String deals, String offerPeriod, String normalPrice, String discountPrice, String imagePath) {
this.name = name;
this.location = location;
this.details = details;
this.deals = deals;
this.offerPeriod = offerPeriod;
this.normalPrice = normalPrice;
this.discountPrice = discountPrice;
this.imagePath = imagePath;
}
private outletData(Parcel in) {
name = in.readString();
location = in.readString();
details = in.readString();
deals = in.readString();
offerPeriod = in.readString();
normalPrice = in.readString();
discountPrice = in.readString();
imagePath = in.readString();
}
public static final Creator<outletData> CREATOR = new Creator<outletData>() {
#Override
public outletData createFromParcel(Parcel in) {
return new outletData(in);
}
#Override
public outletData[] newArray(int size) {
return new outletData[size];
}
};
public String getName() {
return name;
}
public String getLocation() {
return location;
}
public String getDetails() {
return details;
}
public String getDeals() {
return deals;
}
public String getOfferPeriod() {
return offerPeriod;
}
public String getNormalPrice() {
return normalPrice;
}
public String getDiscountPrice() {
return discountPrice;
}
public String getImagePath() {
return imagePath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(location);
parcel.writeString(details);
parcel.writeString(deals);
parcel.writeString(offerPeriod);
parcel.writeString(normalPrice);
parcel.writeString(discountPrice);
parcel.writeString(imagePath);
}
}
listAdapter.java:
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;
listAdapter(ArrayList<outletData> outletDataFromFragment) {
this.outletDataFromFragment = outletDataFromFragment;
}
#Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
this.mContext = viewGroup.getContext();
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull listAdapter.ViewHolder viewHolder, int i) {
outletData data = outletDataFromFragment.get(i);
viewHolder.listName.setText(data.getName());
viewHolder.listDeal.setText(data.getDeals());
viewHolder.listOffer.setText(data.getOfferPeriod());
// viewHolder.listImg.setImageURI(Uri.parse(data.getImagePath()));
try {
InputStream ims = mContext.getAssets().open(""+data.getImagePath().trim());
Drawable d = Drawable.createFromStream(ims, null);
viewHolder.listImg.setImageDrawable(d);
ims.close();
} catch (IOException ex) {
return;
}
}
#Override
public int getItemCount() {
return outletDataFromFragment.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView listName, listDeal, listOffer;
ImageView listImg;
public ViewHolder(View itemView) {
super(itemView);
listName = (TextView)itemView.findViewById(R.id.txtName);
listDeal = (TextView)itemView.findViewById(R.id.txtDeals);
listOffer = (TextView)itemView.findViewById(R.id.txtOffer);
listImg = (ImageView)itemView.findViewById(R.id.imgFood);
recyclerView = (RecyclerView)itemView.findViewById(R.id.reCyclerView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
((sendInfo)view.getContext()).detailInfo(outletDataFromFragment.get(getLayoutPosition()), getLayoutPosition());
}
}
interface sendInfo {
void detailInfo(outletData outletData, int pos);
}
}
fragmentDetail.java:
public class fragmentDetail extends Fragment {
TextView fragName, fragDeal, fragOffer, fragDetail, fragOldPrice, fragNewPrice, fragLocation;
ImageView fragImage;
outletData OD;
Bundle bundle;
public fragmentDetail() {}
public static fragmentDetail newInstance(outletData oData) {
fragmentDetail fragmentDetail = new fragmentDetail();
Bundle b = new Bundle();
b.putParcelable("pData", oData);
fragmentDetail.setArguments(b);
return fragmentDetail;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = this.getArguments();
OD = bundle.getParcelable("pData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
fragName = (TextView)view.findViewById(R.id.frag_name);
fragDeal = (TextView)view.findViewById(R.id.frag_Deal);
fragOffer = (TextView)view.findViewById(R.id.frag_Offer);
fragDetail = (TextView)view.findViewById(R.id.frag_Detail);
fragOldPrice = (TextView)view.findViewById(R.id.frag_oldPrice);
fragNewPrice = (TextView)view.findViewById(R.id.frag_newPrice);
fragLocation = (TextView)view.findViewById(R.id.frag_location);
fragImage = (ImageView)view.findViewById(R.id.frag_image);
Toast.makeText(getContext(), OD.getImagePath(), Toast.LENGTH_LONG).show();
fragOldPrice.setPaintFlags(fragOldPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
fragName.setText(OD.getName());
fragDeal.setText(OD.getDeals());
fragOffer.setText(OD.getOfferPeriod());
fragDetail.setText(OD.getDetails());
fragOldPrice.setText(OD.getNormalPrice());
fragNewPrice.setText(OD.getDiscountPrice());
fragLocation.setText(OD.getLocation());
fragImage.setImageURI(Uri.parse(OD.getImagePath()));
return view;
}
}
Based on suggestions online I have tried trimming the string but it doesn't change the outcome. I am still learning the logic flows and syntax of Android Studio, but I don't know why its not getting the image even the images are in the same folder as the text file (Assests) and it does gets the food[7] string as icon_nandos.png when I tried printing it out.
You can try to get drawable from asset file and setting it to your imageview. Use the following code.
try {
InputStream ims = getAssets().open(""+your_image_name);
Drawable d = Drawable.createFromStream(ims, null);
mImage.setImageDrawable(d);
ims.close();
} catch(IOException ex) {
return;
}
so you need to edit your code as below.
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;
listAdapter(ArrayList<outletData> outletDataFromFragment) {
this.outletDataFromFragment = outletDataFromFragment;
}
#Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
this.mContext = viewGroup.getContext();
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull listAdapter.ViewHolder viewHolder, int i) {
outletData data = outletDataFromFragment.get(i);
viewHolder.listName.setText(data.getName());
viewHolder.listDeal.setText(data.getDeals());
viewHolder.listOffer.setText(data.getOfferPeriod());
try {
InputStream ims = mContext.getAssets().open(""+your_image_name);
Drawable d = Drawable.createFromStream(ims, null);
viewHolder.listImg.setImageDrawable(d);
ims.close();
} catch(IOException ex) {
return;
}
}
I am trying to open a url link when I click on a list item in a recyclerview but I keep getting a NullPointerException. I am using a ViewPager, I don't know if this is the cause of the exception, maybe I'm doing something wrong. Please check out my code and logcat below.
This is my adapter:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsHolder> {
private ArrayList<News> mNews = new ArrayList<>();
private static ClickListener clickListener;
public NewsAdapter(ArrayList<News> news) {
mNews = news;
}
private static String timeConverter(String inputTime) {
long startTime = 0;
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
simpleDate.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date date = simpleDate.parse(inputTime);
startTime = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
long currentTime = System.currentTimeMillis();
long end = currentTime - startTime;
long seconds = TimeUnit.MILLISECONDS.toSeconds(end);
long minutes = TimeUnit.SECONDS.toMinutes(seconds);
long hours = TimeUnit.MINUTES.toHours(minutes);
if (minutes > 59) {
return hours + "h";
}else if (seconds > 59) {
return minutes + "m";
}else {
return seconds + "s";
}
}
#Override
public NewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_view, parent, false);
return new NewsHolder(view);
}
#Override
public void onBindViewHolder(NewsHolder holder, int position) {
String imagePath = mNews.get(position).getImageUrl();
Picasso.with(holder.mImageView.getContext()).load(imagePath).into(holder.mImageView);
holder.mNewsTextView.setText(mNews.get(position).getNews());
holder.mTimeStampTextView.setText(timeConverter(mNews.get(position).getTime()));
}
#Override
public int getItemCount() {
return mNews.size();
}
// NewsHolder class that extends the ViewHolder
public static class NewsHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mImageView;
private TextView mNewsTextView;
private TextView mTimeStampTextView;
// Setting the views
public NewsHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.simple_imageView);
mNewsTextView = (TextView) itemView.findViewById(R.id.news_tv);
mTimeStampTextView = (TextView) itemView.findViewById(R.id.time_tv);
}
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
}
}
public void setOnItemClickListener(ClickListener listener) {
NewsAdapter.clickListener = listener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
This is one of my ViewPager fragments:
public class TechFragment extends Fragment {
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView mErrorMessage;
private NewsAdapter mNewsAdapter;
ArrayList<News> news;
NetworkInfo info;
// The Loader takes in a bundle
Bundle sourceBundle = new Bundle();
private final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String TECH_NEWS_QUERY_URL = "query";
private static final String TECH_NEWS_SOURCE = "techcrunch";
private static final String TECH_SOURCE_CATEGORY = "latest";
private static final int TECH_NEWS_LOADER = 22;
private RecyclerView mRecyclerView;
public TechFragment() {
// 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_news, container, false);
mErrorMessage = (TextView) view.findViewById(R.id.tv_error_message);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_main);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);
getActivity().getSupportLoaderManager().initLoader(TECH_NEWS_LOADER, sourceBundle, new NewsDataLoader());
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.v(LOG_TAG, "Refreshing");
restartLoader();
mSwipeRefreshLayout.setColorSchemeResources(
R.color.colorPrimary,
R.color.colorPrimaryDark);
}
});
return view;
}
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity()
.getSystemService(CONNECTIVITY_SERVICE);
info = cm.getActiveNetworkInfo();
return info != null && info.isConnectedOrConnecting();
}
private int anyRandomInt(Random random) {
return random.nextInt();
}
private void restartLoader() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
URL techNewsUrl = NetworkUtils.buildUrl(TECH_NEWS_SOURCE, TECH_SOURCE_CATEGORY);
sourceBundle.putString(TECH_NEWS_QUERY_URL, techNewsUrl.toString());
Random random = new Random();
int uniqueId = anyRandomInt(random); //Generates a new ID for each loader call;
LoaderManager loaderManager = getActivity().getSupportLoaderManager();
if (loaderManager.getLoader(TECH_NEWS_LOADER) == null) {
loaderManager.initLoader(uniqueId, sourceBundle, new NewsDataLoader());
} else {
loaderManager.restartLoader(TECH_NEWS_LOADER, sourceBundle, new
NewsDataLoader());
}
}
}, 5000);
mSwipeRefreshLayout.setRefreshing(false);
Log.v(LOG_TAG, "Finished refreshing");
}
private void showErrorScreen() {
mErrorMessage.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.INVISIBLE);
mErrorMessage.setText(getString(R.string.internet_error));
}
public class NewsDataLoader implements LoaderManager.LoaderCallbacks<ArrayList<News>> {
#Override
public Loader<ArrayList<News>> onCreateLoader(int id, final Bundle args) {
if (isConnected()) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
return new AsyncTaskLoader<ArrayList<News>>(getActivity()) {
ArrayList<News> mNewsData;
#Override
protected void onStartLoading() {
super.onStartLoading();
if (mNewsData != null) {
deliverResult(mNewsData);
} else {
forceLoad();
mSwipeRefreshLayout.setRefreshing(true);
}
}
#Override
public ArrayList<News> loadInBackground() {
try {
ArrayList<News> news = NetworkUtils.parseJSON(TECH_NEWS_SOURCE, TECH_SOURCE_CATEGORY);
return news;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void deliverResult(ArrayList<News> data) {
mNewsData = data;
super.deliverResult(data);
}
};
} else {
showErrorScreen();
return null;
}
}
#Override
public void onLoadFinished(Loader<ArrayList<News>> loader, final ArrayList<News> data) {
mSwipeRefreshLayout.setRefreshing(false);
if (null == data) {
showErrorScreen();
} else {
mErrorMessage.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
if (news != null) {
news.clear();
news.addAll(data);
mNewsAdapter = new NewsAdapter(news);
mRecyclerView.setAdapter(mNewsAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
mNewsAdapter.notifyDataSetChanged();
} else {
news = data;
}
}
mNewsAdapter.setOnItemClickListener(new NewsAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
News currentNews = news.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(currentNews.getUrl()));
if (intent.resolveActivity(getActivity().getPackageManager()) != null){
startActivity(intent);
}
}
});
}
#Override
public void onLoaderReset(Loader<ArrayList<News>> loader) {
}
}
}
And this is my error:
06-13 12:11:38.667 3890-3890/com.ire.blogbot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ire.blogbot, PID: 3890
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ire.blogbot.adapter.NewsAdapter.setOnItemClickListener(com.ire.blogbot.adapter.NewsAdapter$ClickListener)' on a null object reference
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader.onLoadFinished(TechFragment.java:192)
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader.onLoadFinished(TechFragment.java:131)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:476)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:444)
at android.support.v4.content.Loader.deliverResult(Loader.java:126)
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader$1.deliverResult(TechFragment.java:164)
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader$1.deliverResult(TechFragment.java:137)
at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:252)
at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:80)
at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:485)
at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:502)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Try this code, it is working
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// on click
}
})
);
RecyclerItemClickListener Class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}}
Move
mNewsAdapter.setOnItemClickListener(new NewsAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
News currentNews = news.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(currentNews.getUrl()));
if (intent.resolveActivity(getActivity().getPackageManager()) != null){
startActivity(intent);
}
}
});
after
mNewsAdapter = new NewsAdapter(news);
I need yout help. How to add Ad Unit (NativeAd) within a List of Articles, using Facebook Audience Network https://developers.facebook.com/docs/audience-network/android/native-api. Im not programmer and need all code how it should be. The ads have to be between posts (listview)Thanks
import com.facebook.ads.*;
public class Posts extends Fragment{
ArrayList<Post> mPosts;
private static final String KEY_CONTENT = "PostsFragment:array";
boolean isLoadMore = false;
int mPageCount = 0;
int mCurrectPage = 1;
PullToRefreshListView mListView;
MyAdapter mListViewAdapter;
View mLoadingFooter;
private Tracker tracker;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.tracker = EasyTracker.getInstance(this.getActivity());
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mPosts = (ArrayList<Post>) savedInstanceState.getSerializable(KEY_CONTENT);
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
#Override
public void onResume() {
super.onResume();
this.tracker.set(Fields.SCREEN_NAME, "Article");
this.tracker.send( MapBuilder.createAppView().build() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_CONTENT, mPosts);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View _result = inflater.inflate(R.layout.list, null);
mLoadingFooter = inflater.inflate(R.layout.loading_footer, null);
mLoadingFooter.setVisibility(View.GONE);
if (mPosts == null)
{
mPosts = new ArrayList<Post>();
loadPostsList();
}
mListView = (PullToRefreshListView) _result.findViewById(R.id.listView);
mListViewAdapter = new MyAdapter(getActivity(), mPosts);
mListView.addFooterView(mLoadingFooter);
mListView.setAdapter(mListViewAdapter);
mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
});
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (totalItemCount > Constant.MIN_ITEM_COUNT && lastInScreen >= (totalItemCount - Constant.MIN_ITEM_COUNT_HALF) && !isLoadMore && mCurrectPage <= mPageCount)
{
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
});
return _result;
}
public void loadPostsList() {
isLoadMore = true;
mLoadingFooter.setVisibility(View.VISIBLE);
new AsynckRequestGet().execute(getActivity(), TYPE_GET_OPERATION.POSTS, CodeRequestManager.codePosts(TempData.getInstance().getToken(), mCurrectPage));
}
private class AsynckRequestGet extends AbstractAsyncRequestGet {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
isLoadMore = false;
if(!isDetached()) {
mLoadingFooter.setVisibility(View.GONE);
mListView.onRefreshComplete();
}
if(result == null) return;
int[] t = JsonParser.parsePageCountResponse(result);
mPageCount = t[0];
mCurrectPage = t[1] +1;
ArrayList<Post> temp = JsonParser.parsePostsResponse(result);
if(temp == null || isDetached())
return;
mPosts.addAll(temp);
mListViewAdapter.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<Post> {
private LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Post> objects) {
super(context, R.layout.post_item, objects);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.post_item, null);
final Post post = getItem(position);
final TextView postLikes = ((TextView) convertView.findViewById(R.id.post_likes));
final TextView postComments = ((TextView) convertView.findViewById(R.id.post_comments));
postComments.setText(post.getCountComment() + "");
postLikes.setText(post.getCountLike() + "");
if(post.isMyLike()) {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_my_icon, 0, 0, 0);
} else {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_icon, 0, 0, 0);
}
postLikes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AbstractAsyncRequestGet().execute(getActivity(), TYPE_GET_OPERATION.LIKE, CodeRequestManager.codeLike(TempData.getInstance().getToken(), post.getId(), post.isMyLike()? 0 : 1));
post.setCountLike((post.getCountLike()) + (post.isMyLike()? -1 : 1));
post.setMyLike(post.isMyLike()? 0 : 1);
postLikes.setText(post.getCountLike() + "");
mListViewAdapter.notifyDataSetChanged();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
((TrainingFragment) getParentFragment().getParentFragment()).showPostDetails(mPosts.get(arg2-1), new DetailListener() {
#Override
public void onRefresh() {
if(!isDetached())
mListViewAdapter.notifyDataSetChanged();
}
})
;}
});
((TextView) convertView.findViewById(R.id.post_title)).setText(post.getTitle());
((TextView) convertView.findViewById(R.id.post_content)).setText(post.getContent());
return convertView;
}
}
}
If you get the latest Facebook Android SDK, you can find the NativeAdSample project updated with how to display native ads in a list view. Code copied from the sample:
package com.facebook.samples.NativeAdSample;
import java.util.ArrayList;
import java.util.List;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.NativeAd;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class NativeAdListActivity extends ListActivity implements AdListener {
private ListView listView;
private ListViewAdapter adapter;
private NativeAd listNativeAd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listNativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
listNativeAd.setAdListener(this);
listNativeAd.loadAd();
listView = getListView();
adapter = new ListViewAdapter(getApplicationContext());
listView.setAdapter(adapter);
}
#Override
public void onAdClicked(Ad ad) {
Toast.makeText(this, "Ad Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdLoaded(Ad ad) {
adapter.addNativeAd((NativeAd) ad);
}
#Override
public void onError(Ad ad, AdError error) {
Toast.makeText(this, "Ad failed to load: " + error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
class ListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Object> list;
private NativeAd ad;
private static final int AD_INDEX = 2;
public ListViewAdapter(Context context) {
list = new ArrayList<Object>();
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 1; i <= 35; i++) {
list.add("ListView Item #" + i);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == AD_INDEX && ad != null) {
// Return the native ad view
return (View) list.get(position);
} else {
TextView view; // Default item type (non-ad)
if (convertView != null && convertView instanceof TextView) {
view = (TextView) convertView;
} else {
view = (TextView) inflater.inflate(R.layout.list_item, parent, false);
}
view.setText((String) list.get(position));
return view;
}
}
public synchronized void addNativeAd(NativeAd ad) {
if (ad == null) {
return;
}
if (this.ad != null) {
// Clean up the old ad before inserting the new one
this.ad.unregisterView();
this.list.remove(AD_INDEX);
this.ad = null;
this.notifyDataSetChanged();
}
this.ad = ad;
View adView = inflater.inflate(R.layout.ad_unit, null);
NativeAdSampleActivity.inflateAd(ad, adView, NativeAdListActivity.this);
list.add(AD_INDEX, adView);
this.notifyDataSetChanged();
}
}
}