Changing TextView Attributes from button onClick not working - android

So I have a xml fragment called fragment_home. Which has 2 buttons and a textview inside cardview. One of the button (tries to) change the value in the textview. On both the buttons I have an onClick. The tools:context for the fragment is set to .MainActivity. I also have a extend Fragment class which is associated with the xml fragment.
Whenever I try to call anything to change the TextView attributes such as setText,setTextSize I get an exception: java.lang.IllegalStateException: Could not execute method for android:onClick
If I do not have setText, setTextSize, the onClick works.
MainActivity:
public class MainActivity extends AppCompatActivity {
private int textViewData;
private TextView inputDataTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputDataTextView= (TextView)findViewById(R.id.focus_counter);
}
//onClick For One of the buttons
public void increaseNumber(View view) {
textViewData++;
// Crashes When I have This. Doesn't crash when I comment this.
inputDataTextView.setTextSize(60);
// Crashes When I have this. Doesn't crash when I comment this.
inputDataTextView.setText(String.valueOf(textViewData);
Toast.makeText(this, "TextView Value = " + textViewData, Toast.LENGTH_SHORT).show();
}
I feel like It's something to do with my fragment and activity. But I just do not know what the problem is. As soon as I call anything related to the textview in the onClick the app crashes. And the textview in the xml is set to 0 initially and when I increase the number, it increases, so thats working.
Thanks for the help!!
HomeFragment:
public class HomeFragment extends Fragment {
private int textViewData;
private static final String TAG = "MyActivity";
private TextView inputDataTextView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
inputDataTextView = view.findViewById(R.id.focus_counter);
return view;
}
public void increaseNumber(View view) {
textViewData++;
//inputDataTextView.setText("t");
inputDataTextView.setText(String.valueOf(inputViewData));
//Toast.makeText(getContext(), "Focus Vale = " + inputViewData, Toast.LENGTH_SHORT).show();
}
}

Your inputDataTextView is null because its in fragment but your instantiating it from MainActivity, which is wrong. Move both the onClick methods and view to the fragment java code.
Edit copy theses codes from MainActivity to HomeFragment before onCreateView:
private int textViewData;
private TextView inputDataTextView;
Then these inside onCreateView before the return statement:
inputDataTextView=
(TextView)findViewById(R.id.focus_counter);
Then these method inside your fragment:
public void increaseNumber(View view) {
textViewData++;
inputDataTextView.setTextSize(60);
inputDataTextView.setText(String.valueOf(textViewData);
Toast.makeText(this, "TextView Value = " + textViewData, Toast.LENGTH_SHORT).show();
}
It should work now

Related

onClick at button in Fragment desn't work

In my app I have tabbed activity with two fragments. At the fragment I want to use button to open dialog alert. But for five hours now I'm struggling with actual clicking on button. I tried ways with making onClick with xml, Implement OnClickListener But nothing worked. The button is just doing nothing. I tried to debug it and it seems that onCreateView method is not called at all. Any tips?
public class PlayersFragment extends Fragment {
public PlayersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_players, container, false);
Button addButton = (Button) view.findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "YES is clicked!",
Toast.LENGTH_LONG).show();
}
});
return view;
}
Override the onViewCreated method in your fragment class. Then put the onClickListener on your Button with the method.

Android: "Method is never used" warning for onClick method

This is a part of my calc_fragment.xml file ,
<Button
android:id="#+id/b7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="2dp"
android:background="#drawable/roundedbutton"
android:fontFamily="sans-serif-thin"
android:text="Add"
android:textColor="#color/light_grey"
android:textSize="45sp"
android:onClick="clicked"/>
that is linked with the following fragment:
public class CalcFragment extends Fragment {
private TextView textView;
private String text;
private Vibrator vibe;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.calc_fragment, container, false);
return rootView;
}
public void clicked (View v){ <--- "Method clicked is never used"
...content...
}
I get a warning "Method clicked is never used" but I my button is linked with this method
A Fragment is tightly linked with its activity. So, the above method declaration in xml will basically look for that method in the Activity class. One of the ways is that you can explicitly link your method and the button:
public class CalcFragment extends Fragment {
private TextView textView;
private String text;
private Vibrator vibe;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.calc_fragment, container, false);
View myButton = rootView.findViewById(R.id.b7);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked(v);
}
});
return rootView;
}
public void clicked (View v){ // Your method
...content...
}
Get rid of the 'android:onClick="clicked"' property in your xml.
This is because the XML code for handling clicks does not work for the Fragment class, it currently works only with the Activity class. As such, this method will never be called. See this question for more details.
In the onCreateView method of the CalcFragment, you need to declare and initialize the button after the initializing the rootView:
Button b7 = (Button) rootView.findViewById(R.id.b7);
You then need an onClickListener instead of defining your own clicked method. There are two methods to listen to a click of a button.
The first method:
You can set the onClickListener within the onCreatView as follows:
b7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do something
}
});
The second method:
You can define an onClickListener as follows:
final View.OnClickListener b7OnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do something
}
};
When using the second method, you will need to set the onClickListener like you did in the first method however in this case you will pass the name of the onClickListener object you created.
Example:
b7.setOnClickListener(b7OnClickListener);

How to get values of edittext which is in fragment on button click which is in activity?

signup screen with of two different modules driver and customer
Hi everyone I am working in android from past one year but now I am creating an app in which am using fragments instead of activity even after serching from so many sites and blogs am unable to implement what I want.
My requirement is as you see on the image two radio button one for customer and one for driver so when user click on any one of options then signup screen appears which is on fragment and one button is there at bottom which is on activity so I want how to get all edittext value on button click so that i can send these values to the server. My main problem is getting the values of edittext fields on button click.
So any help will be appriciated.
thanks in advance
Try like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
this.initViews(rootView);
selectProfessionsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
whta_you_want_on_button_click();
}
});
}
private void initViews(View view) {
//define your edittext like FirstNameEditText = (EditText) view.findViewById(R.id.FirstNameEditText);
}
now define the whta_you_want_on_button_click() method
in your activity, put below code in your button's click event.
try {
Fragment rg = getSupportFragmentManager().findFragmentByTag("YourFragmentTag");
if (rg != null) {
EditText et = (EditText) ((YourFragment) rg).getView().findViewById(R.id.edittext);
String etValue = et.getText().toString();
}
} catch (Exception e) {
}
Your context will change from getApplicationContext() to getActivity.getApplicationContext() when you are referencing a fragment instead of an activity
You have to create your edittext in this fashion
While assigning the layout you need to assign in this way.
View view = inflater.inflate(R.layout.fragmentlayout,container,false);
And while assigning edittext you need to take it as below
EditText edt = (EditText) view.findViewById(R.id.yourid);
String str = edt.getText().toString();
So on button click you can get the edittext string easily from onClick method with above code.
You can use static keyword make all edittext static so you will get all edittext values in activity on button click.
in your fragment suppose MyFragment.java
public class MyFragment extends Fragment{
View rootView;
public static EditText edt;
public MyFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
init();
return rootView;
}
protected void init(){
edt = (EditText) rootView.findViewById(R.id.edt);
}
}
in your activity suppose MainActivity.java
public class MainActivity extends Activity{
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewByid(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String value = MyFragment.edt.getText().toString().trim();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
});
}
}

Android: Button OnClick not working in SherlockFragment

I've tab activity in which i want to use a button, but when i click on button, it force closes the app. Can you please tell me what is going on, i am new to Android.
public class HomeActivity extends SherlockFragment {
private Button bt;
private Context con;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_layout, container, false);
bt = (Button)rootView.findViewById(R.id.btn);
bt.setOnClickListener(new View.OnClickListener(){
#Override public void onClick(View v)
{
Toast.makeText(con, "hello", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
when i click on button, it force closes the app
Because con object of Context is null. which is used for showing Toast message in Button onClick method.
Do it as:
Toast.makeText(v.getContext(), "hello", Toast.LENGTH_LONG).show();
And initialize con object by calling getActivity() in onCreateView as:
con=getActivity();
If you can avoid that, don't keep a reference to the context; instead of the
private Context con;
get the current Activity in the code, so use
Toast.makeText(getActivity(), "hello", Toast.LENGTH_LONG).show();
Btw, this seems to be the cause of your crash, as Context is null.

change Imagebutton background after refreshing fragment

im still new in android developement.
I want to refresh my fragment and getting new imageButton background in that fragment but i keep failing to do that.
This is my main activity
public class MainActivity extends AppCompatActivity {
public int QuestionNum =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MainActivityFragment MainFrag = new MainActivityFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.content, MainFrag).commit();
}
public void Answer1(View view){
QuestionNum++;
Stage StageFrag = new Stage();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content,StageFrag).commit();
}
and this is my fragment
public class Stage extends Fragment {
public Stage() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stage, container, false);
MainActivity Main = new MainActivity();
String QuestionInd[] = getResources().getStringArray(R.array.Qind);
Integer AnswerAnimal[]={R.drawable.anjing,R.drawable.kucing....};
int QNum = Main.QuestionNum;
TextView Question = (TextView) view.findViewById(R.id.Questions);
Question.setText(QuestionInd[Main.QuestionNum]);
ImageButton Ans1 = (ImageButton) view.findViewById(R.id.Choice1);
ImageButton Ans2 = (ImageButton) view.findViewById(R.id.Choice2);
ImageButton Ans3 = (ImageButton) view.findViewById(R.id.Choice3);
ImageButton Ans4 = (ImageButton) view.findViewById(R.id.Choice4);
switch(QNum) {
case 0:
Ans1.setBackgroundResource(AnswerAnimal[0]);
Ans2.setBackgroundResource(AnswerAnimal[1]);
Ans3.setBackgroundResource(AnswerAnimal[2]);
Ans4.setBackgroundResource(AnswerAnimal[3]);
break;
case 1:
Ans1.setBackgroundResource(AnswerAnimal[8]);
Ans2.setBackgroundResource(AnswerAnimal[9]);
Ans3.setBackgroundResource(AnswerAnimal[5]);
Ans4.setBackgroundResource(AnswerAnimal[4]);
break;
}
return view;
}
}
i didnt get error in my logcat. I also try using add but the background didn't change only the fragments keep stacking. Using the attach and retach didnt work too.
Please help me and explain my mistake. i really want to learn about this. Thank you.
First of all, never do this:
MainActivity Main = new MainActivity();
explained here.
Second: Even if you considered an Android Activity as just a normal Java Class, then new MainActivity() means you are creating new instance of that class, so the instance variables will be what or how you defined them i.e public int QuestionNum =0 will remain the same.
Hence the switch statement never comes to case: 1.
What you can do is just call some method like changeImageButtons() on the StageFrag Object you have in the Activity.

Categories

Resources