I'm currently working on a mobile app as a final project for my course. I have these two fragments inside a ViewPager2 controlled by a TabLayout. There are buttons inside of these fragments.
The first frag contains 2 buttons. The other frag has only one button. I want them to open an activity but the problem is when I run the app, these buttons won't work. They didn't open the other activity.
Login Fragment
package com.example.biowit;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
public class LoginTabFragment extends Fragment {
EditText email, password;
Button btn_login, btn_forpass;
TextView textView;
float v=0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_fragment, container, false);
email = root.findViewById(R.id.input_LI_email);
password = root.findViewById(R.id.input_LI_pass);
btn_forpass = root.findViewById(R.id.btn_FPass);
btn_login = root.findViewById(R.id.btn_LIn);
email.setTranslationX(800);
password.setTranslationX(800);
btn_forpass.setTranslationX(800);
btn_login.setTranslationX(800);
email.setAlpha(v);
password.setAlpha(v);
btn_forpass.setAlpha(v);
btn_login.setAlpha(v);
email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
password.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_forpass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeScreen.class);
startActivity(intent);
Animatoo.animateFade(getActivity());
getActivity().finish();
}
});
return root;
}
}
LoginScreen (where the fragment locates)
package com.example.biowit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class
LoginScreen extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager;
float v=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
LoginAdapter login_adapter = new LoginAdapter(this);
viewPager.setAdapter(login_adapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0:
tab.setText("LOGIN");
break;
case 1:
tab.setText("SIGNUP");
break;
}
}
}).attach();
tabLayout.setAlpha(v);
}
}
Here's the error log(?)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.biowit, PID: 18551
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.biowit/com.example.biowit.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.biowit.HomeScreen.onCreate(HomeScreen.java:22)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
HomeScreen (Activity that supposedly open when clicking the button)
package com.example.biowit;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class HomeScreen extends AppCompatActivity {
Button Chap1_btn, Achieve_btn, HowToPlay_btn, LogOut_btn, Settings_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide(); // hides the action bar.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Chap1_btn = findViewById(R.id.btn_Chap1);
Achieve_btn = findViewById(R.id.btn_Achievements);
HowToPlay_btn = findViewById(R.id.btn_HowToPlay);
LogOut_btn = findViewById(R.id.btn_Logout);
Settings_btn = findViewById(R.id.btn_Settings);
Chap1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Chap1 = new Intent(getApplicationContext(), LessonScreen.class);
startActivity(open_Chap1);
}
});
Achieve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_Achievements = new Intent(getApplicationContext(), Achievements.class);
}
});
HowToPlay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_HowToPlay = new Intent(getApplicationContext().HowToPlay.class);
}
});
LogOut_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Settings = new Intent(getApplicationContext(), Settings.class);
startActivity(open_Settings);
}
});
}
}
getSupportActionBar().hide(); is what's causing the error. You have added it before
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
So it's trying to execute it before the activity is initialised.
Add it after the above 2 lines and it should work.
Related
I want to save some data from the dialog to use it in my app, but after enetering the data and going to the next step my app is crushing instantly (after pressing on Create).So i'm practicing with a textView(fragment layout). What should i do, bcs i didn't manage even with an method or class .Actually my purpose is to print in the text ,the input without crashing.
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class Passwords_Fragment extends Fragment {
FloatingActionButton floating_button;
AlertDialog dialog;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_passwords_, container, false);
floating_button=view.findViewById(R.id.floatingActionButton);
buildDialog();
floating_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.show();
}
});
return view;
}
private void buildDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
View view = getLayoutInflater().inflate(R.layout.dialog,null);
EditText name_of_platform=view.findViewById(R.id.platform_name);
EditText name_of_password=view.findViewById(R.id.password_name);
builder.setView(view)
.setTitle("Save a new password")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
addItem(name_of_platform.getText().toString()); // my app crashes here
}
});
dialog=builder.create();
}
private void addItem(String name){
View view = getLayoutInflater().inflate((R.layout.item),null);
TextView text= view.findViewById(R.id.textView2);
text.setText(name);
}
}```
My error at Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.passowrdgenerator.Passwords_Fragment.buildDialog(Passwords_Fragment.java:65)
at com.example.passowrdgenerator.Passwords_Fragment.onCreateView(Passwords_Fragment.java:32)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1808)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
package com.example.gymmanagment;
import static com.example.gymmanagment.Trainignactivity2.Training_key;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
public class plandetailsdialogue extends DialogFragment {
private Button buttondismiss,butoonadd;
private TextView txtname;
private EditText edittextmintues;
private Spinner spinnerdayy;
public interface passplaninteface{
void getplan(plan plan);
}
private passplaninteface passplaninteface;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
View
view=getActivity().getLayoutInflater().inflate(R.layout.dialoguedetails,null);
intiviews(view);
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle("enter details");
Bundle bundle=getArguments();
if(null !=bundle){ Training training=bundle.getParcelable(Training_key);
if(null!=training){
txtname.setText(training.getName());
buttondismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
butoonadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String day=spinnerdayy.getSelectedItem().toString();
int
minitues=Integer.valueOf(edittextmintues.getText().toString());
plan plan=new plan(training,minitues,day,false);
try {
passplaninteface=(passplaninteface) getActivity();
passplaninteface.getplan(plan);
dismiss();
}catch (ClassCastException e){
e.printStackTrace();
dismiss();
}}
});
}
}
return builder.create();
}
private void intiviews(View view){
buttondismiss= view.findViewById(R.id.buttondissmiss);
butoonadd= view.findViewById(R.id.onlyadd);
txtname= view.findViewById(R.id.txtname234);
edittextmintues= view.findViewById(R.id.edttxtminutes);
spinnerdayy= view.findViewById(R.id.spinnerdays);
}
}
The error is below:
022-01-29 13:20:54.963 8688-8688/com.example.gymmanagment E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.gymmanagment, PID: 8688
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.valueOf(Integer.java:801)
at
com.example.gymmanagment.plandetailsdialogue$2.onClick(plandetailsdialogue.java:52)
at android.view.View.performClick(View.java:7448)
at
com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1131)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Your EditText is probabbly empty. The error shows that input string is: "". You can't assign a value of nothing to an Integer. You should check if EditText isn't empty before casting it to an Integer.
Try something like this:
if(!edittextminutes.getText().toString.isEmpty())
{
//cast to Integer
}
I'm currently creating my own application with Android Studio. In this app, I want to create a switch, that changes to dark mode and back.
In the MainActivity.java I'm using the following code
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
public class MainActivity extends AppCompatActivity {
private Button button;
private Switch aSwitch;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button feed = findViewById(R.id.feed);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
aSwitch = findViewById(R.id.day_night);
checkNightModeActivated();
aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(true);
recreate();
}
});
feed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Newsfeed.class));
}
});
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
private void checkNightModeActivated() {
if(sharedpreferences.getBoolean(KEY_ISNIGHTMODE, false)) {
aSwitch.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else{
aSwitch.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
The problem is, that the switch will change the mode to dark when I've started the app. But then, the app beginns to flicker and does not longer responds.
Can soneone please tell me, what I'm doing wrong?
Kind regards
Kai
I've found a solution for my problem.
private Switch day_night;
day_night=findViewById(R.id.day_night);
day_night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
});
How to put more than one class,overview,void in MainActivity java of Android Studio? I need to have both the button and a code to make the map of google have some restricions in the same page. What names of the classes should be changed for it to work. The codes work when put independently but not together.How to make them work good together?
package com.example.maps;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
public class FirstFragment extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFoodFragment();
}
});
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
}
public class MainACTIVITY extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mapAPI;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment =(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.mapAPI);
mapFragment.getMapAsync(this);
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
#Override
public void onMapReady(GoogleMap googleMap){
mapAPI = googleMap ;
LatLng one = new LatLng(-21.754812, -48.219451);
LatLng two = new LatLng(-21.787443, -48.113332);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//add them to builder
builder.include(one);
builder.include(two);
LatLngBounds bounds = builder.build();
//get width and height to current display screen
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20);
mapAPI.setLatLngBoundsForCameraTarget(bounds);
mapAPI.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mapAPI.setMinZoomPreference(mapAPI.getCameraPosition().zoom);
LatLng Kampai = new LatLng(-21.780985, -48.186859);
mapAPI.addMarker(new MarkerOptions().position(Kampai).title("Kampai"));
mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Kampai));
}
}
Yes the can be in the same file but you have your mainACTIVITY inside your FirstFragment which cannot happen you need to remove the bottom most bracket and place it right above the start of your mainACTIVITY class, your FirstFragment's brackets need to close before you paste another class into the file.
adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );This Line Generates Error & my knowlwdge is quite low about this error. the both required java file & the detailed error is given after this two java files.
ImageAdapter.java
package com.example.login;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context Context;
private List<Upload> Uploads;
private OnItemClickListener Listener;
public ImageAdapter (Context context, List<Upload> uploads1){
Context = context;
Uploads = uploads1;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent,int viewType) {
View v= LayoutInflater.from(Context).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder,int position) {
Upload uploadCurrent= Uploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(Context)
.load(uploadCurrent.getImageUrl())
.placeholder(R.drawable.logo)
.fit()
.centerInside()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return Uploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_product_name);
imageView = itemView.findViewById(R.id.product_image);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Listener.OnItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem details = menu.add(Menu.NONE ,1,1,"Details");
MenuItem delete = menu.add(Menu.NONE ,2,2,"Delete");
details.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch(item.getItemId()){
case 1:
Listener.OnDetailsClick(position);
return true;
case 2:
Listener.OnDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener{
void OnItemClick(int Position);
void OnDetailsClick(int Position);
void OnDeleteClick(int Position);
}
public void SetOnClickItemListener(OnItemClickListener listener){
Listener = listener;
}
}
MyAddsFragment.java
package com.example.login.ui.login;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.login.ImageAdapter;
import com.example.login.R;
import com.example.login.Upload;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyAddsFragment extends Fragment implements ImageAdapter.OnItemClickListener{
private RecyclerView recyclerView;
private ImageAdapter adapter;
private ProgressBar progressBar;
private DatabaseReference databaseRef;
private List<Upload> Uploads;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_myadds, container, false);
recyclerView = v.findViewById(R.id.Recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressBar = v.findViewById(R.id.progress_bar_1);
Uploads = new ArrayList<>();
databaseRef = FirebaseDatabase.getInstance().getReference("uploads");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot){
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Upload upload = postSnapshot.getValue(Upload.class);
Uploads.add(upload);
}
adapter = new ImageAdapter(getActivity(), Uploads);
recyclerView.setAdapter(adapter);
adapter.SetOnClickItemListener((ImageAdapter.OnItemClickListener) getActivity());
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
return v;
}
#Override
public void OnItemClick(int Position) {
Toast.makeText(getActivity(),"Normal Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDetailsClick(int Position) {
Toast.makeText(getActivity(),"Details Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDeleteClick(int Position) {
Toast.makeText(getActivity(),"Delete Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
}
Error is Given below
01-24 12:33:27.072 6252-6252/com.example.login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6252
java.lang.ClassCastException: com.example.login.HomeActivity cannot be cast to com.example.login.ImageAdapter$OnItemClickListener
at com.example.login.ui.login.MyAddsFragment$1.onDataChange(MyAddsFragment.java:57)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.0:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
....................................................................................................
your class MyAddsFragment is implementing the ImageAdapter.OnItemClickListener so to set adapter.SetOnClickItemListener you can simple use below code -
adapter.SetOnClickItemListener(MyAddsFragment.this)
You can not cast ImageAdapter.OnItemClickListener to HomeActicity.class as it might not implementing it.