2

I am new to android programming and have ran into a problem. I am trying to create a voting app where when a user opens up the application and the MainActivity is shown, from here they press a button to go into the second Screen (Screen2) which shows images of people and their names as buttons. When a persons name (in a button on Screen2) is pressed , a text field shows the number of times the button is pressed in an another activity (Screen4) . The problem here is that when i try to show this (Screen4), the app crashes. I am quite new to this so if you didn't understand my issue or need more information please let me know. Any help is appreciated. Thank you.

EDIT : After some help I used Intent to try send the data across but now when when the button in screen2 is pressed the app refreshes and then takes me back to the mainActivity and when this process is tried again the app crashes.

This is the new Screen2 :

package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Screen2 extends AppCompatActivity {

    TextView showValue;
    int counter = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen2);

        showValue = findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the On click for the Textview in a different activity.


    }

    public void AnCount(View v) {
        //increase the count
        counter++;
        showValue.setText(Integer.toString(counter));

    }

    public void ButtonToGoToTheOtherActivity(View v) {

        Intent intent = new Intent(this, Screen4.class);
        intent.putExtra("valueOfCounter", counter);   //the code for sending data to the other activity.
        startActivity(intent);


    }
}

This is the XML for screen 2 :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".Screen2">


    <Button
        android:id="@+id/AnnieBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:text="@string/annie_liou"
        android:onClick="AnCount"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView5"

        />

This is my Screen4:

   package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class Screen4 extends AppCompatActivity {

    private Button Button3;

int counter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen4);




        Button3 = (Button) findViewById(R.id.Button3);
        Button3.setOnClickListener(new View.OnClickListener() {
                                       public void onClick(View view) { openActivity4();
                                       }
                                   }


        );
        counter = getIntent().getIntExtra("valueOfCounter", 0); // 0 is default value

    }

    public void openActivity4() {
        Intent intent = new Intent(Screen4.this, MainActivity.class);
        startActivity(intent);
    }

}

Here is the XML for screen4:

 <?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/MainScreen"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Screen4">

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="193dp"
            android:layout_marginLeft="193dp"
            android:layout_marginEnd="109dp"
            android:layout_marginRight="109dp"
            android:layout_marginBottom="660dp"
            android:text="This is 4th screen"
            android:textSize="32sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.664"
            app:layout_constraintStart_toStartOf="parent" />

        <Button
            android:id="@+id/Button3" // return to main screen
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="532dp"
            android:text="Return" 
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.498"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView5" />

        <TextView
            android:id="@+id/VoteCountAnnie" // textview where i want the increment to show
            android:layout_width="121dp"
            android:gravity="center"
            android:layout_height="52dp"
            android:layout_marginStart="116dp"
            android:layout_marginLeft="116dp"
            android:layout_marginTop="82dp"
            android:layout_marginEnd="174dp"
            android:layout_marginRight="174dp"
            android:text="0"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView5" />

    </androidx.constraintlayout.widget.ConstraintLayout>

This is my main Activity Screen (not used for the clicking but if there is something wrong in this that could affect the other Screens please let me know) :

package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openActivity2();

            }
        });

        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
                                       public void onClick(View view) {
                                           openActivity3();
                                       }

                                   }
                                   );


    }

    public void openActivity2() {
        Intent intent = new Intent(this, Screen2.class);
        startActivity(intent);
    }

    public void openActivity3() {
        Intent intent = new Intent(this, Screen3.class);
        startActivity(intent);
    }
}
Here is the XML for screen 4:
Unknown C
  • 23
  • 5
  • `//VoteCountAnnie is the Id for the Textview in a different activity` – You cannot access `View`s in another `Activity` like that. If you'd like to relay data back to the previous `Activity`, you can use `startActivityForResult()`: https://stackoverflow.com/q/920306. – Mike M. Aug 28 '19 at 15:40
  • 1
    @MikeM. Thank you for your response Mike, I see where I am going wrong – Unknown C Aug 29 '19 at 09:08

3 Answers3

0

As Mike M. said you are using id of a textview which is in a different activity. In android we cannot access ids of views in a different activity. We can only access ids of view in the same activity in which we are. So that is for the error you are getting. For accessing Data from another activity you can pass the data like this:

        public class Screen2 extends AppCompatActivity {

       int counter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_screen1);
            showValue = (TextView) findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the Id for the Textview in a different activity.


    }
public void AnnieCountInc (View view) {
        //increase the count
    counter++;
    showValue.setText(Integer.toString(counter));
}
//make another button with a method like
     public void ButtonToGoToTheOtherActivity(View view){

        Intent intent =new Intent(this,Screen4.class);
              intent.putExtra("valueOfCounter",counter);   //the code for sending data to the other activity.
              startActivity(intent);
}

Then in your Screen4 activity you can get the value of "counter" in the onCreate method by:

counter = getIntent().getIntExtra("valueOfCounter",0); // 0 is default value

This is one method.

You can also use a static variable to pass on data easily by defining your counter varaible as public static int counter;

Then you can access it directly and it will show you the value.

Muhammad Ali
  • 683
  • 4
  • 9
  • Hi Muhammad. Thank you for your response, I tried to implement what you have said but upon running the app it just freeze. Also I'm sending the data from Screen2 to Screen4 ( which is meant to show the increment in a tex tview). – Unknown C Aug 29 '19 at 09:06
  • put intent.putExtra("valueOfCounter",counter) in screen2 and call it with getIntent().getIntExtra("valueOfCounter",0) in screen4. there should be no problem. Otherwise copy the code of screen4 here. – Muhammad Ali Aug 29 '19 at 10:55
  • Hi Muhammad, i have provided the code for the other pages, could you have a look if you can and tell me what is going wrong ? – Unknown C Aug 29 '19 at 11:41
  • In screen2, you wrote Intent intent =new Intent(this,Screen2.class); change Screen2.class with Screen4.class i.e the activity in which you want to go. On startActvity(intent) you will go in Screen4 activity. And I hope freezing will stop. – Muhammad Ali Aug 29 '19 at 11:47
  • I tried this but as soon as I press the button in MainActivity to get to the second screen it instead takes me directly to screen4 – Unknown C Aug 29 '19 at 11:55
  • You have pasted my code in the wrong place: Understand what it does. What we are doing here is using intent to send the screen to another activity.So basically if you want to go to Activity A and you are in Activity B you will use intent like this in Activity B: Intent intent =new Intent(this,Name of Activity A); startActivity(intent); – Muhammad Ali Aug 29 '19 at 12:32
  • Where should your code go ? I do understand the basic use of intent, i use it in my application to navigate to different activities with buttons, but what i want here is to have the number of button clicks showing on the 4th screen without taking me directly there. Im sorry for my lack of knowledge, I am very new to this. – Unknown C Aug 29 '19 at 12:49
  • I honestly appreciate the help in trying to educate me but would you be able to show me where i can place your code so that it sends the data to the 4th screen without actually opening the 4th screen at the same time. – Unknown C Aug 29 '19 at 13:04
  • I am sorry I wrote intent code in onCreate in my answer it should go into a button like this: public void ButtonToGoToTheOtherActivity(View view){ Intent intent =new Intent(this,Screen4.class); intent.putExtra("valueOfCounter",counter); //the code for sending data to the other activity. startActivity(intent); } I have changed my answer a bit. Please check it again. – Muhammad Ali Aug 29 '19 at 13:05
  • The app has stopped crashing ! however now when I press the button to go to screen 4 the value remains at 0, is this because the increment is not saved and is resetting everytime I navigate to a new page ? – Unknown C Aug 29 '19 at 13:31
  • The way I understand your code is you are counting in Screen2 then back to mainActivity and then go to Screen4. You can only get the value of counter correctly through intent if you go directly after counting in screen2 to screen4. If you go back to main activity and then go to screen4 you will not get the value. – Muhammad Ali Aug 29 '19 at 14:08
  • which bit of the code makes you think that its going back to mainActivity after screen2? – Unknown C Aug 29 '19 at 14:38
  • Have you pasted this code also in the button: intent.putExtra("valueOfCounter",counter); ? Can you please update your code in the Question with the new code you are using in your App. I can then more easily understand what is the problem. – Muhammad Ali Aug 29 '19 at 14:44
  • I have as you told me ( I have updated the original post ). Now what happens is when the increment button is pressed the app refreshes and goes back to the main activity as a fresh start, when the process is tried again the app crashes. Again thank you for your patience and help, i just want to get my head around this. – Unknown C Aug 29 '19 at 14:51
  • If you need more like the XML then please let me know – Unknown C Aug 29 '19 at 14:54
  • Are you using intent in increment button? – Muhammad Ali Aug 29 '19 at 14:56
  • No, just in the ButtonToGoToTheOtherActivity method. – Unknown C Aug 29 '19 at 15:00
  • send the xml in you Question. – Muhammad Ali Aug 29 '19 at 15:02
  • In Screen2: showValue = findViewById(R.id.VoteCountAnnie); You can not access a view defined in another activity's xml. that is why your AnCount method crashes. – Muhammad Ali Aug 29 '19 at 15:50
  • How would i access that view, i tried to have a look around but nothing specific has come up – Unknown C Aug 30 '19 at 07:47
  • you have defined VoteCountAnnie in the Screen4's xml. So you can only access VoteCountAnnie in Screen4 Activity and not any where else. After counting in Screen2 get back to Screen4 and there access VoteCountAnnie. – Muhammad Ali Aug 30 '19 at 09:57
0

add following to manifest :

// Main Activity //

 - List item

package com.example.cameraone;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
    private Button counter,show;
    private int count  = 0;

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        counter = findViewById(R.id.bt_counter);
        show = findViewById(R.id.bt_show);
        counter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;
            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               go();
            }

        });
    }

    public void go(){
        DisplayCount.setVoteCount(count);
        Intent intent = new Intent(this, DisplayCount.class);
        startActivity(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(EXTRA_VOTE_KEY,count);
    }
}



/** Class to display: **/
- List item 

package com.example.cameraone;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

public class DisplayCount extends AppCompatActivity{

   private TextView textView ;
   private static int count ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_count_activity);

        textView = findViewById(R.id.tv_vote_count);
        textView.setText(Integer.toString(count));`enter code here`
    }

    public static void setVoteCount(int c){
       count = c;
    }
}

/***** Activity files *****/

- List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_gravity="center">

    <TextView
        android:id="@+id/tv_vote_count"
        android:layout_width="wrap_content"
        android:inputType="number"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:maxLength="10"/>

</RelativeLayout>

/**** Activity That display's ****/

-List item


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt_counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="PressMe"
        />
    <Button
        android:id="@+id/bt_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/bt_counter"
        android:text="Done"
        />
</RelativeLayout>
0
This works same using intent .

Main Class :

package com.example.cameraone;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
    private Button counter,show;
    private int count  = 0;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(savedInstanceState != null){
            count = savedInstanceState.getInt(EXTRA_VOTE_KEY);
        }
        counter = findViewById(R.id.bt_counter);
        show = findViewById(R.id.bt_show);
        counter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;
            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                go();
            }
        });

      /* Intent intent = new Intent(this,DisplayCount.class);
       //intent.putExtras(intent);
        startActivity(intent,bundle);*/

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(EXTRA_VOTE_KEY,count);
    }

    public void go(){
        Intent intent = new Intent(this,DisplayCount.class);
        intent.putExtra(EXTRA_VOTE_KEY,count);
        startActivity(intent);
    }
}

Activity of Main Class :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt_counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="PressMe"
        />
    <Button
        android:id="@+id/bt_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/bt_counter"
        android:text="Done"
        />
</RelativeLayout


Display Class :

package com.example.cameraone;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

public class DisplayCount extends AppCompatActivity{

    private  TextView textView;
    private int count;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_count_activity);

        textView = findViewById(R.id.tv_vote_count);
        Intent intent = getIntent();
        count = intent.getIntExtra(MainActivity.EXTRA_VOTE_KEY,0);
        textView.setText(Integer.toString(count));
    }
}


Activity of display class :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_gravity="center">

    <TextView
        android:id="@+id/tv_vote_count"
        android:layout_width="wrap_content"
        android:inputType="number"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:maxLength="10"/>

</RelativeLayout>


Manifest : 

include following in your   manifest file :

<activity android: name =".DisplayCount"></activity>