Adapters in Java Android stuio - java

I'm trying to make and activity that uses fragment with viewpager2 and I'm having problem populating the grid view inside the viewpage2. and I'm having trouble using adapters. what are the steps I need to know to make this activity work?
this is my fragment class
public class item_frag extends Fragment{
Context context;
FragmentItemDisplayBinding binding;
String name, description, category, price, imageurl;
FirebaseStorage firebaseStorage;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("inventory");
firebaseStorage = FirebaseStorage.getInstance();
name = databaseReference.getDatabase().getReference("inventory").toString();
description = databaseReference.getDatabase().getReference("inventory").toString();
category = databaseReference.getDatabase().getReference("inventory").toString();
price = databaseReference.getDatabase().getReference("inventory").toString();
imageurl = firebaseStorage.getReference("inventory").toString();
String[] itemname = {"hello"};
int[] itemimage = {R.drawable.unimas_logo};
View view = inflater.inflate(R.layout.fragment_item_display, container, false);
GridView gridView = (GridView) view.findViewById(R.id.grid_view);
item_frag_adapter itemFragAdapter = new item_frag_adapter(context, itemname, itemimage);
gridView.setAdapter(itemFragAdapter);
return inflater.inflate(R.layout.fragment_item_display, container, false);
}
}
this is my item fragment adapter class
public class item_frag_adapter extends BaseAdapter {
Context context;
String[] itemname;
int[] image;
LayoutInflater inflater;
public item_frag_adapter(Context context, String[] itemname, int[] image) {
this.context = context;
this.itemname = itemname;
this.image = image;
}
#Override
public int getCount() {
return itemname.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
convertView = inflater.inflate(R.layout.item_card,null);
}
ImageView imageView = convertView.findViewById(R.id.idIVimage);
TextView textView = convertView.findViewById(R.id.idTVtext);
imageView.setImageResource(image[position]);
textView.setText(itemname[position]);
return convertView;
}
}

Related

RecyclerView onCreateViewHolder method not calling

Below are my ShelflifeAdapter and HomeFragment classes:-
public class HomeFragment extends Fragment {
RecyclerView shelflifeRecyclerview;
ShelflifeAdapter shelflifeAdapter;
Product product;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_home, container, false);
shelflifeRecyclerview = rootView.findViewById(R.id.shelflifeRecyclerview);
shelflifeAdapter = new ShelflifeAdapter(getContext());
shelflifeRecyclerview.setAdapter(shelflifeAdapter);
shelflifeRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
shelflifeRecyclerview.setHasFixedSize(true);
//fragment->fragment 데이터받기
Bundle bundle = getArguments(); //번들 받기
if(bundle != null){
product = new Product();
product = (Product) bundle.getSerializable("bundle");
shelflifeAdapter.addItem(product);
Log.d("TAG", shelflifeAdapter.getItemCount() +" 갯수");
}
return rootView;
}
}
public class ShelflifeAdapter extends RecyclerView.Adapter<ShelflifeAdapter.ViewHolder>{
ArrayList<Product> items = new ArrayList<Product>();
Context mContext;
ShelflifeAdapter(Context context){
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d("TAG","onCreateViewHolder 작동함");
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_shelflife,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
Log.d("TAG","onBindViewHolder 작동함");
Product item = items.get(position);
viewHolder.setItem(item,mContext);
}
#Override
public int getItemCount() {
return items.size();
}
public void addItem(Product item){
if(item != null){
Log.d("TAG","addItem 작동함(item 추가) : " + item.toString());
items.add(item);
notifyDataSetChanged();
}else{
Log.d("TAG","addItem 작동함(item 못가져옴)");
}
}
public void setItems(ArrayList<Product> items){
this.items = items;
}
public Product getItem(int position){
return items.get(position);
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView tv_shelflife;
LinearLayout itemContainer;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
tv_shelflife = itemView.findViewById(R.id.tv_shelflife);
itemContainer = itemView.findViewById(R.id.itemContainer);
}
public void setItem(Product item, Context context){
if(item != null){
Log.d("TAG","어댑터의 item : "+ item.toString());
if(item.getImage()==null){
Glide.with(itemView).load(R.drawable.no_image).override(48,48).into(imageView);
}else{
Glide.with(itemView).load(item.image).override(48,48).into(imageView);
}
tv_shelflife.setText(item.shelflifeDate);
}else{
Log.d("TAG","item이 null임" );
}
}
}
}
addItem(Product item) is working well
But onCreateViewHolder method is not working.
Any help is appreciated !!!
initialize recycler view first ,then set adapter for recycler view.
shelflifeAdapter = new ShelflifeAdapter(getContext());
shelflifeRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
shelflifeRecyclerview.setHasFixedSize(true);
//Always set adapter after setLayoutManager, setHasFixedSize
shelflifeRecyclerview.setAdapter(shelflifeAdapter);
Bundle bundle = getArguments(); //번들 받기
if(bundle != null){
product = new Product();
product = (Product) bundle.getSerializable("bundle");
shelflifeAdapter.addItem(product);
Log.d("TAG", shelflifeAdapter.getItemCount() +" 갯수");
}
And make sure item is not null
Product item = items.get(position);
if(item!=null)
viewHolder.setItem(item,mContext);
pass context into glide
if(item.getImage()==null){
Glide.with(context).load(R.drawable.no_image).override(48,48).into(imageView);
}else{
Glide.with(context).load(item.image).override(48,48).into(imageView);
}
tv_shelflife.setText(item.shelflifeDate);

String Values not showing in listview using base adapter

I am passing value as string from an activity through intent to this Page Activity and adding it to an arraylist and setting that list to an list view using base adapter.But unfortunately its the values are not showing in listview.
And I am not able to figure out how to set that value to the textview present in PagesAdapter.java.
Please help me guys.
Pages.java
public class Pages extends Activity implements AdapterView.OnItemClickListener {
private static final String TAG = null;
private List<String> list = new ArrayList<>();
private ListView listView;
private PagesAdapter pageadapter;
private String androidOS;
private String device_uuid;
private String contributor_id;
public String tocName;
public String categoryName;
private SessionManager session;
private String first_Page;
private String last_Page;
private String current_Page;
private String firstPage;
private String lastPage;
private String currentPage;
ProgressDialog loading;
private String page;
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
page = getIntent().getExtras().getString("CONTENT");
name = getIntent().getExtras().getString("NAME");
session = new SessionManager(getApplicationContext());
SharedPreferences pref = this.getSharedPreferences("preferences", 0);
firstPage = pref.getString("firstpage",null);
lastPage = pref.getString("lastpage",null);
currentPage = pref.getString("currentpage",null);
contributor_id = pref.getString("contributor_id",null);
loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//getData();
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
androidOS = Build.VERSION.RELEASE;
device_uuid = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
list.add(name);
pageadapter = new PagesAdapter(Pages.this, list);
listView.setAdapter(pageadapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(Pages.this, RecordComposition.class);
i.putExtra("PAGE",page);
startActivity(i);
}
}
PagesAdapter.java
public class PagesAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<String> Pagelist;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public PagesAdapter(Activity activity, List<String> billionairesItems) {
this.activity = activity;
this.Pagelist = billionairesItems;
}
#Override
public int getCount() {
return Pagelist.size();
}
#Override
public Object getItem(int location) {
return Pagelist.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.pages_view, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView name = (TextView) convertView.findViewById(R.id.name);
// String m = Pagelist.get(position);
// thumbNail.setImageUrl(m.getImage(), imageLoader);
// name.setText(m.get);
return convertView;
}
}
You have to set value to the textView :
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(Pagelist.get(position));
The first problem is related to your list variable. You are passing it as a Empty List, because you are not populating it with String values.
The adapter will scan your list and verify that there is no data to display, so try to put some data inside the list variable and test the ListView again.
The second question is easy to resolve, just add these lines inside your getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(Pagelist.get(position));
}

Grid Item button not working

I have a GridView and an adapter called MyAdapter. My button in each grid is not showing a dialog box as it should do (MyAdapter.java). Here is my code, I am not sure what I am missing here:
MyAdapter.java
public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Players> playerList;
private static LayoutInflater inflater = null;
Button btnRoleReveal;
public MyAdapter(Context context, ArrayList<Players> playerList){
this.context = context;
this.playerList = playerList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return playerList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(layout_grid_item, null);
final Button button = (Button) convertView.findViewById(R.id.btnRoleReveal);
TextView idTextView = (TextView) convertView.findViewById(R.id.tv_player_id);
TextView nameTextView = (TextView) convertView.findViewById(R.id.tv_player_name);
final TextView roleTextView = (TextView) convertView.findViewById(R.id.tv_player_role);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(context)
.setTitle("Test")
.setMessage("Test");
}
});
Players p = new Players();
p = playerList.get(position);
idTextView.setText("ID: " + String.valueOf(p.getId()));
nameTextView.setText("Name: " + String.valueOf(p.getName()));
roleTextView.setText("Role: " + String.valueOf(p.getRole()));
return convertView;
}
}
RolesFragment.java
public class RolesFragment extends Fragment implements View.OnClickListener {
GridView gridView;
ArrayList<Players> playersList;
MyAdapter adapter;
Button role;
public RolesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewroles, container, false);
gridView = (GridView) view.findViewById(R.id.gv_players);
role = (Button) view.findViewById(R.id.btnRoleReveal);
DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
playersList = new ArrayList<Players>();
playersList = databaseHelper.getPlayers();
adapter = new MyAdapter(getActivity(), playersList);
gridView.setAdapter(adapter);
return view;
}
#Override
public void onClick(View v) {
}
}
You're missing the show() call on the dialog:
new AlertDialog.Builder(context)
.setTitle("Test")
.setMessage("Test")
.show();

Android Checkbox in Listview selecting automatically

in my android application I am displaying the contact list of phone in a list view and a check box in each row for selecting contacts. But when I am selecting a particular row about tenth row is also getting selected automatically. I am giving my code below, if any one knows please help..
public class ContactsAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Contact> contacts;
public ContactsAdapter(Context context, ArrayList<Contact> contacts)
{
this.context = context;
this.contacts = contacts;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
final ViewHolder mHolder;
if (convertView == null)
{
// gridView = new View(context);
// get layout from mobile.xml
//gridView = inflater.inflate(R.layout.contact, null);
convertView = inflater.inflate(R.layout.contact, null);
mHolder = new ViewHolder();
mHolder.textName =(TextView) convertView.findViewById(R.id.name);
mHolder.textMobile =(TextView) convertView.findViewById(R.id.mobile);
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
convertView.setTag(mHolder);
));
}
else
{
mHolder = (ViewHolder) convertView.getTag();
mHolder.textSelector.setOnCheckedChangeListener(null);
}
mHolder.textMobile.setText(contacts.get(position).getMobile());
mHolder.textName.setText(contacts.get(position).getName());
mHolder.textSelector.setFocusable(false);
return convertView;
}
private class ViewHolder {
private TextView textMobile,textName;
private CheckBox textSelector;
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
Well Thats because ViewHolder will recycle the Views everytime you Scroll
i suggest you to Use onCLick on ListItem instead checkbox
To overcome this Declare a SparseBooleanArray
SparseBooleanArray sba=new SparseBooleanArray();//this should be global
Then set the items checked state as soon as you render it
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
mHolder.textSelector.setChecked(sba.get(position));
Then write a onClickListener to you convertView and check it manually
convertView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mHolder.textSelector.setChecked(isChecked);
sba.put(position,isChecked); //storing the state
}
}
);
**Well Now the sba has list items checked and you can use that for further Actions**
# Jocheved... edit your code like this...
public class ContactsAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Contact> contacts;
SparseBooleanArray sba=new SparseBooleanArray();
public ContactsAdapter(Context context, ArrayList<Contact> contacts)
{
this.context = context;
this.contacts = contacts;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ViewHolder mHolder;
if (convertView == null)
{
convertView = inflater.inflate(R.layout.contact, null);
mHolder = new ViewHolder();
mHolder.textName =(TextView) convertView.findViewById(R.id.name);
mHolder.textMobile =(TextView) convertView.findViewById(R.id.mobile);
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
convertView.setTag(mHolder);
}
else
{
mHolder = (ViewHolder) convertView.getTag();
}
mHolder.textMobile.setText(contacts.get(position).getMobile());
mHolder.textName.setText(contacts.get(position).getName());
mHolder.textName.setSelected(true);
mHolder.textSelector.setChecked(sba.get(position));
mHolder.textSelector.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if(mHolder.textSelector.isChecked())
{
sba.put(position, true);
}
else
{
sba.put(position, false);
}
}
});
return convertView;
}
private class ViewHolder
{
private TextView textMobile,textName;
private CheckBox textSelector;
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}

Dynamically loading data to a new view

First im loading the data dynamically to a grid which is in the PMenu.java, then each item has view more button. once I pressed that I want to load the image, name and its amount in the item description view.
Im using a custom grid to load data to the grid in PMenu.java, and I have placed a button in the custom grid, so that it will navigate to viewmore.java.
I want to know once i press the button then how to load the data to viewmore.java file
PMenu.java fragment
GridView grid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu_grid_main, container, false);
new PMenuAsyncTask(getActivity(), this).execute();
grid = (GridView) view.findViewById(R.id.grid);
return view;
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> descriptions = new ArrayList<String>();
List<String> imageUrls = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
Log.i("ImageURL ", object.getString("ImageURL"));
imageUrls.add(object.getString("ImageURL"));
Log.i("Description ", object.getString("Description"));
descriptions.add(object.getString("Description"));
}
}
CustomGrid adapter = new CustomGrid(getActivity(), descriptions,
imageUrls);
grid.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomGrid class
public class CustomGrid extends BaseAdapter {
private Context context;
private final List<String> descriptions;
private final List<String> imageUrls;
public CustomGrid(Context c, List<String> descriptions, List<String> imageUrls) {
this.context = c;
this.descriptions = descriptions;
this.imageUrls = imageUrls;
}
#Override
public int getCount() {
return descriptions.size();
}
#Override
public Object getItem(int position) {
return descriptions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.fragment_pizza, parent, false);
holder.ivImage = (ImageView) convertView
.findViewById(R.id.grid_image);
holder.tvHeader = (TextView) convertView
.findViewById(R.id.grid_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvHeader.setText(descriptions.get(position));
Picasso.with(this.context).load(imageUrls.get(position)).into(holder.ivImage);
Button backButton = (Button) convertView.findViewById(R.id.button1);
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent next = new Intent(context, viewmore.class);
context.startActivity(next);
next.putExtra("description", descriptions.get(position));
next.putExtra("imageUrl", imageUrls.get(position));
context.startActivity(next);
}
});
return convertView;
}
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
}
}
viewmore.java
public class viewmore extends Activity {
private Context context;
private final List<String> descriptions;
private final List<String> imageUrls;
public viewmore(Context c, List<String> descriptions, List<String> imageUrls) {
this.context = c;
this.descriptions = descriptions;
this.imageUrls = imageUrls;
}
private ActionBar actionBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_viewmore);
String description = getIntent().getStringExtra("description");
String imageUrl = getIntent().getStringExtra("imageUrl");
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
// Associate searchable configuration with the SearchView
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
return true;
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.activity_viewmore, parent, false);
holder.ivImage = (ImageView) convertView
.findViewById(R.id.grid_image);
holder.tvHeader = (TextView) convertView
.findViewById(R.id.grid_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvHeader.setText(descriptions.get(position));
Picasso.with(this.context).load(imageUrls.get(position)).into(holder.ivImage);
return convertView;
}
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
}
}
You can use intent.putExtra("key", value) methods before starting the viewmore Activity.
Then in the viewmore Activity, you can get these data from the getIntent().get*Extra("key") methods.
Like:
Intent next = new Intent(context, viewmore.class);
next.putExtra("description", descriptions.get(position));
next.putExtra("imageUrl", imageUrls.get(position));
context.startActivity(next);
Then (in viewmore Activity):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_viewmore);
String description = getIntent().getStringExtra("description");
String imageUrl = getIntent().getStringExtra("imageUrl");
// Get the TextView using its ID defined in the layout activity_viewmore.xml
TextView tv = (TextView) findViewById(R.id.my_text_view);
tv.setText(description);
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Picasso.with(this).load(imageUrl).into(imageView);
}

Categories

Resources