Is it possible change the fragment when listview click - java

I would like to change the fragment when listview item clicked under Bottom navigation activity
But I have not idea how to write the OnClickListener
Anyone can provide some hints or tell me what wrong in this program?
Here is the program
And thank you for spend the time to view my program
Thank you very much
package com.example.campus.ui.campus;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.c.MainActivity;
import com.example.c.R;
import com.example.c.database.campus.CampusData;
import com.example.c.ui.campusInformation.CampusInformationActivity;
import com.example.c.ui.campusInformation.CampusInformationFragment;
import java.util.ArrayList;
import java.util.List;
public class CampusListLayoutAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<CampusData> campusList = new ArrayList<CampusData>();
private int resourceViewID;
private Context context;
private Context mContext;
static class ViewHolder{
LinearLayout llCampusCard;
TextView tvCampusName;
TextView tvCampusAddress;
ImageView ivCampusImage;
}
public CampusListLayoutAdapter(Context c, List<CampusData> campusList){
context = c;
layoutInflater = LayoutInflater.from(c);
this.campusList = campusList;
}
#Override
public int getCount() {
return campusList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
mContext = viewGroup.getContext();
ViewHolder holder = new ViewHolder();
view = layoutInflater.inflate(R.layout.listview_campus, null);
if(view != null){
holder.tvCampusName = view.findViewById(R.id.tvCampusName);
holder.tvCampusAddress = view.findViewById(R.id.tvCampusAddress);
holder.ivCampusImage = view.findViewById(R.id.ivCampusImage);
holder.tvCampusName.setText(campusList.get(i).name);
holder.tvCampusAddress.setText(campusList.get(i).address);
String image = campusList.get(i).image;
resourceViewID = context.getResources().getIdentifier(image, "drawable", context.getPackageName());
holder.ivCampusImage.setImageResource(resourceViewID);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}else {
return null;
}
}
}

First of all, create an interface in your adapter class.
public interface Callbacks {
void onItemClick(YourObject object, int position); // arguments as per the requirement
}
change your constructor of adapter as
Callbacks callback;
public CampusListLayoutAdapter(Context c, List<CampusData> campusList, Callbacks callback){
.....
this.callback = callback;
}
Now in your onClick() use..
callback.onItemClick(yourClickedItem, position)
then pass an anonymous or simply implement interface in your activity.
adapter = new CampusListLayoutAdapter(context, list, new CampusListLayoutAdapter.Callbacks() {
#Override
public void onItemClick(Alert_bean alert, int position) {
// do what you want here in activity like changing fragment or view updates
}
});

Related

App crash when trying to move intent to another adapter

So I have two Adapter class for RecyclerView. I want the ImageView inside one Adapter class to display the other Adapter class
I already tried to use intent on MainActivity
// listener for image
cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Intent detail = new Intent(context,DetailAdapter.class);
context.startActivity(detail);
}
}
));
here is the link for what the application supposed to be
https://ibb.co/gmnnghw
https://giphy.com/gifs/Y3NK0lHfAcN1dGbCZX
CardViewDeviceAdapter
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
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.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardViewDeviceAdapter extends RecyclerView.Adapter<CardViewDeviceAdapter.CardViewHolder> {
private Context context;
private ArrayList<Device> deviceArrayList;
private ArrayList<Device> getDeviceArrayList() {
return deviceArrayList;
}
public void setDeviceArrayList(ArrayList<Device> deviceArrayList) {
this.deviceArrayList = deviceArrayList;
}
public CardViewDeviceAdapter(Context context) {
this.context = context;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_device, viewGroup, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardViewHolder cardViewHolder, int i) {
Device d = getDeviceArrayList().get(i);
Glide.with(context)
.load(d.getPhoto())
.apply(new RequestOptions().override(350, 550))
.into(cardViewHolder.photo);
cardViewHolder.title.setText(d.getTitle());
cardViewHolder.detail.setText(d.getDetail());
// listener untuk button favorite
cardViewHolder.favorite.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Toast.makeText(context, "Favorite device"+getDeviceArrayList()
.get(position)
.getTitle()
, Toast.LENGTH_SHORT).show();
}
}
));
// listener untuk button share
cardViewHolder.share.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Toast.makeText(context, "Share device"+getDeviceArrayList()
.get(position)
.getTitle()
, Toast.LENGTH_SHORT).show();
}
}
));
// listener untuk image
cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Intent detail = new Intent(context, DetailAdapter.class);
context.startActivity(detail);
}
}
));
}
#Override
public int getItemCount() {
return getDeviceArrayList().size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
ImageView photo;
TextView title, detail;
Button favorite, share;
public CardViewHolder(View itemView) {
super(itemView);
photo = itemView.findViewById(R.id.pc_photo);
title = itemView.findViewById(R.id.pc_name);
detail = itemView.findViewById(R.id.pc_details);
favorite = itemView.findViewById(R.id.pc_favourite);
share = itemView.findViewById(R.id.pc_share);
}
}
}
DetailAdapter
package com.example.myapplication;
import android.content.Context;
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.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.DetailHolder> {
private Context context;
private ArrayList<Device> deviceArrayList;
private ArrayList<Device> getDeviceArrayList() {
return deviceArrayList;
}
#NonNull
#Override
public DetailAdapter.DetailHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.detail_adapter, viewGroup, false);
return new DetailAdapter.DetailHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DetailAdapter.DetailHolder detailHolder, int i) {
Device d = getDeviceArrayList().get(i);
Glide.with(context)
.load(d.getPhoto())
.apply(new RequestOptions().override(350, 550))
.into(detailHolder.photo);
detailHolder.title.setText(d.getTitle());
detailHolder.detail.setText(d.getDetail());
detailHolder.summary.setText(d.getSummary());
detailHolder.origin.setText(d.getOrigin());
detailHolder.market_value.setText(d.getMarket_value());
detailHolder.consumer.setText(d.getConsumer());
}
#Override
public int getItemCount() {
return getDeviceArrayList().size();
}
public class DetailHolder extends RecyclerView.ViewHolder {
ImageView photo;
TextView title, detail, summary, origin, market_value, consumer;
public DetailHolder(View view) {
super(view);
photo = view.findViewById(R.id.photo_detail);
title = view.findViewById(R.id.title_title);
detail = view.findViewById(R.id.detail_title);
summary = view.findViewById(R.id.detail_detail);
origin = view.findViewById(R.id.origin_year);
market_value = view.findViewById(R.id.market_value);
consumer = view.findViewById(R.id.konsumer);
}
}
}
Right now it asks for explicit activity on AndroidManifest.xml ,
but I can't assign DetailAdapter to AndroidManifest.xml
Logcat
2019-05-29 17:38:59.097 8897-8897/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 8897
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.myapplication/com.example.myapplication.DetailAdapter}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2012)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1675)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at com.example.myapplication.CardViewDeviceAdapter$3.onItemClicked(CardViewDeviceAdapter.java:89)
at com.example.myapplication.CustomOnItemClick.onClick(CustomOnItemClick.java:16)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:782)
at android.view.View$PerformClick.run(View.java:25945)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
App crashses when tapping on Image
You've got all the concept of RecyclerView wrong. Check out how to use RecyclerView from
Simple RecyclerView Example.
What you're trying to do is launch RecyclerView like an Activity. Your RecyclerView is not an activity, it is a view.
In the gif you've attached to shown what you want to accomplish, it's a completely different thing. After clicking the item in RecyclerView, a new activity is launched with SharedElement transition. Your DetailAdapter should be AppCompatActivity.
To correct your error, make your DetailAdapter extend AppCompatActivity, after doing that, while launching the DetailAdapter with Intent, pass the data like title, detail through Intent.

How can I pass a created array from Custom adapter class to other class?

I'm trying to pass a String list from my custom array class to another class, but for some reason when I try to access the list, it always seems empty.
Here is my Custom Adapter class:
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CustomAdapter extends ArrayAdapter {
private final List<Model> orders;
private final Context context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public List<String> selectedItems = new ArrayList<>();
public CustomAdapter(#NonNull Context context, List<Model> orders) {
super(context, R.layout.company_list_order, orders);
this.context = context;
this.orders = orders;
}
static class ViewHolder {
protected TextView orderText;
protected CheckBox checkOrder;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
selectedItems = new ArrayList<>();
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.company_list_order, parent, false);
viewHolder = new ViewHolder();
viewHolder.orderText = (TextView) convertView.findViewById(R.id.textViewList);
viewHolder.checkOrder = (CheckBox) convertView.findViewById(R.id.listCheckBox);
viewHolder.checkOrder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
orders.get(getPosition).setSelected(buttonView.isChecked());
if (orders.get(getPosition).isSelected()) {
selectedItems.add(orders.get(getPosition).getName());
Log.d("Add", "Item added: " + orders.get(getPosition).getName());
Log.d("Size", "Selected items " + selectedItems.size());
} else {
selectedItems.remove(orders.get(getPosition).getName());
Log.d("Remove", "Item removed: " + orders.get(getPosition).getName());
Log.d("Size", "Selected items " + selectedItems.size());
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.textViewList, viewHolder.orderText);
convertView.setTag(R.id.listCheckBox, viewHolder.checkOrder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkOrder.setTag(position);
viewHolder.orderText.setText(orders.get(position).getName());
viewHolder.checkOrder.setChecked(orders.get(position).isSelected());
return convertView;
}
public List<String> getListItems() {
return selectedItems;
}
}
At the bottom I have the method returning the list. How should I access this in another class?
Probably because you create a new ArrayList everytime getView() is called, which is called a lot. And when you call the method getListItems() the method getView() is called before due to scrolling the listview or something. Remove the line
selectedItems = new ArrayList<>();
from getView() method.
Another option is to make a class with static variables to hold the value during the applications lifetime
public class GlobalVars {
public static List<String> selectedItems;
}

java.lang.IllegalArgumentException: Context must not be null

I am using adapter to show images. In Adapter, How to get context when using Picasso?
I tried different solutions but I couldn't solve. What should I do when using picasso in Adapter? Context is a big problem for developers I see on the internet.
package gc.x;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import gc.ovidos_challenge.R;
import gc.ovidos_challenge.models.Image;
import java.net.URL;
import java.util.List;
public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.MyViewHolder> {
private List<Image> imagesList;
private Context context;
public ImagesAdapter(Context context) {
this.context = context;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView imageview;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.textview);
imageview = (ImageView) view.findViewById(R.id.imageurl);
}
}
public ImagesAdapter(List<Image> imagesList) {
this.imagesList = imagesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_image, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = imagesList.get(position);
holder.title.setText(image.title);
Picasso.with(this.context).load(image.url).into(holder.imageview);
// holder.imageview.setImageBitmap(image.getBitmapFromURL());
}
#Override
public int getItemCount() {
return imagesList.size();
}
}
you have created two constructors one for context and one for your data. use one constructor to initialize both of them
like this
public ImagesAdapter(Context context,List<Image> imagesList) {
this.context = context;
this.imagesList=imagesList;
}

proper way of creating method in your custom listview adapter

I created a simple android application with a ListView in it. I have my custom list adapter below:
package com.example.android.efaas;
import java.util.List;
import com.example.android.R;
import com.example.android.efaas.bean.ListItem;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomListAdapter extends BaseAdapter {
LayoutInflater inflater = null;
Context ctx;
List<ListItem> data;
public CustomListAdapter(Activity activity, List<ListItem> data){
ctx = activity;
this.data = data;
inflater = ( LayoutInflater )ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int pos) {
return pos;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View view, ViewGroup vgroup) {
View rowView = inflater.inflate(R.layout.list_menu, null);
ImageView img = (ImageView) rowView.findViewById(R.id.list_menu_image);
TextView title = (TextView) rowView.findViewById(R.id.list_menu_title);
ListItem item = data.get(pos);
img.setImageResource(item.getId());
title.setText(item.getTitle());
return rowView;
}
public ListItem getListItem(int pos){
return data.get(pos);
}
}
I have a public method getListItem, I tried to call it during ListView onClick but somehow I cant seem to make it work. Here's the image of the problem:
How do I resolve this?
You should cast adapter.getAdapter() to CustomListAdapter class then
the compile time error is due of the fact that adapter is not your CustomListAdapter. What you can do is cast the return value of adapter.getAdapter() to CustomListAdapter. Conversely you should use what's already available to retrieve the object at position. Like getItemAtPosition(int)

Image url passing null value to another Intent

I have implemented RecyclerView in my app and have setup a onClickListener on Recycler View. The text fields are passing successfully, however I also have a image in the recyclerview, which is being brought through picasso. So I try to retrieve the image url which is stored in another class, but I'm getting a empty value.
The code is:
package xyz.xyz;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class FlatSearchCardAdapter extends RecyclerView.Adapter<FlatSearchCardAdapter.ViewHolder> {
private Context context;
private ImageLoader imageLoader;
List<FlatCardItemReturn> flatlistCard;
public FlatSearchCardAdapter(List<FlatCardItemReturn> flatlistCard, Context context){
super();
//Getting all the superheroes
this.flatlistCard = flatlistCard;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.flatrenter_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FlatCardItemReturn flatcarditemreturn = flatlistCard.get(position);
Picasso.with(context).load(flatcarditemreturn.getImageUrl()).placeholder(R.drawable.loadingpicasso).error(R.drawable.errorpicasso).resize(100, 100).into(holder.imageView);
holder.textViewId.setText(flatcarditemreturn.getId());
holder.textViewType.setText(flatcarditemreturn.getType());
holder.textViewFurnishing.setText(flatcarditemreturn.getFurnishing());
holder.textViewArea.setText(flatcarditemreturn.getArea());
holder.textViewPrice.setText(flatcarditemreturn.getPrice());
holder.textViewNumberofrooms.setText(flatcarditemreturn.getNumberofrooms());
}
#Override
public int getItemCount() {
return flatlistCard.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public TextView textViewType;
public TextView textViewPrice;
public TextView textViewFurnishing;
public TextView textViewArea;
public TextView textViewNumberofrooms;
public TextView textViewId;
public FlatCardItemReturn flatcarditemreturn = new FlatCardItemReturn();
public ViewHolder(View itemView) {
super(itemView);
textViewId = (TextView) itemView.findViewById(R.id.id);
imageView = (ImageView) itemView.findViewById(R.id.flatphoto);
textViewType = (TextView) itemView.findViewById(R.id.type);
textViewFurnishing = (TextView) itemView.findViewById(R.id.furnishing);
textViewArea = (TextView) itemView.findViewById(R.id.area);
textViewPrice = (TextView) itemView.findViewById(R.id.price);
textViewNumberofrooms = (TextView) itemView.findViewById(R.id.numberofrooms);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), flatrenterpostview.class);
i.putExtra("idvalue", textViewId.getText().toString());
i.putExtra("typevalue", textViewType.getText().toString());
i.putExtra("furnishingvalue", textViewFurnishing.getText().toString());
i.putExtra("areavalue", textViewArea.getText().toString());
i.putExtra("pricevalue", textViewPrice.getText().toString());
i.putExtra("numberofroomsvalue", textViewNumberofrooms.getText().toString());
i.putExtra("imageurl", flatcarditemreturn.getImageUrl());
v.getContext().startActivity(i);
}
});
}
}
}
I'm pretty confused on how to set the position in that, so as to get the currect value. Will be grateful if anyone can help me out.
Just to make it clear, i.putExtra("imageurl", flatcarditemreturn.getImageUrl()); is giving nothing. I expect the url stored in my class. The url is stored perfectly, I checked.
Just to make it clear, i.putExtra("imageurl", flatcarditemreturn.getImageUrl()); is giving nothing. I expect the url stored in my class
Then why do you create a new FlatCardItemReturn in your ViewHolder? This line:
public FlatCardItemReturn flatcarditemreturn = new FlatCardItemReturn();
You'll want to set the correct data item to the ViewHolder, rather that instantiating a new 'empty' one. You can easily accomplish this by adding a method to the ViewHolder:
public void setData(FlatCardItemReturn item) {
flatcarditemreturn = item;
}
Now, just call this from onBindViewHolder():
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FlatCardItemReturn flatcarditemreturn = flatlistCard.get(position);
// other stuff omitted
holder.setData(flatcarditemreturn);
}
You can now also change:
public FlatCardItemReturn flatcarditemreturn = new FlatCardItemReturn();
into:
public FlatCardItemReturn flatcarditemreturn;

Categories