Android application with switch statement crashes on my phone - java

When I run this code on my Android Phone, it keeps on crashing.
My java code is as follows
public class MainActivity extends Activity {
EditText edit = (EditText) findViewById(R.id.text);
Button button = (Button) findViewById(R.id.button);
String string = edit.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (string){
case "c":
MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
mp1.start();
break;
My XML code:
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pembroke.com.example.algorhythmic.MainActivity">
<EditText
android:id="#+id/box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="308dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.781" />
The code is crashing, but I don't know why. I might not be using the string correctly.
No errors in the code but it is still crashing. Is it because the Android IDE can't compute my code?

There are 3 problems with the code :
For doing the findViewById, we do this after setContentView in onCreate method of activity. This is because, before setContentView, all views are null. Hence, I moved the findViewById code for both EditText and button after setContentView(R.layout.activity_main) in onCreate method of activity.
For the edittext, the ID which you used is R.id.text in java code, but in xml, it is R.id.box. So I have changed that to R.id.box in java code when doing the findViewById.
To find the value present in EditText, we have to get text present in EditText inside the onClickListener since the value inside EditText keeps on changing as user enters inside EditText.
Hence we assign the value to variable string inside the onClickListener's onClick method.
So final code would be :
public class MainActivity extends Activity {
EditText edit;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.box);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = edit.getText().toString();
switch (string){
case "c":
MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
mp1.start();
break;
}
}
}
}

Related

TextView wont redirect me to my registration activity from login

When I click on the Sign up txt on my application it crashes I've tried almost everything i could find including the XML onClick
XML clickable
onClick
public class LoginActivity extends AppCompatActivity
{
TextView sign_up_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sign_up_text = (TextView) findViewById(R.id.sign_up);
sign_up_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
}
}
xml:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sign_up_text"
android:textSize="18dp"
android:gravity="center"
android:layout_alignParentBottom="true"
android:id="#+id/sign_up"
android:clickable="true"
android:onClick="onClick"
/>
Android app crashes with no failure
You have android:onClick="onClick" attribute in your xml. And you have also define sign_up_text.setOnClickListener in java.
You can do only one thing at a time.
1.
If you want to use sign_up_text.setOnClickListener , you simply need to remove android:onClick="onClick" from xml file.(Reference)
2.
If you want to use android:onClick="onClick", you should define new method in your activity like:(Reference)
public void onClick(View view) {
}
First solution is to remove android:onClick="onClick" from your XML, according to my perception the reason of crash is the function name called on onClick of your button click define in XML is "onClick" which is also override function of setOnClickListner
#Override
public void onClick(View v){
//todo your code
}
Second Solution is if you use onClick in XMl change function name other that override function onClick like:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sign_up_text"
android:textSize="18dp"
android:gravity="center"
android:layout_alignParentBottom="true"
android:id="#+id/sign_up"
android:clickable="true"
android:onClick="myFunction"
/>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
private myFunction(View view){
}

Button is not reacting to click

I created a simple activity that is intended to send two pieces of information to another activity. However, my button isn't registering any click events. Does anyone have any idea why this would be? I expected that by adding the onClick = "onClickWrite" to the XML file that they would be linked but there is no response when clicked. If anyone could help me out, I would greatly appreciate it. I have tried implementing the onClickListener, however, with that implementation, it throws an error on my Toasts.
Activity
public class InitializeClass extends Activity {
private Service service;
private Button button;
EditText infoOne;
EditText infoTwo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button_control);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(clicked);
infoOne= (EditText) findViewById(R.id.editText);
infoTwo= (EditText) findViewById(R.id.editText1);
}
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
if (service != null) {
int size = 100;
byte[] byteArray = new byte[size];
byte[] byteArrayTwo = new byte[size];
byteArray = infoOne.getText().toString().getBytes(Charset.defaultCharset());
byteArrayTwo= infoTwo.getText().toString().getBytes(Charset.defaultCharset());
if ((!(infoOne.getText().toString().isEmpty())) && (!(infoTwo.getText().toString().isEmpty()))) {
service.setInfo(byteArray);
service.setInfoTwo(byteArrayTwo);
intentMethod();
}
}
}
};
public void intentMethod() {
Intent intent = new Intent(this, DeviceScanActivity.class);
startActivity(intent);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".InitializeClass">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/send_info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText1" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="150dp"
android:ems="10"
android:inputType="textPersonName"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</android.support.constraint.ConstraintLayout>
You need to initialize your button first.
Button button = (Button) findViewById(R.id.button);
Hope this helps!
In your activity class assign the button to the id of the button in the xml:
private Button btn = findViewById(R.id.button);
You will then create an OnClickListener:
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
//Insert Code here
}
};
In your onCreate method in the same activity class you will instantiate the button and assign the button to the onClickListener:
btn = new Button(this);
btn.setOnClickListener(clicked);
There are couple of things you need to do for that.
Create Field.
private Button button;
Initialize button.
Button button = (Button) findViewById(R.id.button);
Set Listener on button.
button.setOnClickListener();
I found the answer. Service in if (service != null) was never being initialized. Stupid mistake on my part. Thanks, everyone for the help and directing me in a way to implement onClickListener!
You need to cast the button (name) with you Java code .
for example on xml you have id/button (name)
declare it on your Java file, and do the casting.
and the onClickListener will look like this :
Cast the button : Button button ;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

How to permanently remove a linearlayout?

In this program, I want to delete ll2 (LinearLayout) when mButton is pressed. I.e I don't want this layout to appear the second time I enter this activity. When I push the button, the layout is gone for as long as I am in the activity, but when I come back into the activity, the layout is there.
How do I permanently delete it? Thanks in advance!
LinearLayout ll,ll2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
location_btn = (Button)findViewById(R.id.location_btn);
menu_btn = (Button)findViewById(R.id.bt_menu);
mButton = (Button) findViewById(R.id.buttone);
mEdit = (EditText) findViewById(R.id.edittexte);
ll2 = (LinearLayout)findViewById(R.id.llayout);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
number = mEdit.getText().toString();
mEdit.setText("");
ll2.setVisibility(View.GONE);
ll2.removeAllViewsInLayout();
}
});
}
My layout file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/llayout"
android:visibility="visible">
<EditText
android:id="#+id/edittexte"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SAVE"
android:id="#+id/buttone"/>
</LinearLayout>
Just keep a SharedPreference and save the state that you have pressed the button earlier. Then each time you enter the activity, check the value stored in your SharedPreference and if its found that the button is already pressed before, just hide the LinearLayout.
LinearLayout ll,ll2;
SharedPreference pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
pref = getSharedPreferences("MyApplication", Activity.MODE_PRIVATE);
location_btn = (Button)findViewById(R.id.location_btn);
menu_btn = (Button)findViewById(R.id.bt_menu);
mButton = (Button) findViewById(R.id.buttone);
mEdit = (EditText) findViewById(R.id.edittexte);
ll2 = (LinearLayout)findViewById(R.id.llayout);
// Check the preference value when activity is launched each time and hide of the button was pressed before
if(pref.getBoolean("ButtonPressed", false)) ll2.setVisibility(View.GONE);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
number = mEdit.getText().toString();
mEdit.setText("");
// Save the sate of the button pressed in the SharedPreference
pref.edit().putBoolean("ButtonPressed", true).apply();
ll2.setVisibility(View.GONE);
}
});
}
You can try saving a boolean in SharedPreferences...
For e.g.
Keep the boolean as false in the beginning.
As soon as you press the button, remove the View (LinearLayout), change the boolean to true & save it to SharedPreferences...
In the onCreate(),
try as
if(booleanisTrue) {
ll2.setVisibility(View.GONE);
ll2.removeAllViewsInLayout();
}

How to update text field on button click?

I need help in the MainActivity.java coding such that the value of the text field is stored into a variable on button click so that i could use it for search query later.
The activity_main.xml contains the following:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:text="Search"
android:ems="10"
android:id="#+id/SearchText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button2" />
Could anyone suggest what the MainActivity.java file should contain as to recieve the text value as i am new to coding?
Add onClick on your button
onClick:"btnClicked"
Like
<Button
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button2"
android:onClick="btnClicked" />
Add these code in Java file
public void btnClicked(View view){
EditText et = (EditText)findViewById(R.id.SearchText);
String value = et.getText().toString();// your edit text value
}
//Variable to store value.
String variable;
//References to the views.
Button btnClick = (Button)findViewById(R.id.button2);
EditText etText = (EditText)findViewById(R.id.SearchText);
//Setting click to the button
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
// Do Your stuff.
variable = etText.getText().toString();
}
});
what the MainActivity.java file should contain as to receive the text value as i am new to coding?
Write This Code in Your MainActivity.java Whatever you will give in Text field and click Button , It will update and show in Toast Message.
public class MainActivity extends Activity {
EditText et;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
et = (EditText)findViewById(R.id.SearchText);
bt = (Button)findViewById(R.id.button2);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String eText = et.getText().toString();
Toast.makeText(getApplicationContext(),"Your Text is here"+eText,Toast.LENGTH_SHORT).show();
}
});
}
String YOUR_VARIABLE = "";
Button btn= (Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtText = (Edittext)findViewById(R.id.SearchText);
if(!edtText.isEmpty()){
YOUR_VARIABLE = edtText.getText().toString();
}
});
This will store your EditText text in your Variable
if you want to use That variable Globally you should make if public static
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = SearchText.getText().toString();
}
});

Android app and java activities, issues with onCreate() method and XML

I am trying use the onClick() function in an activity for an android app. So far I have:
public class Activity2 extends Activity implements OnClickListener {
private ImageButton closeButton;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
Button myButton = (Button) findViewById(R.id.wowButton);
myButton.setOnClickListener(this);
this.closeButton = (ImageButton)this.findViewById(R.id.close);
this.closeButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
finish();
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
TextView lowerText = (TextView) findViewById(R.id.textView2);
EditText boxText = (EditText) findViewById(R.id.editText1);
lowerText.setText(boxText.getText());
}
}
This is just a stripped down version of my project. When I enter my app as usual in the emualtor, everything works fine. When I click the button to open up this particular activity, everything crashes. I assume the issue lies within the onClick() method. This code was sent to me by my project partner without the XML files so I think thats where the problem lies.
here is my basic XML file that I thought should work:
<?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">
<Button android:id="#+id/wowButton" android:layout_width="fill_parent"
android:layout_height="200dp" android:text="WoW" android:typeface="sans"
android:background="#drawable/btn_default_normal_red" />
<EditText
android:id="#+id/editText1"
/>
<TextView
android:id="#+id/textView2"
/>
</LinearLayout>
While very basic, I though it should work. Thanks for your help.
you instantiate an ImageButton through this.closeButton = (ImageButton)this.findViewById(R.id.close);
But you don't declare it in the xml file. That's why it's null and throws a NullPointer Exception.

Categories

Resources