creating pop up window - java

I'm creating a pop-up window on button click. But, I'm getting error on getSupportFragmentManager();
public class PrizeList extends AppCompatDialogFragment {
TextView players, prizePoolList, perKill, rank1, rank2, rank3;
SeekBar seekBar;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.prize_list_layout, null);
builder.setView(view).setTitle("Prize List")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
players = view.findViewById(R.id.players);
prizePoolList = view.findViewById(R.id.prizePoolList);
perKill = view.findViewById(R.id.perKill);
rank1 = view.findViewById(R.id.rank1);
rank2 = view.findViewById(R.id.rank2);
rank3 = view.findViewById(R.id.rank3);
seekBar = view.findViewById(R.id.seekBar);
return builder.create();
}
}
Adapter
holder.prizeList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
Toast.makeText(v.getContext(), "prize list clicked", Toast.LENGTH_SHORT).show();
}
});
}
private void openDialog() {
PrizeList prizeList = new PrizeList();
prizeList.show(prizeList.requireActivity().getSupportFragmentManager(), "Prize");
}
The error I'm getting,
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.luteraa.luteraaesports, PID: 6355
java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.fragment.app.FragmentManager androidx.fragment.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
at com.luteraa.luteraaesports.BGMICategoryAdapter.openDialog(BGMICategoryAdapter.java:93)
at com.luteraa.luteraaesports.BGMICategoryAdapter.access$000(BGMICategoryAdapter.java:25)
at com.luteraa.luteraaesports.BGMICategoryAdapter$1.onClick(BGMICategoryAdapter.java:76)
at android.view.View.performClick(View.java:7191)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7164)
at android.view.View.access$3500(View.java:821)
at android.view.View$PerformClick.run(View.java:27856)
at android.os.Handler.handleCallback(Handler.java:914)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)

DataAdapter adapter = new DataAdapter(MainActivity.this,tasks,getSupportFragmentManager());
you can pass the parameter getSupportFragmentManager in
adapter
calling
and get the constructor in getSupportFragmentManager like this
DataAdapter(Context context, List<Task> tasklist,
FragmentManager
supportFragmentManager) {
this.context = context;
this.taskList = tasklist;
this.supportFragmentManager=supportFragmentManager;
}
After pass the object supportFragmentManager in the prizeList
show
method
PrizeList prizeList = new PrizeList();
prizeList.show(supportFragmentManager, "Prize List");
also work in my project so this help to solve your error in
supportFragmentManager

Related

Android: Always receiving null object in extras passed in the intent

I am creating a recycler view in my app and fetching data from firestore for the same. In the process, I am passing some arguments to the intent which is called when an item in the recycler view is clicked.
RecyclerView recyclerView = findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new LearningModuleAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
LearningModule learningModule = documentSnapshot.toObject(LearningModule.class);
String id=documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
String title = (String) documentSnapshot.get("title");
System.out.println("what did i get from document snapshot? id: "+id+" path:"+path+" title:"+title);
Intent intent = new Intent(learn.this,learn_content.class);
intent.putExtra("title",title);
startActivity(intent);
}
});
The output from the print statements in above code is as follows :
what did i get from document snapshot? id: EsHW9FGjVe8A3pG4 path:LearningModules/EsHW9FGjVe8A3pG4 title:Front Load vs Top Load
The onClick method of the called activity looks like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_learn_view_pager);
viewPager = findViewById(R.id.pager);
progressBar = findViewById(R.id.progressBarViewPager);
Bundle extras;
extras = getIntent().getExtras();
System.out.println("captured form the first " + extras.getString("title"));
However, this piece of code throws an error NullPointerException for the print statement.
Where am I going wrong ?
Additional code:
Adapter
public class LearningModuleAdapter extends FirestoreRecyclerAdapter<LearningModule, LearningModuleAdapter.LearningModuleViewHolder> {
private OnItemClickListener listener;
public LearningModuleAdapter(#NonNull FirestoreRecyclerOptions<LearningModule> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull final LearningModuleViewHolder holder, final int position, #NonNull LearningModule model) {
holder.title.setText(model.getTitle());
// holder.img.setImageResource(model.getImg());
}
#NonNull
#Override
public LearningModuleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new LearningModuleViewHolder(v);
}
public class LearningModuleViewHolder extends RecyclerView.ViewHolder {
public View view;
public TextView title;
public ImageView img;
public LearningModuleViewHolder(View v) {
super(v);
view = v;
img = itemView.findViewById(R.id.list_image);
title = itemView.findViewById(R.id.list_text_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
Intent intent = new Intent(view.getContext(), learn_content.class);
view.getContext().startActivity(intent);
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot,int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
}
Error Stacktrace
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gigforce.app/com.gigforce.app.learn_content}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.gigforce.app.learn_content.onCreate(learn_content.java:45)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
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:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356)
You are calling startActivity twice that cause the problem.
Option - 1: Try removing inside itemView.setOnClickListener like below :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
//Intent intent = new Intent(view.getContext(), learn_content.class);
//view.getContext().startActivity(intent);
}
});
Option - 2: Try to start activity inside itemView.setOnClickListener and remove OnItemClickListener related code like below :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
/*if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}*/
Intent intent = new Intent(view.getContext(), learn_content.class);
DocumentSnapshot documentSnapshot = getSnapshots().getSnapshot(position);
String title = (String) documentSnapshot.get("title");
intent.putExtra("title",title);
view.getContext().startActivity(intent);
}
});
Try this out :
Intent i = getIntent()
if (i == null)
Log.d("***DEBUG****", "Intent was null");
else
Log.d("**** DEBUG ***", "Intent OK");
String title= i.getStringExtra("title"); //Exception points to this line
Log.d("*** DEBUG", rec + " " + title);
Also from itemview click you are not passing title see below
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
Intent intent = new Intent(view.getContext(),
learn_content.class);
intent.putExtra("title",title); //This one
view.getContext().startActivity(intent);
}
});
My alternative solution: Instead of putting click listener on LearningModuleViewHolder class put in onCreateViewHolder, so now view will not be null.i will try to add a code here :
#NonNull
#Override
public LearningModuleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
LearningModuleViewHolder holder = new LearningModuleViewHolder(v);
v.setOnClickListener(v -> {
System.out.println("The click was captured");
Intent intent = new Intent(parent.getContext(), learn_content.class);
parent.getContext().startActivity(intent);
});
return holder;
}

Dynamically add Views in Dialog

I am trying to make Dialog that will consist 2x EditText and 1x Buttons. By clicking additional button you can add another 2x EditText and 1x Buttons. This 1x Button provide deleting this added pair. When i try to use button that should add another Views it's working properly. But button for deleting the View is working only for the first pairs. How can i do this with android:onClick, because i was trying buy it crashed.
Here is my code of Dialog class:
public class ExampleDialog extends AppCompatDialogFragment {
private EditText editTextUsername;
private EditText editTextPassword;
private ExampleDialogListener listener;
private LinearLayout parentLinearLayout;
private Context mContext;
Button dodaj,usun;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_template, null);
builder.setView(view)
.setTitle("Login")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
listener.applyTexts(username, password);
}
});
editTextUsername = view.findViewById(R.id.edit_username);
editTextPassword = view.findViewById(R.id.edit_password);
parentLinearLayout = (LinearLayout) view.findViewById(R.id.parent_linear_layout);
dodaj = view.findViewById(R.id.add_field_button);
usun = view.findViewById(R.id.delete_button);
dodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
}
});
usun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
parentLinearLayout.removeView((View) v.getParent());
usun = v.findViewById(R.id.delete_button);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
public void contexta(Context context)
{
this.mContext = context;
}
public interface ExampleDialogListener {
void applyTexts(String username, String password);
}
}
And there is the conception of Dialog box on the picture below:
Picture
This issue may be due to view reference. Check whether v.getParent() is the view you want to delete or not.
For testing you can use "removeViewAt(int index)" method. Pass an index and check whether view is deleted at index or not.

SetText from a Class to the main XML file

I'm trying to use the .setText within a java class to try to change the value of a TextView on the activity_main XML file, so far i'm getting the NullpointerExeption error and I've read that its due an error when declaring my variable. How can i achieve this? Do i need to declare it first at the mainActivity.java?
On my activity_main.xml i have a button -> it opens a custom listView -> if you press the 2 item on the list view -> it opens a custom alert dialog -> the custom alert dialog it contains 2 buttons -> if you press the second button -> it has to set the text of a TextView that is on activity_main.xml
Any help is appreciated!
MainActivity.java
final TextView KMLabel = (TextView)findViewById(R.id.KMlabel);
activity.main.xml
<TextView
android:id="#+id/KMlabel"
android:layout_alignBottom="#+id/TVKm"
android:layout_toRightOf="#+id/TVKm"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#e6c009"
android:text="KM/H"
android:textStyle="italic"/>
custom.java
public class custom extends BaseAdapter{
Context context;
String Item[];
String SubItem[];
int flags[];
LayoutInflater inflter;
public custom(Context applicationContext, String[] Item, String[] SubItem , int[] flags) {
this.context = context;
this.Item = Item;
this.SubItem = SubItem;
this.flags = flags;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return Item.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_items, null);
//TextView Prueba = (TextView)view.findViewById(R.id.KMlabel);
TextView item = (TextView) view.findViewById(R.id.item);
TextView subitem = (TextView) view.findViewById(R.id.subitem);
ImageView image = (ImageView) view.findViewById(R.id.image);
item.setText(Item[i]);
subitem.setText(SubItem[i]);
image.setImageResource(flags[i]);
return view;
}
viewdialog.java
public class ViewDialog {
public void showDialog(Activity activity, String msg){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
//I'm declaring it like this
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//and calling it this way:
KMLabel.setText("MLL/H");
}
});
dialog.show();
}
}
LOGCAT:
FATAL EXCEPTION: main
Process: com.example.dell.getspeed, PID: 3925
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.dell.getspeed.ViewDialog$2.onClick(ViewDialog.java:38)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10936)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
You have to move your code
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//and calling it this way:
KMLabel.setText("MLL/H");
}
});
final TextView KMLabel = (TextView)dialog.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
below the dialog.show() code because code findViewById only work after you pop up dialog.
Create a Global class which extends to application class, then create a texview in Global
Textview t = null;
Then create two static methods to set and get this textview
Public static void setT(TextView p){
t = p;
}
And get it from
Public static TextView getT(){
return t;
}
Set TextView in your activity ,then access this textview from wherever you want until your activity is alive.
Try the code below:
MainActivity class:-------
public class MainActivity extends AppCompatActivity {
private TextView KMlabel;
private Button b;
private ViewDialog vd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo2);
vd = new ViewDialog();
KMlabel = (TextView) findViewById(R.id.KMlabel);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vd.showDialog(MainActivity.this , KMlabel , "Your Message" , "Your Text");
}
});
}
}
ViewDialog class:------
public class ViewDialog {
public void showDialog(Context context, final TextView v , String msg , final String text) {
createYesNoInfoDialog(context, msg, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
v.setText(text);
}
}).show();
}
private AlertDialog createYesNoInfoDialog(Context finalContext, String message,
DialogInterface.OnClickListener onNoListener, DialogInterface.OnClickListener onYesListener) {
AlertDialog a = new AlertDialog.Builder(finalContext).setTitle(
message)
.setNegativeButton("No", onNoListener)
.setPositiveButton("Yes", onYesListener).create();
return a;
}
}
demo2.xml:-----
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="xcxc"
android:id="#+id/KMlabel"/>
<Button
android:layout_width="match_parent"
android:text="Create Dialog"
android:layout_height="wrap_content"
android:id="#+id/b"/>
</LinearLayout>
R.id.KMlabel is on activity_main.xml so you have to initialize the TextView from MainActivity reference.
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Edit:
You can use callback pattern for this:
ViewDialog:
public class ViewDialog {
// interface for callback
public interface OnSelectListener {
public void onOkSelect();
}
OnSelectListener mOnSelectListener;
public void showDialog(Activity activity, String msg, OnSelectListener mListener){
mOnSelectListener = mListener;
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
//I'm declaring it like this
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//pass to the implementation if not null
if( mOnSelectListener != null){
mOnSelectListener.onOkSelect();
}
}
});
dialog.show();
}
}
In MainActivity:
// initialize interface
ViewDialog.OnSelectListener mOnSelectListener = new ViewDialog.OnSelectListener(){
public void onOkSelect(){
KMLabel.setText("MLL/H");
}
};
ViewDialog viewDialog = new ViewDialog();
viewDialog.showDialog(this, "Message", mOnSelectListener);
This happens since you are trying to call the TextView within the custom alert dialog. TextView only belongs to the MainActivity. You can call or change that only within the MainActivity class. So please try this below.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private TextView KMlabel;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
KMlabel = (TextView) findViewById(R.id.KMlabel);
}
public void setTextKM(String string){
KMlabel.setText(string);
}
}
ViewDialog class
public class ViewDialog {
public void showDialog(Activity activity, String msg){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity mainActivity = new MainActivity();
mainActivity.setTextKM("MLL/H");
}
});
dialog.show();
}
}

Why I change to fragment, the application is crashed

My page is activity page and now i would like to change to fragment but it crashed,
Caused by: java.lang.ClassCastException: com.mac.Activity cannot be cast to android.app.Activity
I dont know which part of code is crashed. So I put my code in below.
Code:
public class Activity extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.activity, container, false);
final TextView nameTxt = (TextView) view.findViewById(R.id.nameTxtDetail);
final TextView descTxt = (TextView) view.findViewById(R.id.descDetailTxt);
final Button btn = (Button) view.findViewById(R.id.btn);
//RECEIVE
Intent i = getActivity().getIntent();
String name = i.getExtras().getString("NAME_KEY");
String desc = i.getExtras().getString("DESCRIPTION_KEY");
//BIND
nameTxt.setText(name);
descTxt.setText(desc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getContext());
alertDialogBuilder.setTitle("Do you want to login?");
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setNeutralButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(getActivity(), FacebookLogin.class);
startActivity(i);
}
})
.setPositiveButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
TextView toolbar_title = (TextView) getActivity().findViewById(R.id.toolbar_title);
toolbar_title.setText("DETAIL");
}
#Override
public void onStop() {
super.onStop();
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(false);
}
}
First I though crashed because forget put final for textview and button but i already put now, still crashed. I am using android studio. Hope somebody help thanks.
There are a lot of factors here that could cause this. But firstly did you remove it from Android Manifest, because fragments are not shown in Android Manifest, and if you didn't it would try opening it as an activity.
Override another method onViewCreated(). Get all the codes you put in onCreateView(), except the first line that inflates, put them in onViewCreated(). This way you are sure the view has been created and is ready to be used.
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity, container, false);
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState){
super.onViewCreated (view, savedInstanceState);
final TextView nameTxt = (TextView) view.findViewById(R.id.nameTxtDetail);
final TextView descTxt = (TextView) view.findViewById(R.id.descDetailTxt);
final Button btn = (Button) view.findViewById(R.id.btn);
//RECEIVE
Intent i = getActivity().getIntent();
String name = i.getExtras().getString("NAME_KEY");
String desc = i.getExtras().getString("DESCRIPTION_KEY");
//BIND
nameTxt.setText(name);
descTxt.setText(desc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getContext());
alertDialogBuilder.setTitle("Do you want to login?");
// set dialog message alertDialogBuilder .setCancelable(false)
.setNeutralButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(getActivity(), FacebookLogin.class); startActivity(i);
}
})
.setPositiveButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close //
current activity dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it alertDialog.show();
}
});
}

Recycler View Item onClick

I have Googled a number of possibilities on how to get the item which is clicked in a recycler view but none of them seem to work. The code below should work but I dont understand why its not. In android studio, the getPosition() method is crossed out. I am running out of ideas, Is there a way i can at least toast the name of the recycler view is clicked?
ViewHolder
public class ShoppingListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CardView cv;
public TextView name;
public TextView description;
Context context;
public ShoppingListViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cardView);
name = (TextView) itemView.findViewById(R.id.title);
description = (TextView) itemView.findViewById(R.id.description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("RecyclerView", "onClick:" + getPosition());
}
});
}
public void bindView(int position) {
}
#Override
public void onClick(View v) {
Log.d("TAG", "onClick " + getPosition() + " " + name);
}
Adapter
public class MainShoppingListViewActivity extends AppCompatActivity {
List<Data> list = new ArrayList<>();
RecyclerView recyclerView;
ShoppingListViewAdapter adapter;
Context context;
EditText listName;
Firebase ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_shoppinglist_view);
Firebase.setAndroidContext(this);
ref = new Firebase("https://shoppinglistshare.firebaseio.com/");
// Getting the recycler view, using the Recycler View
recyclerView = (RecyclerView) findViewById(R.id.shopping_list_recycler_view);
// The setLayoutManager which contains the main container where the Recycler View is contained
recyclerView.setLayoutManager(new LinearLayoutManager(MainShoppingListViewActivity.this));
// Floating action bar initiated, background color is set and then onClickListener to act when the
// button is pressed to which the createDialogBox(); method is called
FloatingActionButton addFloat = (FloatingActionButton) findViewById(R.id.fab);
addFloat.setBackgroundTintList(ColorStateList.valueOf(Color
.parseColor("#3F51B5")));
addFloat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Click action
createDialogBox();
}
});
}
/*
* This method is used to add a new item to the Recycler View
*/
public void addNewShoppingListItem(String val) {
ref = new Firebase("https://shoppinglistshare.firebaseio.com/");
adapter = new ShoppingListViewAdapter(list, MainShoppingListViewActivity.this);
recyclerView.setAdapter(adapter);
adapter.addItem(new Data(val, "Created by: Me"));
ref.child("List Name: ").setValue(val);
}
/*
* This method is used to add a new item to the Recycler View
*/
public void removeShoppingListItem(String val) {
adapter = new ShoppingListViewAdapter(list, MainShoppingListViewActivity.this);
recyclerView.setAdapter(adapter);
adapter.addItem(new Data(val, "Created by: Me"));
}
/*
* This method is called inside the float action bar to create a dialog box when the floating action button is pressed.
*/
public void createDialogBox() {
// Alert Dialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Using Layout Inflater class and assigned to a variable and using getLayout
LayoutInflater inflater = this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout.
// Using the view class to inflate the layout.
View rootView = inflater.inflate(R.layout.custom_alert_dialog, null);
listName = (EditText) rootView.findViewById(R.id.ShoppinglistName);
// Using the AlertDialog Builder created above as "builder" to set the view.
builder.setView(rootView)
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String val = listName.getText().toString();
if (!val.isEmpty()) {
addNewShoppingListItem(val);
} else {
Toast.makeText(MainShoppingListViewActivity.this, "Please enter a value", Toast.LENGTH_SHORT).show();
}
}
})
// Show the dialog
.show();
}
}
Logs
FATAL EXCEPTION: main
Process: familyshopshare.com.familyshopshare, PID: 17889
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:102)
at android.widget.Toast.makeText(Toast.java:259)
at familyshopshare.com.familyshopshare.ShoppingListViewHolder$1.onClick(ShoppingListViewHolder.java:33)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Made small changes, here is the solution i got. I am going to alter the onClick onto another method instead of where it is. If there are any suggestions on how i can make the code better please let me know, any advise is much appreciated :)
public class ShoppingListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CardView cv;
public TextView name;
public TextView description;
Context context;
public ShoppingListViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cardView);
name = (TextView) itemView.findViewById(R.id.title);
description = (TextView) itemView.findViewById(R.id.description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Data test = new Data(name.getText().toString(), description.getText().toString());
Toast.makeText(v.getContext(), "onClick " + test.getName(), Toast.LENGTH_SHORT).show();
Log.d("RecyclerView", "onClick is this:" + getAdapterPosition());
}
});
}
#Override
public void onClick(View v) {
Toast.makeText(context, "onClick " + getAdapterPosition() + " " + name, Toast.LENGTH_SHORT).show();
}
}
There are a few ways you can do it. Personally, I like to set the listener in the onBindViewHolder inside of the adapter class(wherever you have your viewholder):
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.YourTargetObject.setOnClickListener(new View.onClickListener(){
public void onClick(View view){
//do something
}
});
}

Categories