How to pass data from a user activity to a recyclerview? - java

I want to make a interface which user can add its data to activity and after its must be show on in recyclerview, I used manual data adding in code it's working but I want to user must be able to store its data on application and can see & modified.
I used put_extra function but is not working.`
[code for put_put Extra]
Here is adapter class:
public class Handler_Adapter extends RecyclerView.Adapter<Handler_Adapter.MyViewHolders> {
ArrayList<MyMode> myModel;
View ReceivedImages;
Context context;
public Handler_Adapter (Context context, ArrayList<MyMode> list, View myImagesF){
this.context=context;
this.myModel=list;
ReceivedImages=myImagesF;
}
#Override
public MyViewHolders onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater= LayoutInflater.from(context);
View view = inflater.inflate(R.layout.row,parent,false);
return null;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolders holder, int position) {
holder.EName.setText(myModel.get(position).getLangName());
holder.E_Des.setText(myModel.get(position).getLangName());
holder.Price.setText(myModel.get(position).getLangName());
holder.itemsSize.setText(myModel.get(position).getLangName());
holder.myImages.setImageResource(myModel.get(position).getLangLogo());
holder.rows.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public int getItemCount() { return myModel.size();
}
public class MyViewHolders extends RecyclerView.ViewHolder {
TextView EName,E_Des,Price,itemsSize;
ImageView myImages;
RelativeLayout rows;
public MyViewHolders(#NonNull View itemView) {
super(itemView);
EName=itemView.findViewById(R.id.EName);
E_Des=itemView.findViewById(R.id.E_Des);
ReceivedImages=itemView.findViewById(R.id.my_Imaage);
Price=itemView.findViewById(R.id.E_Price);
itemsSize=itemView.findViewById(R.id.itemsSize);
rows=itemView.findViewById(R.id.rows);
}
}
}
Here is UserActivity
public class AddMenu extends AppCompatActivity {
public static final String TEXT_TO_SEND="com.example.EMenu.TEXT_TO_SEND";
private ImageView mImageView;
private EditText EName,E_Des,E_Price,E_size;
private Button Import;
private String TextToSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_menu);
mImageView=findViewById(R.id.imageFilterView);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImagePicker.Companion.with(AddMenu.this)
.crop()
// .cropOval()
.compress(1024)
.maxResultSize(1080,1080)
.start();
}
});
Import=findViewById(R.id.Import);
EName=findViewById(R.id.EName);
E_Des=findViewById(R.id.E_Des);
E_Price=findViewById(R.id.E_Price);
E_size=findViewById(R.id.E_size);
Import.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextToSend=EName.toString().toUpperCase().trim();
TextToSend=E_Des.toString().toLowerCase().trim();
TextToSend=E_Price.toString().toUpperCase().trim();
TextToSend=E_size.toString().toUpperCase().trim();
gotoActivity();
}
});
}
private void gotoActivity() {
Intent on=new Intent(AddMenu.this,Mainpage.class);
on.putExtra("Selected_Image",R.id.imageFilterView);
on.putExtra(TEXT_TO_SEND, String.valueOf(EName).toUpperCase());
on.putExtra(TEXT_TO_SEND, String.valueOf(E_Des));
on.putExtra(TEXT_TO_SEND, String.valueOf (E_Price).toUpperCase());
on.putExtra(TEXT_TO_SEND, String.valueOf(E_size).toUpperCase());
startActivity(on);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uri=data.getData();
mImageView.setImageURI(uri);
}
**Main page code_ at there is
used adding images manually
but I want to its added it by user activity**
public class Mainpage extends AppCompatActivity {
RecyclerView Recycler;
ArrayList<MainModels> mainModel;
MainAdapter mainAdapter;
Handler_Adapter mHandler_adapter;
ArrayList<MyMode> myModel;
SearchView SearchView;
ImageView mImageView,myImagesF;
////////////////////////////////////////////////////////: Images resource file..
String s1[],s2[],s3[],s4[];
/////////////////////////////////////////////////////.......... continue..............
RecyclerView recyclerView;
NavigationView click;
private FirebaseAuth fAuth;
private String currentUserId;
private DatabaseReference databaseReference;
Button Navigation;
//Menu Account,Settings,Restaurant,Menu;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
myModel = new ArrayList<>();
int images[]={R.drawable.delfina_cocciardi_ndpbk_d_03m_unsplash,R.drawable.ic_launcher_foreground,
R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_foreground };
/////////////////////////////////////.......Goat it data from input data fragment
mImageView=findViewById(R.id.my_Imaage);
Bundle bundle=getIntent().getExtras();
if (bundle != null){
int res_image=bundle.getInt("Selected_Image");
// mImageView.setImageResource(res_image);
}
//////////////////////////////////////////////////................!!!
recyclerView=findViewById(R.id.recyclerView);
Intent intent=getIntent();
s1=getResources().getStringArray(R.array.Menu_items);
s2=getResources().getStringArray(R.array.Description);
s3=getResources().getStringArray(R.array.Prices);
s4=getResources().getStringArray(R.array.Prices);
Adapter mAdapter=new Adapter(this,s1,s2,s3,s4,images);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new GridLayoutManager(this,2,RecyclerView.VERTICAL,false));
/*
recyclerView=findViewById(R.id.recyclerView);
Integer[] langLogos={R.id.imageFilterView};
Intent intent=getIntent();
String langNames=intent.getStringExtra(AddMenu.TEXT_TO_SEND);
if (langNames!=null){
TextView textView=findViewById(R.id.Menu_Name);
textView.setText(langNames);
}
String langPrice=intent.getStringExtra(AddMenu.TEXT_TO_SEND);
if (langPrice!=null){
TextView textView2=findViewById(R.id.Description_name);
textView2.setText(langPrice);
}
String langDisc=intent.getStringExtra(AddMenu.TEXT_TO_SEND);
if (langDisc!=null){
TextView textView3=findViewById(R.id.Price);
textView3.setText(langDisc);
}
String langSize=intent.getStringExtra(AddMenu.TEXT_TO_SEND);
if (langSize!=null){
TextView textView4=findViewById(R.id.itemsSize);
textView4.setText(langSize);
}
myModel=new ArrayList<>();
MyMode so=new MyMode(langLogos,langNames,langDisc,langPrice,langSize);
myModel.add(so);
GridLayoutManager gridLayoutManager= new GridLayoutManager(Mainpage.this,2,GridLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mHandler_adapter=new Handler_Adapter(Mainpage.this,myModel,myImagesF);
recyclerView.setAdapter(mHandler_adapter);
*/
// for (int j=0;j<langLogos.length;j++){
// }

Here is what you can do.
Create a private list in your activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myModel = new ArrayList<>();
}
Now change the constructor of your adapter.
public Handler_Adapter(Context context, ArrayList<MyModels> list, ...)
{
...
this.myModelList = list;
...
}
Now when you modify "myModel" than this is visible to your adapter.
All you have to do is to call the following once you modify it.
mHandlerAdapter.notifyDataSetChanged();

Related

How can I show/hide a layout in the main activity from a RecyclerView in android studio java?

I have an activity which consists of a recycler view for generating buttons (from a different layout file) and a layout with elements for confirmation.
I want to make it so when I click on the button "NEW GAME" (in the Recyclerview class), the confirmationLayout (in the MainMenu Activity) shows. But I can't, can someone help me?
MainMenu Class
public class MainMenu extends AppCompatActivity {
private ImageView profileIcon;
private TextView username;
private RelativeLayout newGameConfirmationLayout;
private TextView yesButton, noButton;
private RecyclerView buttonRecyclerView;
private ButtonRecyclerAdapter adapter;
private DataHandler dataHandler;
private ArrayList<String> buttonNames = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
newGameConfirmationLayout = findViewById(R.id.newGameConfirmationLayout);
yesButton = findViewById(R.id.yesButton);
noButton = findViewById(R.id.noButton);
buttonRecyclerView = findViewById(R.id.buttonRecyclerView);
buttonRecyclerView.setLayoutManager(new LinearLayoutManager(MainMenu.this));
if(General.infoSaved){buttonNames.add("CONTINUE GAME");}
buttonNames.add("NEW GAME");
buttonNames.add("CHANGE USER");
buttonNames.add("PRACTICE");
buttonNames.add("EXERCISE LIST");
adapter = new ButtonRecyclerAdapter(buttonNames, MainMenu.this);
buttonRecyclerView.setAdapter(adapter);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startGame();
}
});
noButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newGameConfirmationLayout.setVisibility(View.INVISIBLE);
}
});
}
private void startGame(){}
public void show_confirmationLayout(){
newGameConfirmationLayout.setVisibility(View.VISIBLE);
}
RecyclerView Class
public class ButtonRecyclerAdapter extends RecyclerView.Adapter<ButtonRecyclerAdapter.buttonHolder>{
private ArrayList<String> buttonNames;
private Context context;
public ButtonRecyclerAdapter(ArrayList<String> loginButtonNames, Context context) {
this.buttonNames = loginButtonNames;
this.context = context;
}
#NonNull
#Override
public buttonHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.button_block,parent,false);
return new buttonHolder(view);
}
#Override
public void onBindViewHolder(#NonNull buttonHolder holder, int position) {
holder.button.setText(buttonNames.get(position));
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String buttonName = holder.button.getText().toString();
switch (buttonName){
case "NEW GAME":
MainMenu mainMenu = new MainMenu();
mainMenu.show_confirmationLayout();
break;
}
}
});
}
#Override
public int getItemCount() {
return buttonNames.size();
}
public class buttonHolder extends RecyclerView.ViewHolder{
private Button button;
public buttonHolder(#NonNull View itemView) {
super(itemView);
button = itemView.findViewById(R.id.buttonblock);
}
}
}
I tried adding it as a class (as above) but I get the error that the layout is a null object / However when I try to write the ame line of code directly in the activity it works.
There's a method I personally use in my RecyclerView's Adapter and ViewHolder is to set the width and height of your item's ViewGroup to 0.
Here's the method you can add to your adapter class which takes item position that you want to hide:
public void hideFeedItem(int position){
RecyclerView.ViewHolder holder = getViewHolderAtPosition(position);
if(holder != null){
ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();
params.height=0;
params.width= 0;
holder.itemView.setLayoutParams(params);
}
}
Where itemview is the root ViewGroup that should be already defined in your ViewHolder in your case should be buttonHolder.

I can not pass data from Recyclerview to another activity

program crashed. and I get this message:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mob3000.group11.Cars.getImgurl()' on a null object reference
at com.mob3000.group11.Reservation.onCreate(Reservation.java:57)
I want to pass info to another activity
#Reservation class
public class Reservation extends AppCompatActivity {
ImageView imgMakeRes;
TextView pricMakeRes;
TextView brandMakeRes;
TextView girMakeRes;
TextView seatMakeRes;
public static final String BOOKING_INFORMATION= "booking_information";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
imgMakeRes = (ImageView) findViewById(R.id.imgMakeReservation);
pricMakeRes = (TextView) findViewById(R.id.pricMakereservation);
brandMakeRes = (TextView) findViewById(R.id.brandMakeReservation);
girMakeRes = (TextView) findViewById(R.id.girMakeReservation);
seatMakeRes = (TextView) findViewById(R.id.seatMakeReservation);
Cars cars = getIntent().getParcelableExtra(BOOKING_INFORMATION);
Glide.with(this).load(cars.getImgurl()).into(imgMakeRes);
pricMakeRes.setText((int) cars.getPrice());
brandMakeRes.setText(cars.getBrand());
girMakeRes.setText(cars.getGir());
seatMakeRes.setText(cars.getSeats());
Adapter class
public class FirestoreAdapter extends FirestoreRecyclerAdapter<Cars,FirestoreAdapter.myViewHolder> {
private OnListItemClick onListItemClick;
private Context context;
private ArrayList<Cars> listCars;
public FirestoreAdapter(#NonNull FirestoreRecyclerOptions<Cars> options,OnListItemClick onListItemClick) {
super(options);
this.onListItemClick=onListItemClick;
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull Cars cars) {
holder.textpri_ce.setText(cars.getPriceWithLabel());
holder.textbra_nd.setText(cars.getBrand());
holder.textg_ir.setText(cars.getGir());
holder.textsea_ts.setText(cars.getSeatsWithLabel());
Glide.with(holder.img.getContext()).load(cars.getImgurl()).into(holder.img);
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.car_items,
parent, false);
return new myViewHolder(view);
}
public class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
CircleImageView img;
TextView textpri_ce,textbra_nd,textg_ir,textsea_ts;
public myViewHolder( View itemView) {
super(itemView);
img = (CircleImageView) itemView.findViewById(R.id.img1);
textpri_ce= (TextView) itemView.findViewById(R.id.textprice);
textbra_nd= (TextView)itemView.findViewById(R.id.textbrand);
textg_ir= (TextView)itemView.findViewById(R.id.textgir);
textsea_ts= (TextView)itemView.findViewById(R.id.textseats);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onListItemClick.onItemClick(getItem(getAdapterPosition()),getAdapterPosition());
}
}
public interface OnListItemClick{
void onItemClick(Cars snapshot, int position);
}
}
Booking class
public class booking_activity extends AppCompatActivity implements FirestoreAdapter.OnListItemClick{
FirebaseFirestore firebaseFirestore;
RecyclerView mFirestoreList;
private ArrayList<Cars> listCars;
Context context;
FirestoreAdapter adapter;
private static final String TAG = "booking_activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
// calling function adapetWithRecycle() which contains adapter and recycleview----
adapetWithRecycle();
//--------------------------------------------------------------------------
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// here we call functions for all the spinners to Find Id and set adapters.
priceSpinner();
brandSpinner();
girSpinner();
seatsSpinner();
}
// onStop and onStart for recycle view
#Override public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
protected void adapetWithRecycle() {
firebaseFirestore = FirebaseFirestore.getInstance();
mFirestoreList = findViewById(R.id.recview);
Query query = firebaseFirestore.collection("cars");
FirestoreRecyclerOptions<Cars> options = new FirestoreRecyclerOptions.Builder<Cars>()
.setQuery(query, Cars.class)
.build();
adapter = new FirestoreAdapter(options,this);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
}
#Override
public void onItemClick(Cars snapshot, int position) {
Intent intent = new Intent(booking_activity.this, Reservation.class);
// intent.putExtra(Reservation.BOOKING_INFORMATION, listCars.get(position));
//intent.putExtra(Reservation.BOOKING_INFORMATION, listCars);
startActivity(intent);
Log.d("ITEM_CLICK","clicked the item: " + position+ " Gear is : " + snapshot.getGir()+
" Price is: "+ snapshot.getPrice()+" , Brand is "+ snapshot.getBrand()+" ,Seats: "+
snapshot.getSeats());
inside your onBindViewHolder() in setText() add listcars.get(position).getPriceWithLable() apply it to the rest of your TextViews
ex. holder.textpri_ce.setText(listcars.get(position).getPriceWithLable());

Im trying to make an app that searches files from Firebase and I am getting this error

The Error
'FirebaseRecyclerAdapter(com.firebase.ui.database.FirebaseRecyclerOptions<com.munopa.revise.Files>)'
in 'com.firebase.ui.database.FirebaseRecyclerAdapter' cannot be
applied to '(java.lang.Class<com.munopa.revise.Files>, int,
java.lang.Class<com.munopa.revise.MainActivity.FilesViewHolder>,
com.google.firebase.database.DatabaseReference)'
My Main Activity
public class MainActivity extends AppCompatActivity {
private EditText mSearchField;
private RecyclerView mFileList;
private FloatingActionButton mSearchButton;
private DatabaseReference mFilesDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFilesDatabase = FirebaseDatabase.getInstance().getReference().child("Files");
mSearchField = findViewById(R.id.search_bar_input);
mFileList = findViewById(R.id.file_list);
mSearchButton = findViewById(R.id.btn_search);
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseFileSearch();
}
});
}
private void firebaseFileSearch() {
FirebaseRecyclerAdapter<Files, FilesViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Files, FilesViewHolder>(
Files.class,
R.layout.paper_card,
FilesViewHolder.class,
mFilesDatabase
) {
#Override
protected void onBindViewHolder(#NonNull FilesViewHolder holder, int position, #NonNull Files model) {
}
#NonNull
#Override
public FilesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
};
}
public class FilesViewHolder extends RecyclerView.ViewHolder{
View mView;
public FilesViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
}
}
This is your problem (and where you are getting the error):
FirebaseRecyclerAdapter<Files, FilesViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Files, FilesViewHolder>(
Files.class,
R.layout.paper_card,
FilesViewHolder.class,
mFilesDatabase
)
You are calling the constructor of FirebaseRecyclerAdapter with 4 parameters, but it only expects 1 parameter of type FirebaseRecyclerOptions<Files>.
Refer to https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md for more details about how to set this up.

Convert ListView to RecyclerView

i have a list view in my app.
I want to change it to an recycler view, but even with different tutorials i dont get it.
I was using this: https://www.spreys.com/listview-to-recyclerview/
I failed with the "getView" part here.
Here is my code of the ListActivity and LeagueArrayAdapter.
Thanks for your help.
ListActivity:
public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayAdapter adapter;
private final int REQUEST_CODE_EDIT = 1;
private static LeagueDAO leagueDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
if (allLeagues1.size() == 0) {
leagueDAO.insert(new League("HVM Landesliga 19/20","https://hvmittelrhein-handball.liga.nu/cgi-bin/WebObjects/nuLigaHBDE.woa/wa/groupPage?championship=MR+19%2F20&group=247189"));
allLeagues1 = leagueDAO.getLeagues();
}
adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
ListView lv = findViewById(R.id.league_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
registerForContextMenu(lv);
Button btn_league_add = findViewById(R.id.btn_league_add);
btn_league_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this, EditActivity.class);
startActivity(intent);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu contMenu, View v,
ContextMenu.ContextMenuInfo contextmenuInfo) {
super.onCreateContextMenu(contMenu, v, contextmenuInfo);
getMenuInflater().inflate(R.menu.team_list_context_menu, contMenu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo acmi=
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
League league = (League)adapter.getItem(acmi.position);
switch (item.getItemId()) {
case R.id.evliconit_edit:
editEntry(league, acmi.position);
return true;
case R.id.evliconit_del:
leagueDAO.delete(league);
adapter.remove(league);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
League team = (League)adapter.getItem(position);
editEntry(team, position);
}
private void editEntry(League league, int position) {
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("team", league);
intent.putExtra("position", position);
startActivityForResult(intent, REQUEST_CODE_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CODE_EDIT && resultCode == RESULT_OK && intent != null) {
Bundle extras = intent.getExtras();
int position = extras.getInt("position");
League league = (League) adapter.getItem(position);
league.setLeague_name(extras.getString("league_name"));
league.setLeague_url(extras.getString("league_url"));
adapter.notifyDataSetChanged();
}
}
#Override
protected void onRestart() {
super.onRestart();
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
ListView lv = findViewById(R.id.league_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
registerForContextMenu(lv);
}
LeagueArrayAdapter:
public class LeagueArrayAdapter extends ArrayAdapter<League> {
private List<League> leagues;
private Context context;
private int layout;
public LeagueArrayAdapter(Context context, int layout, List<League> leagues) {
super(context, layout, leagues);
this.context = context;
this.layout = layout;
this.leagues = leagues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
League league = leagues.get(position);
if (convertView == null)
convertView = LayoutInflater.from(context).inflate(layout, null);
TextView tv_name = convertView.findViewById(R.id.tv_name);
TextView tv_url = convertView.findViewById(R.id.tv_url);
tv_name.setText(league.getLeague_name());
tv_url.setText(league.getLeague_url());
return convertView;
}
}
Update: app crashed when opened the activity
public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayAdapter adapter;
private final int REQUEST_CODE_EDIT = 1;
private static LeagueDAO leagueDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
if (allLeagues1.size() == 0) {
leagueDAO.insert(new League("HVM Landesliga 19/20","https://hvmittelrhein-handball.liga.nu/cgi-bin/WebObjects/nuLigaHBDE.woa/wa/groupPage?championship=MR+19%2F20&group=247189"));
allLeagues1 = leagueDAO.getLeagues();
}
// adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
RecyclerView lv = findViewById(R.id.league_list);
lv.setHasFixedSize(true);
lv.setLayoutManager(new LinearLayoutManager(this));
lv.setAdapter(new LeagueArrayAdapter(allLeagues1));
// lv.setOnItemClickListener(this);
registerForContextMenu(lv);
Button btn_league_add = findViewById(R.id.btn_league_add);
btn_league_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this, EditActivity.class);
startActivity(intent);
}
});
}
I reconstructed your ListView Adapter using RecyclerView.Adapter.
onCreateView is called for every visible container on your screen. If your screen can show 10 rows of data RecyclerView makes 11 - 12 containers (ViewHolder)
onBindView updates those containers with new data when you scroll.
MyViewHolder is the object that holds data about every row of data (container)
static class and bind() function inside to avoid any memory leak in your adapter.
We have access to Context in RecyclerView.Adapter using itemView and parent
itemView is the inflated View for each container (ViewHolder).
Initialize your Views inside ViewHolder's constructor so they get assigned once.
public class LeagueArrayAdapter extends RecyclerView.Adapter<LeagueArrayAdapter.MyViewHolder> {
private ArrayList<League> leagues;
public LeagueArrayAdapter(ArrayList<League> leagues) {
this.leagues = leagues;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return LayoutInflater.from(parent.getContext()).inflate(R.layout.row_league, parent, false);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.bind(leagues.get(position));
}
#Override
public int getItemCount() {
return 0;
}
static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_name;
TextView tv_url;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = itemView.findViewById(R.id.tv_name);
tv_url = itemView.findViewById(R.id.tv_url);
}
void bind(League league) {
tv_name.setText(league.getLeague_name());
tv_url.setText(league.getLeague_url());
}
}
}
Your Activity:
LinearLayoutManager for a linear layout
GridLayoutManager for a grid layout
setHasFixedSize() enhances your RecyclerView's speed if you are sure the RecyclerView itself won't change width or height.
public class LeagueActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_ACTIVITY_LAYOUT_ID);
...
RecyclerView recyclerView = findViewById(R.id.YOUR_RECYCLER_VIEW_ID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new LeagueArrayAdapter(SEND_YOUR_ARRAY_OF_LEAGUE));
}
}
I suggest checking the Groupie Lbrary, it works with recyclerView and it makes life much easier for you, here is an example of how you can use it (I'm writing the code in kotlin but it shouldn't be that different from java)
first, add those lines to your Build.gradle (app) file
implementation 'com.xwray:groupie:2.3.0'
implementation 'com.xwray:groupie-kotlin-android-extensions:2.3.0'
then inside your activity create an adapter then set the adapter to your recyclerView
val myAdapter = GroupAdapter<ViewHolder>()
recyclerView.adapter = myAdapter
and just like this you set the adapter to your recyclerView, but you have to create "Items" to put inside the recyclerView. you can create an Item like so
class MyItem: Item() {
override fun getLayout() = R.layout.layout_seen
override fun bind(viewHolder: ViewHolder, position: Int){
}
}
in the getLayout method, you return the layout that you to display inside the recyclerView,
you can use the bind method to do any kind of modifications we want to apply to our layout that we are displaying.
lastly, we can add our items to the adapter this way
myAdapter.add(MyItem())
myAdapter.notifyDataSetChanged()
for more details check the library, in here I just explained how you can simply add an item to your RecyclerView

add next, prev buttons in slider image made by picasso and viewpager

I've made a image slider with help of viewpager and picasso, now i want to add next, prev button on the image, how can i do that?
I saw different answers of this but all of them are showing error
This is main activity where image slider is shown:
public class MainActivity extends AppCompatActivity {
private int[] imageUrls = new int[]{
R.drawable.after_cookie,
R.drawable.before_cookie
};
private WebBackForwardList viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.view_pager);
ViewPageAdapter adapter = new ViewPageAdapter(this, imageUrls);
viewPager.setAdapter(adapter);
}
}
This is ViewPageAdapter:
public class ViewPageAdapter extends PagerAdapter {
private Context context;
private int[] imageUrls;
ViewPageAdapter(Context context, int[] imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
}
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
Picasso.get()
.load(imageUrls[position])
.fit()
.centerCrop()
.into(imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
add this method to your code
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
then use this for next button
Button NextButton = (Button)findViewById(R.id.button1);
yourButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(getItem(+1), true); //getItem(+1) for next
}
});
and use this for the previous button
Button PreviousButton = (Button)findViewById(R.id.button2);
PreviousButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(getItem(-1), true); //getItem(-1) for previous
}
});
it will work fine ;)

Categories

Resources