The simple app with just one activity is creating problems with finding the layout's TextView and showing the same as null. Kindly debug the same why the app is crashing on clicking the submit button. I tried many solutions in Stack Overflow and many solutions say that the view might be located outside the activity specified, but here the only one activity is there. So research didn't help me, and now I'm left with the fellow developers who could predict the fault I could have committed.
MainActivity.java
package me.thirumurugan.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button submit;
TextView result;
RadioButton answer_a;
EditText answer_b;
CheckBox answer_c1, answer_c2, answer_c3, answer_c4;
EditText answer_d;
int correct = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
answer_a = (RadioButton) findViewById(R.id.answer_a);
answer_b = (EditText) findViewById(R.id.answer_b);
answer_c1 = (CheckBox) findViewById(R.id.answer_c1);
answer_c2 = (CheckBox) findViewById(R.id.answer_c2);
answer_c3 = (CheckBox) findViewById(R.id.answer_c3);
answer_c4 = (CheckBox) findViewById(R.id.answer_c4);
answer_d = (EditText) findViewById(R.id.answer_d);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
correct = 0;
if (answer_a.isChecked()){
correct++;
}
if (answer_b.getText().toString().equals("2020")){
correct++;
}
if (answer_c1.isChecked()&&answer_c2.isChecked()&&answer_c3.isChecked()&&!answer_c4.isChecked()){
correct++;
}
if (answer_d.getText().toString().toLowerCase().equals("arun jaitley")){
correct++;
}
result.setText("The Score is " + correct + " on 4!");
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="me.thirumurugan.quiz.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/welcome_messege"
android:textAlignment="center"
android:id="#+id/result"
android:padding="#dimen/padding"
android:textStyle="bold"
android:textSize="16sp"
android:background="#color/colorAccent"
android:textColor="#FFF"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/padding"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:text="#string/question_1"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/answer_a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_a" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_b" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_2"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_b"
android:hint="#string/answer_hint"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:textSize="14sp"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_3"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<CheckBox
android:id="#+id/answer_c1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_a" />
<CheckBox
android:id="#+id/answer_c2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_b" />
<CheckBox
android:id="#+id/answer_c3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_c" />
<CheckBox
android:id="#+id/answer_c4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_d" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_4"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_d"
android:hint="#string/answer_hint"
android:textSize="14sp"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:text="#string/submit"
android:textColor="#FFFFFF"
android:textStyle="bold"
tools:targetApi="lollipop" />
</LinearLayout>
</ScrollView>
</LinearLayout>
The error message was the following in the trace:
08-10 21:58:06.301 20947-20947/me.thirumurugan.quiz E/AndroidRuntime:
FATAL EXCEPTION: main Process: me.thirumurugan.quiz, PID: 20947
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference at
me.thirumurugan.quiz.MainActivity$1.onClick(MainActivity.java:52) at
android.view.View.performClick(View.java:5637) at
android.view.View$PerformClick.run(View.java:22429) at
android.os.Handler.handleCallback(Handler.java:751) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:154) at
android.app.ActivityThread.main(ActivityThread.java:6119) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You are in need of a clean and rebuild. There is nothing wrong with your code. Multiple users have copied the code and used it to success in their applications, including myself:
Text is missing because I do not have your dimens or strings files.
You do not have a scope issue, as others have suggested. Your member variables should be accessible by any anonymous inner class you create.
There are otherwise missing lines from your shared code. In which case, the community can not resolve your problem as nobody will be capable of replicating it.
Related
I'm developing an app for users to share their books. To achieve this, I'm getting different data about the book from the user. The problem is, horizontal autoscrolling of all EditTexts are working until Dialog has been shown and dismissed. Once a dialog has been dismissed on the fragment, horizontal autoscrolling of the EditText's on this layout won't work.
I added:
android:focusable="true"
android:focusableInTouchMode="true"
to parent layout of the edittext but doesn't work.
Also to make sure that autoscrolling is enabled I've added:
android:scrollHorizontally="true"
But none of above helped.
Here is XML code of the fragment layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#color/white"
android:orientation="vertical"
android:paddingStart="#dimen/dp25"
android:paddingEnd="#dimen/dp25"
tools:context=".UI.Fragments.SharePostFragments.Fragment1.OverViewFragment">
<LinearLayout
android:id="#+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<EditText
android:id="#+id/edit_text_name_of_book"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:fontFamily="#font/segoe_ui_semi_bold"
android:hint="#string/name_of_book"
android:inputType="text"
android:maxLength="50"
android:maxLines="1"
android:scrollHorizontally="true"
android:textAlignment="textStart"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorPrimaryDark"
android:textSize="#dimen/font22" />
<TextView
android:id="#+id/text_view_number_of_characters"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginEnd="#dimen/dp10"
android:fontFamily="#font/segoe_ui_light"
android:text="#string/_0_50"
android:textColor="#color/colorAccent"
android:textSize="#dimen/font16"
tools:ignore="RtlSymmetry" />
<EditText
android:id="#+id/edit_text_name_of_author"
android:layout_width="match_parent"
android:layout_height="#dimen/textBoxHeight"
android:layout_marginTop="#dimen/dp30"
android:background="#drawable/round_text_box_gray"
android:fontFamily="#font/segoe_ui_regular"
android:hint="#string/name_of_writer"
android:inputType="text"
android:paddingStart="20dp"
android:paddingEnd="20dp"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorPrimaryDark"
android:textSize="#dimen/font16" />
<RelativeLayout
android:id="#+id/constraint_layout_1"
android:layout_width="match_parent"
android:layout_height="#dimen/textBoxHeight"
android:layout_marginTop="#dimen/dp20"
android:background="#drawable/round_text_box_border_gray"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginTop="3dp"
android:fontFamily="#font/segoe_ui_regular"
android:paddingStart="#dimen/dp20"
android:paddingEnd="#dimen/dp20"
android:text="#string/price_of_book"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/font16" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:paddingStart="#dimen/dp20"
android:paddingEnd="#dimen/dp20"
android:text="#string/azn_sign"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/font16" />
<EditText
android:id="#+id/edit_text_price_of_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toStartOf="#+id/textView2"
android:background="#color/white"
android:clickable="false"
android:hint="#string/_0_0"
android:inputType="text|numberDecimal"
android:maxLength="6"
android:singleLine="true"
android:textColorHint="#android:color/black" />
</RelativeLayout>
<LinearLayout
android:id="#+id/constraint_layout_conditions_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dp20"
android:background="#drawable/round_text_box_border_gray"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="#dimen/textBoxHeight"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="9"
android:gravity="center_vertical"
android:paddingStart="#dimen/dp20"
android:paddingEnd="#dimen/dp20"
android:text="#string/book_condition_placeholder"
android:textColor="#color/colorPrimaryDark" />
<ImageButton
android:id="#+id/image_button_conditions"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginEnd="#dimen/dp10"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:src="#drawable/ic_spinner" />
</LinearLayout>
<LinearLayout
android:id="#+id/linear_layout_conditions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="#+id/text_view_new"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/dp20"
android:paddingTop="#dimen/dp10"
android:paddingEnd="#dimen/dp20"
android:paddingBottom="#dimen/dp10"
android:text="#string/_new"
android:textColor="#color/dark_gray_text_color" />
<TextView
android:id="#+id/text_view_normal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/dp20"
android:paddingTop="#dimen/dp10"
android:paddingEnd="#dimen/dp20"
android:paddingBottom="#dimen/dp10"
android:text="#string/normal"
android:textColor="#color/dark_gray_text_color" />
<TextView
android:id="#+id/text_view_old"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/dp20"
android:paddingTop="#dimen/dp10"
android:paddingEnd="#dimen/dp20"
android:paddingBottom="#dimen/dp10"
android:text="#string/old"
android:textColor="#color/dark_gray_text_color" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/constraint_layout_languages_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dp20"
android:background="#drawable/round_text_box_border_gray"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/linear_layout_2"
android:layout_width="match_parent"
android:layout_height="#dimen/textBoxHeight"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="9"
android:gravity="center_vertical"
android:paddingStart="#dimen/dp20"
android:paddingEnd="#dimen/dp20"
android:text="#string/language"
android:textColor="#color/colorPrimaryDark" />
<ImageButton
android:id="#+id/image_button_languages"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginEnd="#dimen/dp10"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:src="#drawable/ic_spinner" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_languages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/dp20"
android:paddingEnd="#dimen/dp20"
android:paddingBottom="#dimen/dp10"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Fragment Java code:
package org.kitapp.UI.Fragments.SharePostFragments.Fragment1;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import org.kitapp.R;
import org.kitapp.UI.Dialogs.ConditionDialog.ConditionOfBookDialog;
import org.kitapp.UI.Dialogs.LanguageDialog.LanguageDialog;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
public class OverViewFragment extends Fragment implements OverViewContractor.View {
private final String TAG = OverViewFragment.class.getSimpleName();
private Context mContext;
private OverViewCallback mListener;
private OverViewPresenter mPresenter;
#BindView(R.id.constraint_layout_conditions_root)
LinearLayout conditionRoot;
#BindView(R.id.constraint_layout_languages_root)
LinearLayout languagesRoot;
#BindView(R.id.linear_layout_conditions)
LinearLayout conditions;
#BindView(R.id.root_layout)
LinearLayout rootLayout;
#BindView(R.id.text_view_number_of_characters)
TextView numberOfChars;
#BindView(R.id.edit_text_name_of_book)
EditText nameOfBook;
public interface OverViewCallback {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_over_view, container, false);
ButterKnife.bind(this, view);
new OverViewPresenter(this);
//rootLayout.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING);
return view;
}
////// CONTRACTOR METHODS //////
#Override
public void setPresenter(OverViewPresenter presenter) {
this.mPresenter = presenter;
}
////// LISTENERS //////
#Override
#OnClick(R.id.image_button_conditions)
public void showConds() {
ConditionOfBookDialog conditionOfBookDialog = new ConditionOfBookDialog(mContext);
conditionOfBookDialog.show();
}
#Override
#OnClick(R.id.image_button_languages)
public void showLangs() {
LanguageDialog languageDialog = new LanguageDialog(mContext);
languageDialog.show();
}
#Override
#SuppressLint("SetTextI18n")
#OnTextChanged(R.id.edit_text_name_of_book)
public void onNameOfBookChange() {
int len = nameOfBook.getText().toString().trim().length();
numberOfChars.setText(len + "/50");
if (len > 50) {
nameOfBook.setText(nameOfBook.getText().toString().substring(0, 50));
nameOfBook.setSelection(nameOfBook.getText().length());
}
}
////// FRAGMENT METHODS //////
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.mContext = context;
if (context instanceof OverViewCallback) {
mListener = (OverViewCallback) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OverViewCallback");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
UI Design and Dialog
In the image above, there are EditTexts Name Of Book and Name of Author. Before showing a dialog, both of them work like a charm. When writing something, the cursor automatically scrolls to the end. Once Dialog has been shown and dismissed, none of them works properly, and the cursor stays at the end of the EditText but still the characters are being written continues in the hidden part.
In this UI it cannot be seen because of the issue, but I've written.
Roses are red, violets are blue, Stackoverflow I love u
But only Roses are red, violets are blue, Stac can be seen.
Weird buggy layout UI image
Please, help me to solve this problem. Thanks in advance.
As a solution, I don't know the underlying reason, but the problem solved once I removed Butterknife library from my project.
I am quite new to android programming so thanks advance for helping.
On button click, I am trying store the boolean values and a string value into SharedPreferences. After storing it, it will update the mainActivty.xml page. However, after many tries and hours of looking up, i cannot seem to find a way to get rid of the Null Pointer Exception when trying to .setText() the string value. Any help will be much appreciated, thanks
I have tried to create an inflater since some of the issue arise with the view not getting inflated. I have also tried to reassign the location for my textView initialization but to no avail.
This is the SettingPage code:
package com.example.sleep;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class SettingPage extends AppCompatActivity{
public EditText setMinBar;
public Button setTimeEnterButton;
public Switch musicYesSwitch, soundYesSwitch;
public String SP = "New SP", timeStr = "nothing", finalTimeStr = "nil";
public boolean musicYes, soundYes;
public TextView minLeftTV, timerEndsTV;
public SharedPreferences varAcrossApp;
public SharedPreferences.Editor varEditor;
#Override //Creating the setting page
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settingpage);
setMinBar = findViewById(R.id.numMinsBar);
setTimeEnterButton = findViewById(R.id.setTimeButton);
musicYesSwitch = findViewById(R.id.musicSwitch);
soundYesSwitch = findViewById(R.id.soundSwitch);
timerEndsTV = findViewById(R.id.timerEndsTV);
minLeftTV = (TextView) findViewById(R.id.minsLeftDisplay);
varAcrossApp = PreferenceManager.getDefaultSharedPreferences(this);
setTimeEnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
loadData();
updateView();
}
});
}
public void saveData(){ //Declaring method saveData
varEditor = varAcrossApp.edit();
varEditor.putString(timeStr, setMinBar.getText().toString());
varEditor.putBoolean("mYes", musicYesSwitch.isChecked());
varEditor.putBoolean("sYes", soundYesSwitch.isChecked());
varEditor.apply();
}
public void loadData(){ //Declaring method loadData
finalTimeStr = varAcrossApp.getString(timeStr, "0");
musicYes = varAcrossApp.getBoolean("mYes", false);
soundYes = varAcrossApp.getBoolean("sYes", false);
Toast.makeText(getApplicationContext(), "Duration set" +
finalTimeStr, Toast.LENGTH_SHORT).show();
}
public void updateView() {
Log.d(SP, "Time is " + finalTimeStr);
minLeftTV.setText(finalTimeStr);
if (musicYes && soundYes) {
timerEndsTV.setText("-Turn off music /n-Change sound profile to
'Sound'");
} else if (soundYes = true) {
timerEndsTV.setText("-Change sound profile to 'Sound'");
} else if (musicYes = true) {
timerEndsTV.setText("-Turn off music");
} else {
timerEndsTV.setText("-Do nothing");
}
}
}
This is the Homepage.xml page
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/homepage"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<TextView
android:id="#+id/timeLeft"
android:layout_width="191dp"
android:layout_height="49dp"
android:layout_marginStart="146dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="147dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_header"
android:textAlignment="center"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/timeLeftNum"
android:layout_width="84dp"
android:layout_height="52dp"
android:layout_marginTop="143dp"
android:layout_marginEnd="103dp"
android:layout_marginBottom="138dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_timeUnit"
android:textAlignment="center"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/timerEndsTV"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/timeLeft" />
<TextView
android:id="#+id/whenTimerEnd"
android:layout_width="132dp"
android:layout_height="20dp"
android:layout_marginStart="54dp"
android:layout_marginEnd="253dp"
android:layout_marginBottom="12dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_whenTimerEnd"
android:textAlignment="viewStart"
app:layout_constraintBottom_toTopOf="#+id/timerEndsTV"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/timerEndsTV"
android:layout_width="299dp"
android:layout_height="54dp"
android:layout_marginStart="54dp"
android:layout_marginEnd="58dp"
android:layout_marginBottom="114dp"
android:fontFamily="#font/bree_serif"
android:text="TextView"
app:layout_constraintBottom_toTopOf="#+id/startButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/startButton"
android:layout_width="382dp"
android:layout_height="52dp"
android:layout_marginStart="13dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_startButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/minsLeftDisplay"
android:layout_width="155dp"
android:layout_height="144dp"
android:layout_marginStart="68dp"
android:layout_marginTop="56dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="107dp"
android:text="#string/numberInDisplay"
android:textAlignment="textEnd"
android:textSize="125sp"
app:layout_constraintBottom_toTopOf="#+id/whenTimerEnd"
app:layout_constraintEnd_toStartOf="#+id/timeLeftNum"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/timeLeft" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the SettingPage.xml page:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/settingPageConstrainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/inputLayout"
android:layout_width="299dp"
android:layout_height="81dp"
android:layout_marginStart="56dp"
android:layout_marginEnd="56dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/TextboxDurationMins">
<EditText
android:id="#+id/numMinsBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/setTimeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/bree_serif"
android:text="#string/setTimeButton" />
</LinearLayout>
<LinearLayout
android:id="#+id/switchesLayout"
android:layout_width="64dp"
android:layout_height="69dp"
android:layout_marginEnd="32dp"
android:layout_marginBottom="218dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<Switch
android:id="#+id/musicSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Switch
android:id="#+id/soundSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#+id/textBoxLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="56dp"
android:layout_marginEnd="69dp"
android:layout_marginBottom="230dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/switchesLayout"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/turnOffMusics"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/bree_serif"
android:text="#string/offMusic"
android:textAlignment="textStart"
android:textSize="18sp" />
<TextView
android:id="#+id/onSound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/bree_serif"
android:text="#string/onSound"
android:textAlignment="textStart"
android:textSize="18sp" />
</LinearLayout>
<TextView
android:id="#+id/TextboxDurationMins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="176dp"
android:layout_marginEnd="120dp"
android:fontFamily="#font/bree_serif"
android:text="#string/setDurationMins"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the error code:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sleep, PID: 16835
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null object
reference
at com.example.sleep.SettingPage.updateView(SettingPage.java:82)
at com.example.sleep.SettingPage$1.onClick(SettingPage.java:53)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3400(View.java:801)
at android.view.View$PerformClick.run(View.java:27301)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
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:934)
The issue is related to minLeftTV.setText(finalTimeStr);
You are creating an instance by calling
minLeftTV = (TextView) findViewById(R.id.minsLeftDisplay);
but your xml layout does not have any view with that id - #+id/minsLeftDisplay and hence minLeftTV is null and you are getting a null pointer exception.
You have a TextView with id => #+id/TextboxDurationMins which is the view you want to set the text to (I am assuming). Change the id in layout or your activity code.
The app is supposed to call one screen from another and use the other screen's layout components. Whenever I try to call a component, such as ImageButton, it says that member id is unknown, I told my teacher and he says that it shouldn't happen. I have tried renaming the components and even made a new project.
How can I fix it?
the error is in R.id
package com.movil.ejemploventanas;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
public class DatosPersonales extends Activity {
EditText vEdtNom,vEdtEdad;
ImageButton vBtnOrigen,vBtnSantuario;
Intent intnEnvio;
Bundle bndContenedorEnvio;
String strNom;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.datospersonales);
vEdtNom=(EditText)findViewById(R.id.edtNom);
vEdtEdad=(EditText)findViewById(R.id.edtEdad);
vBtnOrigen=(ImageButton)findViewById(R.id.btnOrigen);
vBtnSantuario=(ImageButton)findViewById(R.id.btnSantuario);
intnEnvio=new Intent(DatosPersonales.this,Caracteristicas.class);
bndContenedorEnvio=new Bundle();
vBtnOrigen.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
strNom=vEdtNom.getText().toString();
bndContenedorEnvio.putString("nom",strNom);
bndContenedorEnvio.putString("edad", vEdtEdad.getText().toString());
bndContenedorEnvio.putString("opc","1");
intnEnvio.putExtras(bndContenedorEnvio);
startActivity(intnEnvio);
}
});
vBtnSantuario.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
strNom=vEdtNom.getText().toString();
bndContenedorEnvio.putString("nom",strNom);
bndContenedorEnvio.putString("edad",vEdtEdad.getText().toString());
bndContenedorEnvio.putString("opc","2");
intnEnvio.putExtras(bndContenedorEnvio);
startActivity(intnEnvio);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txtLetrero"
style="style/titulo"
android:layout_centerHorizontal="true"
android:text="#string/letMariposa"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/txtLetrero"
android:id="#+id/linearlayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp">
<TextView
android:id="#+id/txtNom"
style="style/letreros"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="string/nom"/>
<EditText
android:id="#+id/edtNom"
style="style/datos"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:inputType="textPersonName"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:id="#+id/linearlayout2"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/txtEdad"
style="style/letreros"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="#string/edad"
android:textAlignment="gravity"/>
<EditText
android:id="#+id/edtEdad"
style="style/datos"
android:layout_width="220dp"
android:ems="10"
android:layout_height="wrap_content"
android:inputType="number"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/origen"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/linearLayout2"
android:layout_marginLeft="30dp"
android:layout_marginTop="200dp"
android:id="#+id/textView4"
style="style/letreros"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_below="#id/textView4"
android:layout_marginLeft="80dp"
android:id="#+id/btnOrigen"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sant"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/btnOrigen"
android:layout_marginLeft="120dp"
android:id="#+id/textView5"
style="style/letreros"/>
<ImageButton
android:id="#+id/btnSantuario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView5"
android:layout_marginLeft="180dp"/>
</RelativeLayout>
I am making a simple app in which context view changes and then a toast message is displayed as input given by user. I don't understand why the app keeps on crashing when changing the context view.
Also Android studio gives this warning:
Method "Toaster" is missing in "FirstActivity" or has incorrect signature.
Here is my code:
activity_me_clicked.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/welcome"
android:textSize="36sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:paddingLeft="7dp"
android:paddingRight="7dp"
android:text="#string/intro"
android:textSize="24sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="7dp"
android:layout_marginEnd="7dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/named"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:onClick="MainProcess"
android:text="#string/done" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal"
tools:ignore="UselessLeaf"></LinearLayout>
</LinearLayout>
</LinearLayout>
FirstActivity.Java:
package com.example.nautatvanavlakha.abcd;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class FirstActivity extends AppCompatActivity {
public static String owner_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_me_clicked);
}
public void MainProcess(View view) {
final String TAG="DEBUG";
Log.d(TAG,"At least process started");
EditText owner = (EditText) findViewById(R.id.name);
owner_string = owner.getText().toString();
Log.d(TAG,"owner name stored");
TextView textView = (TextView) findViewById(R.id.welcome);
textView.setText("Hi " + owner_string + ".");
Log.d(TAG,"owner name is set");
setContentView(R.layout.activity_main_screen);
Log.d(TAG,"content shown");
}
}
activity_main_screen.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:id="#+id/welcome"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/what_would_you_like_me_to_do_today"
android:textSize="18sp" />
<Button
android:id="#+id/Cam"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:padding="0dp"
android:paddingTop="15dp"
android:text="#string/camera" />
<Button
android:id="#+id/Mus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:padding="0dp"
android:paddingTop="15dp"
android:text="#string/music" />
<Button
android:id="#+id/QR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:padding="0dp"
android:paddingTop="15dp"
android:text="#string/scanQR" />
<EditText
android:id="#+id/toastText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/order"
android:inputType="textPersonName" />
<Button
android:id="#+id/toaster"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:onClick="toaster"
android:padding="0dp"
android:paddingTop="15dp"
android:text="#string/toast"
android:layout_marginEnd="100dp"
android:layout_gravity="center"/>
</LinearLayout>
MainScreen.java:
package com.example.nautatvanavlakha.abcd;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
}
public void toaster(View view){
EditText toast = (EditText)findViewById(R.id.toastText);
String final_toast = toast.getText().toString();
Toast.makeText(getApplicationContext(), final_toast, Toast.LENGTH_SHORT).show();
}
}
EDIT: As suggested, I moved the toaser function to FirstActivity.Java and deleted the MainScreen.java file as it becomes pointless to keep it. But the major problem is when I press the button (id named) the app keeps stopping.
EDIT2: I found that setContentView(R.layout.activity_main_screen) in FirstActivity.Java needs to be above this code
TextView textView = (TextView) findViewById(R.id.welcome);
textView.setText("Hi " + owner_string + ".");
Log.d(TAG,"owner name is set");
so that Activity has access to all the layout components. Thanks solved :)
You replaced the content view in the first activity with a layout that include the onClick attribute, but you have no public void toaster(View view) method there.
So, either don't use setContentView a second time, or implement that method on both Activities.
The recommended way to replace the view is Fragments, by the way
This is a wrong way to change the contents of your Activity, The main problem here is that you have onClick attribute set to "toaster", And you don't have a function called "toaster" in your FirstActivity.
Beside that, The MainScreen Activity in your code will never be used.
So, Your problem is that you set the FirstActivity contents to "activity_main_screen.xml", And FirstActivity doesn't have "toaster" method in it, When you change the context, the Activity will try to find toaster method and the app will crash because the method doesn't exist in FirstActivity.
You can solve this problem by making a method called "toaster" inside FirstActivity, But
This is a very bad practice, You can use Fragments instead, Or you can use Intent to move to another activity.
Some useful links about Fragments:
https://developer.android.com/guide/components/fragments.html
https://www.tutorialspoint.com/android/android_fragments.htm
https://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/
Why should I use fragment in Android?
I am new to Android and programming and having a bit of difficulties with my code. I tried to research this but couldn't find out what was wrong, would appreciate the help. I am basically trying to multiply two values but every time I run my emulator and click on the button (calculate) it crashes:
Java Code:
package com.example.cantcook;
import java.math.BigDecimal;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends Activity {
EditText costofmeal, amountofpeople;
TextView costperperson;
Button Calculate;
BigDecimal costNum, percentNum;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
costofmeal = (EditText) findViewById(R.id.editText1);
amountofpeople = (EditText) findViewById(R.id.editText2);
Calculate = (Button) findViewById(R.id.button1);
costperperson = (TextView) findViewById(R.id.textView2);
//costperperson.setText("£0.00");
Calculate.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v)
{
costNum = new BigDecimal(costofmeal.getText().toString());
percentNum = new BigDecimal(amountofpeople.getText().toString());
costperperson.setText(costNum.multiply(percentNum).toString());
}
});
}
XML code:
<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:background="#drawable/background"
tools:context=".Calculator" >
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:text="£"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="112dp"
android:text=" Total spent on Shopping"
android:textAlignment="center"
android:textSize="18dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text=" Amount of People"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_marginBottom="25dp"
android:onClick="Btncalculate"
android:text="Calculate" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="numberSigned" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="numberDecimal"
android:text="£" />
</RelativeLayout>
In your xml layout you have android:onClick="Btncalculate" in button1. What this does is when a click happens Android tries to look for Btncalculate method in your activity. And I'm assuming you don't have it there, since you're using an OnClickListener for button1(which, in my opinion, is better then using android:onClick).
Remove android:onClick="Btncalculate" from the xml file and it should work(unless there are other errors, in which case it would be great to see the stack trace).
Update
From your stacktrace:
java.lang.NumberFormatException: £5
Looks like you're code is trying to put "£5" into BigDecimal, which is not allowed, since it is not a number. To fix this you can either set android:inputType to a number in your editText1 and remove android:text="£", or use a separate method to filter out the £ sign from input.