1. Are you ready for the Galaxy S20? Here is everything we know so far!

Button makes the to return to the main activity

Discussion in 'Android Development' started by yftach srur, Sep 27, 2019.

  1. yftach srur

    yftach srur Lurker
    Thread Starter

    Hey. I want to make a button which makes the app to move to another activity.
    I did it a few times with this app with no problem, but for some reason, this simple button, when I click it, there is a black screen for half a second and it returns to the main activity.

    Code (Java):
    1.   explanation.setOnClickListener(new View.OnClickListener() {
    2.             @Override
    3.             public void onClick(View v) {
    4.                 Intent toExplanation = new Intent(getApplicationContext(), ChoiceExplanationActivity.class);
    5.  
    6.                 startActivity(toExplanation);
    7.             }
    8.         });
    This is what I'v done in the activity which the button is in.

    Code (Java):
    1. public class ChoiceExplanationActivity extends AppCompatActivity {
    2.  
    3.     @Override
    4.     protected void onCreate(Bundle savedInstanceState) {
    5.         super.onCreate(savedInstanceState);
    6.         setContentView(R.layout.activity_choice_explanation);
    7.  
    8.         TextView choiceExplanation = findViewById(R.id.explanation);
    9.  
    10.  
    11.         choiceExplanation.setText("ok");
    12.     }
    13. }
    14.  
    And this is the activity which it should lead too.
    When I looked at the log when clicking the button, I found this line which I think is the problem.

    Code (Text):
    1. java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appdeveloping/com.example.appdeveloping.ChoiceExplanationActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    Thanks for the help.
     


  2. yftach srur

    yftach srur Lurker
    Thread Starter

    Found my problem.
    I have accidentally initialized the choiceExplanation text view with "explanation" which is a button and not a text view.
    I'm stuiped
     
  3. wseng92

    wseng92 Android Enthusiast

    Learn from mistake and you will be good to go.
     
Loading...
Similar Threads - Button makes return
  1. Georgiaboy9009
    Replies:
    9
    Views:
    176
  2. cbuchananbuchanan
    Replies:
    0
    Views:
    224
  3. amazijn
    Replies:
    11
    Views:
    447
  4. jkgraves
    Replies:
    4
    Views:
    368
  5. Samsung
    Replies:
    1
    Views:
    207
  6. BushraEisa
    Replies:
    0
    Views:
    388
  7. vsLudwig
    Replies:
    4
    Views:
    367
  8. IvanAFG
    Replies:
    2
    Views:
    303
  9. neerav512
    Replies:
    0
    Views:
    195
  10. Zaheer Ahmed
    Replies:
    0
    Views:
    1,261

Share This Page

Loading...