Conflict with buttons android - java

I have 2 xml files, "activity_main" and "main_screen", both have 1 button each here are the xml of the buttons:
The login button < this button is on the first screen of my application
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/entrar"
android:id="#+id/button"
android:onClick="onClick"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
And the "save data button" < this one is on the second screen.
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Salvar"
android:id="#+id/button2"
android:onClick="onClick"
android:layout_marginTop="43dp" />
Java code of the first button:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Editable login = editLogin.getText();
String loginTexto = login.toString();
Editable pass = editPass.getText();
String senhaTexto = pass.toString();
try{
trocaTela();
System.out.println("botao login" + R.id.button);
//a.enviaDados(loginTexto, senhaTexto, textView);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
});
Java code of the second button:
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText editNome = (EditText) findViewById(R.id.nomeEdit);
final EditText editDestino = (EditText) findViewById(R.id.destinoEdit);
final EditText editKm = (EditText) findViewById(R.id.kmEdit);
final TextView textView = (TextView) findViewById(R.id.textView);
//pega o texto inserido no campo da placa
Editable editable = editPlaca.getText();
String placaTexto = editable.toString();
//pega o nome inserido no campo do nome
Editable nomeEditable = editNome.getText();
String nomeTexto = nomeEditable.toString();
//pega o destino inserido no campo do destino
Editable destinoEditable = editDestino.getText();
String destinoTexto = destinoEditable.toString();
//pega o valor inserido no campo do km
Editable kmEditable = editKm.getText();
String kmTexto = kmEditable.toString();
try {
ScreenFunctions f = new ScreenFunctions();
System.out.println("botao screen:" + R.id.button2);
f.formatPost(nomeTexto, placaTexto, destinoTexto, kmTexto, textView);
} catch (Exception e) {
System.out.println("Button press exception: " + e.getMessage());
}
}
});
The problem is... i can't understand how i'll treat the "onClick" function, because the "onClick" method is abstract, so i can't change it's name, how could the second button use the MainScreen onClick and the first button use the MainActivity onClick.

remove the
android:onClick="onClick"
You dont need to have this cause you are setting onclicklisteners in your java code
give me info if this helped or not
EDIT
make sure you have catch your button variables correctly:
button = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.button2;

Remove the android:onClick="onClick" in your xml files.
You are misunderstand the usage of android:onClick tag in xml file.
Please check the document of android:onClick tag

Change the name of function:
android:onClick="onClick"
to
android:onClick="someMethod"

I think if you want to make your code prettier and better, you should use ButterKnife for view injection and specifying the onclick method with that, like this:
1.) add ButterKnife to your dependencies
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
...
compile 'com.jakewharton:butterknife:6.0.0'
2.) inject your view into the field
#InjectView(R.id.button)
public Button button;
3.) specify the onClick method
#OnClick(R.id.button)
public void myOnClickMethod(View view)
{
//do things
}
4.) inject the activity or fragment with ButterKnife
Activity:
#Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
ButterKnife.inject(this);
...
}
Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.inject(this, rootView);
...
return rootView;
}

Related

Adding Dynamic Text View

Trying to create notes application. I am trying to add dynamic text view after button click and it should be added to layout, one after another. In my code, only one text view is getting added successfully but from second time, app got crashed. Please help
XML Code:
<EditText
android:id="#+id/text_thingsToDo"
android:layout_width="#dimen/ThingsToDo_EditText_Width"
android:layout_height="#dimen/ThingsToDo_EditText_Height"
android:layout_margin="#dimen/Standardize_Margin"
android:background="#color/ThingsToDo_EditText_Color"/>
<Button
android:id="#+id/save_thingsToDo"
android:layout_toRightOf="#+id/text_thingsToDo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ThingsToDo_Save_Button_Text"
android:layout_marginRight="#dimen/Standardize_Margin"
android:layout_marginTop="#dimen/Standardize_Margin"
android:layout_marginBottom="#dimen/Standardize_Margin"
android:background="#color/ThingsToDo_Save_Button"
android:textColor="#color/White"
android:layout_centerVertical="true"/>
Java Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_things_to_do);
final EditText editText = (EditText) findViewById(R.id.text_thingsToDo);
Button button = (Button) findViewById(R.id.save_thingsToDo);
final TextView notesView = new TextView(this);
final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.rootView_ThingsToDo);
final ArrayList<String> arrayList = new ArrayList<String>();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notesView.setText(editText.getText().toString());
linearLayout.addView(notesView);
}
});
}
Perhaps create a new TextView every time you press the button? Try to declare the TextView as a class member and then in your OnClickListener do this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notesView = new TextView(this);
notesView.setText(editText.getText().toString());
linearLayout.addView(notesView);
}
});
Hopefully this will fix your problem!

Android - Calling a function from a fragment

I'm trying to make a tabbed activity with 3 fragments. One of my fragments has got a button with is calling a function onClick:
<Button
android:text="Start meeting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="58dp"
android:id="#+id/sp_live_meeting"
android:layout_below="#+id/live_cost"
android:layout_centerHorizontal="true"
android:onClick="sp_timer" />
The fragment is created in the coresponding class file:
public class LiveMeeting_meeting_fragment extends Fragment {
Button sp;
Button stop;
Chronometer chrono;
int cnt = 0;
long timeStop;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.livemeeting_meeting_fragment, container, false);
sp = (Button) rootView.findViewById(R.id.sp_live_meeting);
stop = (Button) rootView.findViewById(R.id.stop_live_meeting);
chrono = (Chronometer) rootView.findViewById(R.id.live_timer);
return rootView;
}
public void sp_timer(View view){
if(cnt == 0){
sp.setText("Pause meeting");
chrono.setBase(SystemClock.elapsedRealtime() + timeStop);
chrono.start();
cnt = 1;
} else if (cnt == 1){
sp.setText("Continue meeting");
chrono.stop();
timeStop = chrono.getBase() - SystemClock.elapsedRealtime();
cnt = 0;
}
}
}
My problem is now, that I'm not able to call the function because it's telling me that it can't find the function:
java.lang.IllegalStateException: Could not find method sp_timer(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'sp_live_meeting'
How can I solve this?
Delete your onClick attribute from XML and instead use onClickListener.
Code:
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//write your sp_timer method here
}
});
Android looks for the onClick method sp_timer() only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.

How to implement a ClickListener for a button from a custom layout to use in a FragmentDialog

I'm try to set the action for ImageButton. When the DialgoFragment is called and is shown on screen, I want to preess the button and get an action. When I put my action inside that onClick in the code below it didn't work. I'm sure that's not the right way of doing it.
I'm using this class as fragment:
public class GeneralDialogFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout to use as dialog or embedded fragment
View v = inflater.inflate(R.layout.activity_dialog, container, false);
ImageButton mImageButton = (ImageButton) v.findViewById(R.id.image_button);
mImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String name = "";
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", Context.MODE_PRIVATE);
String yourmessage = prefs.getString("msg", null);
if (yourmessage != null) {
name = prefs.getString("msg", "No name defined");//"No name defined" is the default value.
}
ScrollTextView txt = (ScrollTextView) v.findViewById(R.id.scroll_text);
txt.setText(name);
txt.setTextSize(220);
txt.startScroll();
}
});
return v;
}
And in this activity_dialog layout I have an ImageButton:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image_button"
android:src="#drawable/ic_image_500px"/>
Edited: Now the action is in the class above. The error actually is in the action. I have the MainActivity where I press this send button:
public void send(View view){
EditText mEditText = (EditText)findViewById(R.id.text_msg);
String MESSAGE = mEditText.getText().toString();
SharedPreferences.Editor editor = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
editor.putString("msg", MESSAGE );
editor.commit();
Intent intent = new Intent(this, MessageActivity.class );
startActivity(intent);
}
It calls the MessageActivity where I call the GeneralDialogFragment class which shows the ImageButton with this code:
DialogFragment mDialog = new GeneralDialogFragment();
mDialog.show(getSupportFragmentManager(), "Dialog TAG");
Because of v which you've added it before, it's working without any errors:
View v = inflater.inflate(R.layout.activity_dialog, container, false);
ImageButton mImageButton = (ImageButton) v.findViewById(R.id.image_button);

changing the setText value in a fragment from main activity

I've been trying to change my textViews text in a fragmentActivity based on whether or not user has clicked the button in the first main activity. I have 2 xml files and 2 .java files and the code at the moment crashes when the app starts.
This is the button code
public void getNum(View view) {
buttonCheck = 1;
}
And this is the code from FragmentTab
public class FragmentTab extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
TextView tv = (TextView) v.findViewById(R.id.text);
tv.setText("nothing has been input yet");
if (FirstActivity.buttonCheck == 1){
tv = (TextView) v.findViewById(R.id.text);
tv.setText("value");}
FirstActivity.buttonCheck = 0;
return v;
}
The first error i get from my code from logcat is: "java.lang.NullPointerException
at com.ezentertainment.dietabialkowa.FragmentTab.onCreateView(FragmentTab.java:23)" and line 23 is tv.setText("nothing has been input yet");
any help at all is greatly appreciated, I have been fighting with this issue for quite some time now..
tl;dr how to change fragment value based upon input from mainActivity?
edit: here is the fragment_layout.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#eaecee">
<TextView
android:id="#+id/textResult"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="value"
android:textAppearance="?android:attr/textAppearanceMedium" />
Your textview id is
android:id="#+id/textResult"
So, that's why you're getting a null pointer exception.
Also, it's probably a good idea to do a null check when finding a view by ID, just in case something isn't instantiated yet, so it doesn't kill your app. Something like:
TextView tv = (TextView) v.findViewById(R.id.textResult);
if (tv != null){
tv.setText("nothing has been input yet");
} else {
// log something if you want.
}
How about using setArguement:
In Activity:
Bundle bundle = new Bundle();
bundle.putString("email", email);
FragmentA fragment = new FragmentA();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(container, fragment, tag).addToBackStack(tag).commit(); //please input container and tag yourself
In FragmentA:
String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
if (arguments != null)
email = bundle.getString("email");
...
}

Adding button click event crashes app at launch

I have the following Java code for my button event. This code doesn't generate any error at compile-time, but the app crashes during launch.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b0 = (Button) findViewById(R.id.button0);
b0.setOnClickListener(this);
}
String t = "";
TextView inp = (TextView) findViewById(R.id.input);
public void onClick(View v)
{
if (v == findViewById(R.id.button0))
{
t = "0";
inp.setText(inp.getText()+t);
}
}
The Xml Code is :
<Button
android:id="#+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/dbtn"
android:layout_alignBottom="#+id/dbtn"
android:layout_toLeftOf="#+id/button3"
android:text="0" />
What am I doing wrong?
TextView inp = (TextView) findViewById(R.id.input);
Put the above line inside onCreate() method after you call setContentView() and change you TextView variable scope from local to global.
This should fix the issue. If you still having trouble, let me know.

Categories