How can I get a dialog to work within a fragment? - java

I am trying to use a floating action button in a fragment to bring up a dialog to create a new post. The issue I am having is that I get an error on this line of code:
popAddPost = new Dialog(this);
The error states that:
Dialog (android.content.context) in Dialog cannot be applied to (com.comhar.firebaseapp.Fragments.ForumFragment)
I have tried using a few solutions i found online but none have worked
ForumFragment.java
public class ForumFragment extends Fragment {
Dialog popAddPost;
public ForumFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_forum, container, false);
iniPopup();
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popAddPost.show();
}
});
return view;
}
private void iniPopup() {
popAddPost = new Dialog(this);
popAddPost.setContentView(R.layout.popup_add_post);
popAddPost.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popAddPost.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT,Toolbar.LayoutParams.WRAP_CONTENT);
popAddPost.getWindow().getAttributes().gravity = Gravity.TOP;
}
}
fragment_forum.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.ForumFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="forum" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:src="#drawable/nep_post" />
</FrameLayout>
The app will not run as I am recieving the error:
error: incompatible types: ForumFragment cannot be converted to Context
any advice would be greatly appreciated!

You should init the dialog with an proper context, it can be the context where the Fragment resides or could be the activity which holds the Fragment. So, replace this line:
popAddPost = new Dialog(this);
by this:
popAddPost = new Dialog(getActivity());

Update your iniPopup() method like this:
private void iniPopup() {
popAddPost = new Dialog(getActivity());
popAddPost.setContentView(R.layout.activity_login);
popAddPost.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popAddPost.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT, Toolbar.LayoutParams.WRAP_CONTENT);
popAddPost.getWindow().getAttributes().gravity = Gravity.TOP;
}
Let me know in case of any query.

Related

Opening a dialog box inside adapter returning null values

I have been trying to get this to work without success for about 10 hours now, I have looked all over stack overflow. I am trying to get a simple dialog box to appear and handle some simple input.
It has a TextView as a title, EditText as a input field, and two button continue with the operation or cancel.
For some reason, no matter what I do, I cannot seem to be able to reference ANY view inside my shopping_dialogue xml layout. It gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
I have tried to add an onClick event to the button to see if that works, when I try to reference the button inside the onClick method it gives me the same error. I am using a fragment to do this.
shopping_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/shoppingDialogTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Edit Shopping List Name" />
<EditText
android:id="#+id/shoppingDialogEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="30"
android:inputType="textPersonName"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/shoppingDialogOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="#+id/shoppingDialogCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="k"
android:text="Button" />
</LinearLayout>
shopping_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
card_view:cardCornerRadius="4dp"
android:id="#+id/shoppingList_card_view"
android:layout_margin="10dp"
android:layout_height="200dp">
<LinearLayout
android:id="#+id/shoppingListParent"
android:layout_gravity="center"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_height="match_parent">
<TextView
android:id="#+id/shoppingName"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textColor="#FFF"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/shoppingDate"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textColor="#FFF"
android:layout_height="wrap_content" />
</LinearLayout>
</androidx.cardview.widget.CardView>
fragment_shopping_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/shoppingList_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ShopingAdapter.java
public class ShoppingAdapter extends RecyclerView.Adapter<ShoppingAdapter.ShoppingViewHolder> {
private List<ShoppingData> shoppingList;
private Context context;
public ShoppingAdapter(List<ShoppingData> shoppingList, Context context){
this.shoppingList = shoppingList;
this.context = context;
}
#NonNull
#Override
public ShoppingViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i){
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.shopping_list_row, viewGroup, false);
return new ShoppingViewHolder(itemView);
}
#Override
public void onBindViewHolder(ShoppingViewHolder viewHolder, int i){
ShoppingData data = shoppingList.get(i);
Random k = new Random();
int color = Color.argb(255,k.nextInt(255),k.nextInt(255),k.nextInt(255));
viewHolder.parent.setBackgroundColor(color);
viewHolder.shoppingName.setText(data.getName());
viewHolder.shoppingDate.setText(data.getDate());
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setCancelable(true);
builder1.setView(R.layout.shopping_dialog);
AlertDialog alert = builder1.create();
/*
EditText text = v.findViewById(R.id.shoppingDialogEditText);
text.setText("Some Text");
This causes a null object reference
*/
alert.show();
}
});
}
#Override
public int getItemCount(){return shoppingList.size();}
public class ShoppingViewHolder extends RecyclerView.ViewHolder{
private TextView shoppingName, shoppingDate;
private LinearLayout parent;
public ShoppingViewHolder(View itemView){
super(itemView);
parent = itemView.findViewById(R.id.shoppingListParent);
shoppingName = itemView.findViewById(R.id.shoppingName);
shoppingDate = itemView.findViewById(R.id.shoppingDate);
}
}
}
ShoppingFragment.java
public class ShoppingFragment extends Fragment {
private RecyclerView recyclerView;
private ShoppingAdapter shoppingAdapter;
private List<ShoppingData> shoppingList = new ArrayList<>();
#NonNull
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState){
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
View rootView = inflater.inflate(R.layout.fragment_shopping_list, container, false);
recyclerView = rootView.findViewById(R.id.shoppingList_recycler_view);
shoppingAdapter = new ShoppingAdapter(shoppingList, getActivity());
RecyclerView.LayoutManager manager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(shoppingAdapter);
return rootView;
}
public void k(View view){ //the click listern that causes a null object reference when referencing the button
Button button = view.findViewById(R.id.shoppingDialogOk);
button.setText("k");
}
}
ShoppingData.java
package com.uhcl.recipe5nd.helperClasses;
public class ShoppingData {
private String name;
private String date;
public ShoppingData(String name, String date){
this.name = name;
this.date = date;
}
public String getDate(){
return this.date;
}
public String getName(){
return this.name;
}
}
Everything works fine until I try to reference anything inside shopping_dialog.xml.
If you look at my shopping adapter class, what I am trying to do is to add an onClick listener to the "shoppigName" text view inside my onBindViewHolder method. This works, but when I try to reference the shoppingDialogEditText, it causes the app the crash and give me that error.
Like I mentioned I also tried adding a click event method k to a button inside shopping_dialog.xml, and implemented it inside my fragment class to see if that would work, but it still causes the same error.
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View dailogView = LayoutInflater.from(mContext).inflate(R.layout.shopping_dialog, null);
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setCancelable(true);
builder1.setView(dailogView);
AlertDialog alert = builder1.create();
EditText text = dailogView.findViewById(R.id.shoppingDialogEditText);
text.setText("Some Text");
alert.show();
}
});
The view your using to the find the edittext is not the view of that dialog box, therefore it's throwing null pointer.
You are using a wrong view to find the editText. It is not the view of dialog box. It is the view of the item which is being clicked rather than dialog box.
Use this
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View dailogView =
LayoutInflater.from(mContext).inflate(R.layout.shopping_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setCancelable(true);
builder.setView(dailogView);
AlertDialog alert = builder.create();
EditText text = dailogView.findViewById(R.id.shoppingDialogEditText);
text.setText("Shopping Dialog Text");
alert.show();
}
});
}

How to find button by id from Fragment [duplicate]

This question already has answers here:
findViewById in Fragment
(37 answers)
Closed 6 years ago.
I'm making an android app and I have a button that won't react when I press it. The button is supposed to bring up an alertdialog box. I'm very confused as I have an OnClickListener and the dialog box is instantiated.
Here is the code from the Java file:
public class tab1Expenses extends Fragment {
Button btnEx;
public class button extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1expense);
btnEx = (Button)findViewById(R.id.btnEx);
btnEx.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
View view = LayoutInflater.from(button.this).inflate(R.layout.add_ex, null);
AlertDialog.Builder add = new AlertDialog.Builder(button.this);
add.setView(view);
add.setCancelable(true)
.setTitle("Enter Expense:")
.setMessage("Expense Name:")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog = add.create();
dialog.show();
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1expense, container, false);
return rootView;
}
}
And here is my XML file that is related to the java file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ojemz.expensetracker.tab1Expenses$button"
android:background="#android:color/darker_gray">
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:width="800dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- TextView and other stuff -->
</LinearLayout>
</ScrollView>
You're doing it wrong!
The button class extending Activity has no reason to exist here.
If you simply want to get some onClick callbacks just do the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button)rootView.findViewById(R.id.btnEx);
btnEx.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
View view = LayoutInflater.from(button.this).inflate(R.layout.add_ex, null);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setView(view);
add.setCancelable(true)
.setTitle("Enter Expense:")
.setMessage("Expense Name:")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
Don't forget to remove your "button" inner class.
Side note
You should rename your tab1Expenses Fragment class to Tab1Expenses in order to distinguish between instances and classes.
Please refer to Java naming conversions.

How to go one Fragment to another when I will click on TextView Id?

How to go one Fragment to another when I will click on TextView Id?
Error shows:
java.lang.ClassCastException: com.example.tripigator.Overview cannot be cast to android.app.Activity.
and error comes from these lines :
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
So please anybody help me how to move from one fragment to another by clicking text item.
ProjectOverview class :
public class ProjectOverview extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project_overview);
initialingpaging();
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
}
private void initialingpaging() {
// TODO Auto-generated method stub
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Overview.class.getName()));
fragments.add(Fragment.instantiate(this, Highlight.class.getName()));
mPageAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPageAdapter);
}
}
Two Fragment Classes:
public class Overview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.overview,container,false);
}
}
public class Highlight extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.highlight,container,false);
}
}
Layout Interface:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/project_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="65dp"
android:gravity="center" >
<TextView
android:id="#+id/txt_overview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Overview" />
<TextView
android:id="#+id/txt_highlite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Highlight" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
You can't initiate the fragment using Intent.Try this it helps.
Fragment fragment = null;
FragmentManager frgManager;
FragmentTransaction ft;
fragment = new Overview();
ft = frgManager.beginTransaction();
ft.replace(R.id.frame_content, fragment);
ft.addToBackStack(null);
ft.commitAllowingStateLoss();
If you use View-Pager
your_ViewPager.setCurrentItem(position)
you should not use intent in fragment to move another fragment
and check this for whole example http://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/
use this.
((yourfragmentActivity) getActivity()).setCurrentItem(1,//desired activity 0=first 1= second and so on
true);
insted
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);

Change view on button click from CustomAdapter

I have created a layout that contains a listView, the view is populated with multiple similar elements in the onCreateView function from a Fragment, the view is populated in the CustomAdapter extends BaseAdapter. In each element of the listView I have a button for which I want to implement a onClickListener. When the button is clicked I want to switch to another view, something similar to viewing comments on the GooglePlus mobile app.
I have tried doing so this way in the CustomAdapter:
public void setOnClickComment(View view) {
final ImageButton btn = (ImageButton)view.findViewById(R.id.addComment);
if (btn != null) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("ONCLICK", "I just clicked this shit" + btn.getTag());
manager.beginTransaction()
.replace(R.id.feedLayout, new CommentFragment()).commit();
}
});
} else {
Log.d("CLICK", "ESTE NULL");
}
}
The manager is a FragmentManager and it's passed from the fragment to the CustomAdapter constructor. I can see the Log in LogCat but that's it nothing else happens, the tag of the button is the position of the element.
This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/feedLayout"
>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
And in the fragment I inflate the above layout:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout linear = (LinearLayout) inflater.inflate(R.layout.swipe_screen_left, container, false);
view = (ListView) linear.getChildAt(0);
adapter = new CustomAdapter(getActivity(), data, getFragmentManager());
view.setAdapter(adapter);
return linear;
}

setRetainInstance not retaining the instance

I'm trying to use setRetainInstance() but it seems not working for me! =(.
I simplified the problem to the easiest version:
I have a fragment with a TextView and a Button.
The initial text of the TextView is "I'm waiting" when the button is pressed the text changes to "Hello!"
That is my code:
The fragment:
public class SayHelloFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.setText("Hello!");
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
The Activity:
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/say_hello_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.example.retaintext.SayHelloFragment" />
The Fragment's layout:
<?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:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I&apos;m Waiting"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
But when I play it, press the button and change the device's orientation the text becomes reset.
What am I missing? How can I solve it? Thanks!
You are missing that onCreateView runs after the rotation again and inflates the default view with the default text again.
You need to restore the state of your views manually, e.g.:
public class SayHelloFragment extends Fragment {
private String mText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
if (mText != null)
text.setText(mText);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mText = "Hello!";
text.setText(mText);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}

Categories

Resources