RecyclerView's onClick method crashes the app - java

Below is my MainActivity.java (I have removed some of unnecessary code. My main activity was a Navigation Viewer activity)
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<MainStoryTile> list = new ArrayList<MainStoryTile>();
int[] image_id = { R.drawable.sample, R.drawable.sample, R.drawable.sample};
String[] name, email, mobile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = getResources().getStringArray(R.array.person_name);
email = getResources().getStringArray(R.array.person_email);
mobile = getResources().getStringArray(R.array.person_mobile);
int count = 0;
for(String NAME: name){
MainStoryTile contact = new MainStoryTile(image_id[count], NAME, email[count], mobile[count]);
count++;
list.add(contact);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new MainStoryAdapter(list);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
return true;
}
}
Below is my Adapter class. (Note : there is an inner class)
public class MainStoryAdapter extends RecyclerView.Adapter<MainStoryAdapter.StoryViewHolder>{
ArrayList<MainStoryTile> contacts = new ArrayList<MainStoryTile>();
public MainStoryAdapter(ArrayList<MainStoryTile> contacts){
this.contacts = contacts;
}
#Override
public StoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main,parent,false );
StoryViewHolder storyViewHolder = new StoryViewHolder(view);
return storyViewHolder;
}
#Override
public void onBindViewHolder(StoryViewHolder holder, int position) {
MainStoryTile CON = contacts.get(position);
holder.person_img.setImageResource(CON.getImage_id());
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
holder.person_mobile.setText(CON.getMobile());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class StoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView person_img;
TextView person_name, person_email, person_mobile;
public StoryViewHolder(View view){
super(view);
person_img = (ImageView) view.findViewById(R.id.person_image);
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
person_mobile = (TextView) view.findViewById(R.id.person_mobile);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d("MY LOG", "sdurfhiusrhdidysdysdysdysdys r");
}
}
}
When I click on a item, my app crashes. below is error log :
03-17 15:20:38.638 28744-28744/com.storyteller.pro.storyteller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.storyteller.pro.storyteller, PID: 28744
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4286)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4277)
at android.view.ViewGroup.addView(ViewGroup.java:4127)
at android.view.ViewGroup.addView(ViewGroup.java:4068)
at android.view.ViewGroup.addView(ViewGroup.java:4041)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:247)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:114)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
03-17 15:20:43.048 28744-28744/com.storyteller.pro.storyteller I/Process: Sending signal. PID: 28744 SIG: 9
Update: Even after I commented the following line in the view.setOnClickListener(this); in the MainStoryAdapter, my app still crashing when I click on an item.
Below is the project for those who like to see more > project zip version

I checked your project and you, why ever, define android:onClick="setContentView" in your content_main.xml layout for the CardView.
Remove that attribute and it works.

Related

Android Studio - (java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ChildEventListener')

I am trying to retrieve data from Firebase real time db to display in RecyclerView of Android Studio, however after running the app on emulator, it only managed to display 1 row of data so i checked the logcat and this is the error
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.test/com.example.test.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'com.google.firebase.database.ChildEventListener
com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)'
on a null object reference
I am only attempting to retrieve the hawker's name and description for now
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseReference ref;
private FirebaseRecyclerOptions<Hawker> options;
private FirebaseRecyclerAdapter<Hawker, myViewHolder> adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ref = FirebaseDatabase.getInstance().getReference().child("hawkers");
recyclerView=findViewById(R.id.recycler);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
options = new FirebaseRecyclerOptions.Builder<Hawker>().setQuery(ref, Hawker.class).build();
adapter = new FirebaseRecyclerAdapter<Hawker, myViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull Hawker model) {
holder.textViewID.setText(model.getName());
holder.textViewName.setText(model.getDescription());
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_layout,parent,false);
return new myViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
}
myViewHolder.java
public class myViewHolder extends RecyclerView.ViewHolder{
TextView textViewID, textViewName;
public myViewHolder(#NonNull View itemView) {
super(itemView);
textViewID = itemView.findViewById(R.id.textViewID);
textViewName = itemView.findViewById(R.id.textViewName);
}
}
Hawker.java
public class Hawker {
private String name;
private String description;
public Hawker() {
}
public Hawker(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
the full error in logcat
2021-03-05 00:24:30.691 6466-6466/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test, PID: 6466
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ChildEventListener com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ChildEventListener com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)' on a null object reference
at com.firebase.ui.database.FirebaseArray.onCreate(FirebaseArray.java:54)
at com.firebase.ui.common.BaseObservableSnapshotArray.addChangeEventListener(BaseObservableSnapshotArray.java:97)
at com.firebase.ui.database.FirebaseRecyclerAdapter.startListening(FirebaseRecyclerAdapter.java:52)
at com.example.test.MainActivity.onCreate(MainActivity.java:67)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
2021-03-05 00:24:30.703 6466-6466/? I/Process: Sending signal. PID: 6466 SIG: 9
Output in emulator
These are the data in firebase
i think you need to check whether your Hawker class is matched with the data in firebase or not, the attribute name and number of attributes in your java class should match to the firebase

How to fix 'IllegalStateException' (fatal exception) in android studio?

I am new to Android Studio and trying to build a calculator which performs addition. On executing the app on my phone there is an error which says 'IllegalStateException' and there is a message displayed on my phone saying that has app has stopped working. Some help please.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v) throws IllegalStateException
{
EditText e1 = (EditText)findViewById(R.id.editText1);
EditText e2 = (EditText)findViewById(R.id.editText2);
TextView t1 = (TextView)findViewById(R.id.view);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int RESULT = num1+num2;
t1.setText(Integer.toString(RESULT));
}
}
The stack trace after running after entering the values
--------- beginning of crash
2019-07-16 11:02:03.122 14400-14400/com.example.calculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.calculator, PID: 14400
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:5675)
at android.view.View$PerformClick.run(View.java:22646)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1075)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5675) 
at android.view.View$PerformClick.run(View.java:22646) 
at android.os.Handler.handleCallback(Handler.java:836) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1075) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) 
Caused by: java.lang.ClassCastException: android.view.View cannot be cast to android.widget.TextView
at com.example.calculator.MainActivity.onButtonClick(MainActivity.java:22)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:5675) 
at android.view.View$PerformClick.run(View.java:22646) 
at android.os.Handler.handleCallback(Handler.java:836) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1075) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) 
This is the error:
java.lang.ClassCastException: android.view.View cannot be cast to
android.widget.TextView at
com.example.calculator.MainActivity.onButtonClick(MainActivity.java:22)
in this line:
TextView t1 = (TextView)findViewById(R.id.view);
because R.id.view is the id of a View, not a TextView (check your layout xml).
You need to make that view a textview in your layout file.
try this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View view){
EditText e1 = view.findViewById(R.id.editText1);
EditText e2 = view.findViewById(R.id.editText2);
TextView t1 = view.findViewById(R.id.view);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int result = num1+num2;
t1.setText(Integer.toString(result));
}
}

My app is crashing when I try to go to another activity

I'm trying to make a clickable image button redirect to the mainactivity
But since I've putted this code, the app crash when I click on the button to go to the 2nd Activity.
This id the first time I'm making an application.
Activity_good.java
public class Activity_good extends AppCompatActivity {
private Button backGood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_good);
final TextView txtBien = (TextView) findViewById(R.id.txtBien);
Button genBien = (Button) findViewById(R.id.genBien);
final String[] pBien={"« Pour réussir, votre désir de réussite doit être plus grand que votre peur de l’échec. » Bill Cosby", "trql", "oui", "non"};
genBien.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int rando = (int) (Math.random()*4);
txtBien.setText(pBien[rando]);
}
});
backGood = (Button) findViewById(R.id.backGood);
backGood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity();
}
});
}
public void openMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer pianoman = MediaPlayer.create(this, R.raw.piano);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pianoman.start();
openActivity_good();
}
});
}
public void openActivity_good() {
Intent intent = new Intent(this, Activity_good.class);
startActivity(intent);
}
}
Crash log ?
E/MediaPlayer: error (1, -19)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.gab.artapp, PID: 9016
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.gab.artapp/fr.gab.artapp.Activity_good}: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at fr.gab.artapp.Activity_good.onCreate(Activity_good.java:30)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Application terminated.
I exprected to to get back on mainactivity when I click on the button backGood.+
Change this line:
backGood = (Button) findViewById(R.id.backGood);
To this:
backGood = (AppCompatImageButton) findViewById(R.id.backGood);
You are casting a AppCompatImageButton as a Button.

App Crashing - java.lang.IllegalStateException: Could not execute method for android:onClick [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 5 years ago.
My app is crashing everytime I try to click a button that inputs text into a listView, I am getting the "java.lang.IllegalStateException: Could not execute method for android:onClick"; I've tried other solutions to the problem but I can't seem to find my own solution. Any help is appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> arrayList;
ArrayAdapter<String> arrayAdapter;
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean isFirstStart = getPrefs.getBoolean("started",true);
if(isFirstStart)
{
startActivity(new Intent (MainActivity.this,Intro.class));
SharedPreferences.Editor e = getPrefs.edit();
e.putBoolean("started", false);
e.apply();
}
}
});
thread.start();
listView = (ListView) findViewById(R.id.ListView);
arrayList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditMessageClass.class);
intent.putExtra(Intent_Constants.INTENT_INFO_DATA,arrayList.get(position).toString());
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION,position);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE_2);
}
});
}
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditFieldClass.class);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode==Intent_Constants.INTENT_REQUEST_CODE){
infoText = data.getStringExtra(Intent_Constants.INTENT_INFO_FIELD);
arrayList.add(infoText);
arrayAdapter.notifyDataSetChanged();
}
else if(resultCode==Intent_Constants.INTENT_REQUEST_CODE_2){
infoText = data.getStringExtra(Intent_Constants.INTENT_CHANGED_INFO);
position = data.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
arrayList.remove(position);
arrayList.add(position,infoText);
arrayAdapter.notifyDataSetChanged();
}
}
}
Intent_Constants.java
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE=1;
public final static int INTENT_RESULT_CODE=1;
public final static int INTENT_REQUEST_CODE_2=2;
public final static int INTENT_RESULT_CODE_2=2;
public final static String INTENT_INFO_FIELD="info_field";
public final static String INTENT_INFO_DATA="info_data";
public final static String INTENT_ITEM_POSITION="item_position";
public final static String INTENT_CHANGED_INFO="changed_info";
EditMessageClass.java
public class EditMessageClass extends AppCompatActivity {
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
Intent intent = getIntent();
infoText = intent.getStringExtra(Intent_Constants.INTENT_INFO_DATA);
position = intent.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
EditText infoData = (EditText) findViewById(R.id.info);
infoData.setText(infoText);
}
public void saveButtonClicked(View v){
String changedinfoText = ((EditText)findViewById(R.id.info)).getText().toString();
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_CHANGED_INFO,changedinfoText);
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION, position);
setResult(Intent_Constants.INTENT_RESULT_CODE_2,intent);
finish();
}
}
EditFieldClass.java
public class EditFieldClass extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
}
public void saveButtonClicked(View v){
String infoText = ((EditText)findViewById(R.id.info)).getText().toString();
if(infoText.equals("")){
}
else{
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_INFO_FIELD,infoText);
setResult(Intent_Constants.INTENT_RESULT_CODE,intent);
finish();
}
}
}
Logs
FATAL EXCEPTION: main
Process: gabriel.com.prototype, PID: 15435
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
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) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
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) 
According to your logcat message, I can say that your EditText object is null
the problem is caused by this line.
((EditText)findViewById(R.id.info)).getText().toString()
Make sure you have EditText with id 'info' in EditFieldClass.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
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)
your EditText is null , check editText id .

NullPointerException: Attempt to invoke virtual method ... on a null object reference [duplicate]

This question already has answers here:
Can not find a View with findViewById()
(4 answers)
Closed 6 years ago.
When I start my SettingsActivity, I get the following Error, but I don't know why, because I have done everything as always.
ERROR:
FATAL EXCEPTION: main Process: com.android.niklasvlach.vertretung, PID: 9175
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.niklasvlach.vertretung/com.android.niklasvlach.vertretung.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5294) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference at com.android.niklasvlach.vertretung.SettingsActivity.onCreate(SettingsActivity.java:28) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)  at android.app.ActivityThread.access$900(ActivityThread.java:154)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5294)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
The Code:
public class SettingsActivity extends AppCompatActivity {
Spinner select;
EditText username;
EditText password;
#Override
protected void onCreate(Bundle savedInstanceState) {
select = (Spinner) findViewById(R.id.selectclass);
username = (EditText) findViewById(R.id.username_view);
password = (EditText) findViewById(R.id.password_view);
select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long text) {
Toast.makeText(SettingsActivity.this,"" + text,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
If anything else is needed, I will post it!
You need to do your UI work after setting the layout of the Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
select = (Spinner) findViewById(R.id.selectclass);
username = (EditText) findViewById(R.id.username_view);
password = (EditText) findViewById(R.id.password_view);
select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long text) {
Toast.makeText(SettingsActivity.this,"" + text,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}

Categories