Error getting in button click event in android [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm generating a click event in android and i used wrote the code in this way
public class LoginActivity extends AppCompatActivity {
Button btnLogin;
EditText inputEmail,inputPassword;
protected String enteredEmail;
String enteredPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// inputEmail = (EditText) findViewById(R.id.email);
// inputPassword = (EditText) findViewById(R.id.password);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
}});}
but getting the below error
TextInputLayout: EditText added is not a TextInputEditText. Please
> switch to using that class instead. 03-11 01:41:52.214
> 21936-21936/com.example.smartlayer.myhive_app I/TextInputLayout:
> EditText added is not a TextInputEditText. Please switch to using that
> class instead. 03-11 01:41:52.294
> 21936-21936/com.example.smartlayer.myhive_app D/AndroidRuntime:
> Shutting down VM 03-11 01:41:52.294
> 21936-21936/com.example.smartlayer.myhive_app W/dalvikvm: threadid=1:
> thread exiting with uncaught exception (group=0xb4ae3ba8) 03-11
> 01:41:52.334 21936-21936/com.example.smartlayer.myhive_app
> E/AndroidRuntime: FATAL EXCEPTION: main
> Process: com.example.smartlayer.myhive_app, PID: 21936
> java.lang.RuntimeException: Unable to start activity
How i solve this error ?

You are missing to initialize Button
btnLogin = (Button) findViewById(R.id.Set_Button_Id);
Like
btnLogin = (Button) findViewById(R.id.Set_Button_Id);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
}});}

Related

I have a problem when I try to use a variable from a getStringArrayListExtra()

When I use getStringArrayListExtra() to transport a variable from SecondActivity to the MainActivity, and when I use the variable, my app always crash. This is the code where there is a problem :
in MainActivity :
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}
}
in SecondActivity :
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
ArrayList tag = new ArrayList();
EditText edit;
Button button;
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
edit = (EditText) findViewById(R.id.edit);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
tag.add(name);
Toast.makeText(getApplicationContext(), tag.toString(), Toast.LENGTH_SHORT).show();
}
});
Button button2;
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
Button button3;
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
startActivity(retourgameActivity);
}
});
}
}
Thank you so much for your help !
EDIT:
This is the error log (logcat):
021-06-24 15:43:16.734 11451-11451/fr.apprentissage.version2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.apprentissage.version2, PID: 11451
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.apprentissage.version2/fr.apprentissage.version2.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at fr.apprentissage.version2.MainActivity.onCreate(MainActivity.java:158)
at android.app.Activity.performCreate(Activity.java:8086)
at android.app.Activity.performCreate(Activity.java:8074)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3755)
You are starting MainActivity from SecondActivity without any extras.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
//add arraylist here in intent
retourgameActivity .putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
}
});
//in your second activity ,make sure you have extras in intent.
if(getIntent!=null && getIntent().getStringArrayListExtra("tag")!=null){
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}}
You are initiating an arraylist and before populating list you are sending it to your MainActivity.So you are passing null list to MainActivity. You should pass your list to other activity on button click.
Just do this inside your button3 listener:
Intent retourgameActivity = new Intent(MainActivity.this, SecondActivity.class);
retourgameActivity.putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
Remove
retourgameActivity.putStringArrayListExtra("tag", tag);
from here
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
Good Practices:
Always put null check before sending arraylist to other activity and also check null before using arraylist.size() or getting some indexes of arralist.

I am trying to use sharedPreferences from my Register Page and retrieve it on another class, but it is giving me error in the logcat

I entered my username here and saved as pref in sharedPreferences
private void saveUserName(){
String userName = mUsernameView.getText().toString();
SharedPreferences prefs = getSharedPreferences(PREFS, 0);
prefs.edit().putString(DISPLAY_NAME_KEY, userName).apply();
}
Retrieving it here and trying to saved it to a textview but getting error
private void setUserName(){
String mSetUserName;
SharedPreferences prefs = getSharedPreferences(RegisterClass.PREFS, MODE_PRIVATE);
mSetUserName = prefs.getString(RegisterClass.DISPLAY_NAME_KEY, null);
if (mSetUserName == null) mSetUserName ="Anonymous";
userName.setText(mSetUserName);
The error is pointing to where i used the setText on my username, saying it is pointing to a null value, which is untrue, I registered with a user name.
FATAL EXCEPTION: main
Process: com.onyebuchboss.bossweatherbitcoinapp, PID: 1553
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.onyebuchboss.bossweatherbitcoinapp/com.onyebuchboss.bossweatherbitcoinapp.OptionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2743)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1544)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6293)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1094)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.onyebuchboss.bossweatherbitcoinapp.OptionActivity.setUserName(OptionActivity.java:84)
at com.onyebuchboss.bossweatherbitcoinapp.OptionActivity.onCreate(OptionActivity.java:36)
I declared the userName in the onCreate method here
mWeatherBtn = (Button) findViewById(R.id.weatherAppButton);
mBitcoinBtn = (Button) findViewById(R.id.bitcoinAppButton);
userName = (TextView) findViewById(R.id.userName);
shareBtn = (Button) findViewById(R.id.shareBtn);
The Xml filefor the userName
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/default_name"
android:textSize="20dp"/>
<Button
android:id="#+id/weatherAppButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/bitcoinAppButton"
android:layout_alignLeft="#+id/bitcoinAppButton"
android:layout_alignStart="#+id/bitcoinAppButton"
android:layout_marginBottom="86dp"
android:background="#android:color/black"
android:text="#string/change_for_WeatherApp"
android:textColor="#android:color/white"
android:textSize="40sp"/>
Entire code for OptionActivity
public class OptionActivity extends AppCompatActivity {
Button mWeatherBtn;
Button mBitcoinBtn;
TextView userName;
Button shareBtn;
String TAG = "Weather & Bitcoin App";
String shareString = "Please download this Awesome App";
//private String mSetUserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.option_layout);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
setUserName();
mWeatherBtn = (Button) findViewById(R.id.weatherAppButton);
mBitcoinBtn = (Button) findViewById(R.id.bitcoinAppButton);
userName = (TextView) findViewById(R.id.userName);
shareBtn = (Button) findViewById(R.id.shareBtn);
mWeatherBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent weatherIntent = new Intent(OptionActivity.this, WeatherActivity.class);
//finish();
startActivity(weatherIntent);
}
});
mBitcoinBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent bitcoinIntent = new Intent(OptionActivity.this, BitcoinActivity.class);
startActivity(bitcoinIntent);
}
});
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, TAG);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
startActivity(shareIntent);
}
});
}
//Retrieve the user name from shared preferences
private void setUserName(){
String mSetUserName;
SharedPreferences prefs = getSharedPreferences(RegisterClass.PREFS, MODE_PRIVATE);
mSetUserName = prefs.getString(RegisterClass.DISPLAY_NAME_KEY, null);
if (mSetUserName == null) mSetUserName ="Anonymous";
userName.setText(mSetUserName);
}
}
Move setUserName() below declaration, right now you are calling settext on userName before initialising it
mWeatherBtn = (Button) findViewById(R.id.weatherAppButton);
mBitcoinBtn = (Button) findViewById(R.id.bitcoinAppButton);
userName = (TextView) findViewById(R.id.userName);
shareBtn = (Button) findViewById(R.id.shareBtn);
setUserName();

Move from One Tab to Another Tab on click event [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have created an app with 5 tabs, in my 1st tab I am having a button on click of which I want to go to tab3. This is my code of button event --
moreButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(view.getContext(), Tab3_Image.class);
view.getContext().startActivity(intent);
}
});
But while clicking the button the app crash, below is the logcat error --
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.s2s.doupnow, PID: 22481
java.lang.NullPointerException
at com.s2s.doupnow.Tab1_Home$6.onClick(Tab1_Home.java:313)
at android.view.View.performClick(View.java:4444)
at android.view.View$PerformClick.run(View.java:18457)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5113)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)
Change this -:
moreButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(view.getContext(), Tab3_Image.class);
view.getContext().startActivity(intent);
}
});
To-:
private Context context=this; //make it global
Button moreButton3=(Button)findViewById(R.id.buttoninxml);
moreButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Tab3_Image.class);
startActivity(intent);
}
});

Exception when trying to send a message to firebase server

Can you please find out what is wrong with this code?
public class NewMessageActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
String mDisplayName = "John";
EditText mNewMessageField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EditText mNewMessageField = (EditText) findViewById(R.id.newMessageText);
setContentView(R.layout.activity_new_message);
ImageButton mSendButton = (ImageButton) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
finish();
}
});
}
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
String input = mNewMessageField.getText().toString();
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}
}
Immediately after I press the send button, the app stops working and I get this error message:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com..NewMessageActivity.sendMessage(NewMessageActivity.java:42)
at com..NewMessageActivity.access$000(NewMessageActivity.java:14)
at com.***.NewMessageActivity$1.onClick(NewMessageActivity.java:33)
at android.view.View.performClick(View.java:4209)
at android.view.View$PerformClick.run(View.java:17457)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
at dalvik.system.NativeStart.main(Native Method)
11-28 20:05:51.566 508-527/? E/AppErrorDialog: Failed to get ILowStorageHandle instance
You need to call setContentView() before you search for the EditText widget. You also must use the instance of mNewMessageField declared at package level. Don't declare a new instance in onCreate().
setContentView(R.layout.activity_new_message);
mNewMessageField = (EditText) findViewById(R.id.newMessageText); // <= CHANGED
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
To get more clues, add this debug output:
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
Editable ed = mNewMessageField.getText();
if (ed == null) {
System.out.println("Editable is NULL");
}
String input = mNewMessageField.getText().toString();
System.out.println("input=" + input);
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}

My simple "counter app" crashes when trying to move to another activity...why?

When trying to move to another activity the app crashes...
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{myact.julianhernandez.com.counterapp/myact.julianhernandez.com.counterapp.CounterDisplay}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:244)
at android.widget.TextView.setText(TextView.java:3888)
at myact.julianhernandez.com.counterapp.CounterDisplay.onCreate(CounterDisplay.java:31)
at android.app.Activity.performCreate(Activity.java:5231)
MainActivity.class Code
public class MainActivity extends AppCompatActivity {
Button moveActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moveActivity = (Button) findViewById(R.id.list1_button);
moveActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toCounter = new Intent(MainActivity.this , CounterDisplay.class);
startActivity(toCounter);
}
});
CounterDisplay.class Code
public class CounterDisplay extends AppCompatActivity {
private TextView countView;
private Button addButton;
private Button subtractButton;
//int initialCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter_display);
countView = (TextView) findViewById(R.id.currentCount);
addButton = (Button) findViewById(R.id.add);
subtractButton = (Button) findViewById(R.id.subtract);
countView.setText(0);
//increment counter by 1
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount;// = initialCount;
for(currentCount=0;currentCount>=0;currentCount++){
countView.setText(currentCount);
}
}
});
}
}
Why does this code crash when switching activities?
Textview.setText(int) method takes a resource ID, not the text you are trying to display. Because there are no resource strings matching the ID you pass in (which is 0 on line 31), an exception gets thrown.
There are additional overloads of the setText() method that allow you to pass in a char[] if you don't want to use resource strings. View the documentation for more information. http://developer.android.com/reference/android/widget/TextView.html

Categories

Resources