0

So what I am trying to make happen is when you check this checkBoxA, some text will appear in a different TextView in a different Activity that the user will reach later on. The app is kind of like a quiz app so this off the text being displaid like the final score or something.

At first I tried this:

 if (checkBoxA.isChecked()){
        systemView.setText("Business");
    }

But then I got a nullPointerException cause the "systemView" is not in the same activity. The activity is extended to the other activity that the "systemView" is located. So I am not really sure whats wrong anyone know what I should do?

Mira
  • 23
  • 6
  • Not that I'm answering your question but... why don't you just save answers in a file and later on read that file? – user2638180 Aug 25 '18 at 22:45

5 Answers5

0

you can pass your text in the intents of navigations between the activities .. otherwise if you want to save your text to recover it later, even if you close and restart your application, you can save it in a shared preferences file, to retrieve it from this file when you want to display it later.. but you can not set a text to a textview of an activity that is not in foreground.

0

There are many ways to do this depending on your exact use case one may be better suited than the others.

You can wrap the data in a bundle and pass it to your other activity through an intent if you are opening a second activity

Or you could store the values (in shared prefs or sqlite) and then retrieve them in the next activity.

You could use RxJava to create a stream via a subject (bevahior subject most likely in this case) and write to the stream in the first activity, then subscribe on the stream in the next to get the values.

Zachary Sweigart
  • 1,051
  • 9
  • 23
0

If you are using an intent to go to the next activity you could put the value in a string and pass the string as an extra to the intent. Take the value in the next activity and set the text view.

//First Activty
String valueToPass = "";
if (checkBoxA.isChecked()){
    valueToPass = "Business";
}

startActivity(new Intent(CurrentActivity.this, NextActivity.class).putExtra("value", valueToPass));



//Second Activity
if(getIntent().getString("value") != null)){
    systemView.setText(getIntent().getString("value"));
}
Xixis
  • 881
  • 6
  • 8
0

Your issue is that even though you can get the ID of the systemView TextView by using R.id.systemView when you try to find that view using findViewById(R.id.systemView) the view cannot be found as it is not in the current activity's list of ViewGroup. As such null is returned.

  • Note systemView as the id given to the TextView has been assumed.

That is, You can only successfully use findViewById to find views within the current ViewGroup (e.g. for this.FindyViewById the layout as set by setContentView).

Instead you need to make the value available to the other activity and then retrieve the value in the other activity.

There are various ways that you can make the value available, some options are :-

To pass it to the activity via the Intent that starts the other activity as an intent extra, you could store the value in shared preferences and then retrieve it in the other activity or you could store the value in a database, e.g. SQLite and retrieve it.

Using an IntentExtra is ideal if you are directly starting the other activity with a limited number of values.

  • using chained Intent Extras is also feasible (that is passing to one activity, then to another and so on).

Shared preferences could suit a situation where there are a limited number of values to be passed and the other activity isn't directly started from the activity.

A database would suit a situation where there is a fair amount of structured data and/or related data (or if you are using a database for other aspects).

An example of using an Intent could be :-

In the Activity that is passing the value

Intent i = new Intent(this, yourOtherActivity.class);
i.putExtra("YOURINTENTEXTRAKEY","Business"); //<<<< 1st parameter is a Key for identification, the 2nd parameter is the value to be passed
startActivity(i);

In the other Activity's onCreate (after you've set the contentView)

TextView mSystemView = this.find(R.id.systemView);
if (this.getIntent().getStringExtra("YOURINTENTEXTRAKEY") != null) {
    mSystemView.setText(this.getItent().getStringExtra("YOURINTENTEXTRAKEY"));
} else {
    mSystemView.setText("NO VALUE PASSED");
}
  • You set pass and return multiple IntentExtras see Intent for various options and types of values that can be passed/retrieved.

Simple Working Example

The following is code for a working example. The first activity (MainActivity) has a CheckBox and a Button.

The Button can be clicked or longClicked. If the latter then nothing is passed to the second activity. If the former then depedning upon whether or not the CheckBox is ticked will either pass "Not Checked" or "Business".

The second activity, if passed a value (either "Not Checked" or "Business") will display the passed value, if nothing is passed then it will display "NOTHING PASSED". The button on the second activity will return to the first activity (alternately using the back button will return to the first activity).

MainActivity.java

public class MainActivity extends AppCompatActivity {

    public static final String INTENTKEY_CHECKBOXA = "checkboxa";

    CheckBox checkBoxA;
    Button nextActivity;
    String valueToPass = "Not Checked";

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

        checkBoxA = this.findViewById(R.id.checkBoxA);
        checkBoxA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (checkBoxA.isChecked()) {
                    valueToPass = "Business";
                } else {
                    valueToPass = "Not Checked";
                }
            }
        });
        nextActivity = this.findViewById(R.id.nextActivity);
        //Set onlick listener (pass value via intent)
        nextActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callNextActivity(true);
            }
        });
        // Set onlongclick listener (doesn't pass value via intent)
        nextActivity.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                callNextActivity(false);

                return true;
            }
        });
    }

    private void callNextActivity(boolean passvalue) {
        Intent i = new Intent(this,NextActivity.class);
        if (passvalue) {
            i.putExtra(INTENTKEY_CHECKBOXA, valueToPass);
        }
        startActivity(i);
    }
}

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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <Button
        android:id="@+id/nextActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NEXT ACTIVITY"/>
    <CheckBox
        android:id="@+id/checkBoxA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

NextActivity.java

public class NextActivity extends AppCompatActivity {

    Button doneButton;
    TextView systemView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);
        systemView = this.findViewById(R.id.sysstemView);
        doneButton = this.findViewById(R.id.done);
        if (this.getIntent().getStringExtra(MainActivity.INTENTKEY_CHECKBOXA) != null) {
            systemView.setText(this.getIntent().getStringExtra(MainActivity.INTENTKEY_CHECKBOXA));
        } else {
            systemView.setText("NOTHING PASSED");
        }
        doneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doneWithActivity();
            }
        });
    }

    // Return from this activity
    private void doneWithActivity() {
        this.finish();
    }
}

activity_next.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"
    tools:context=".NextActivity">

    <Button
        android:id="@+id/done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DONE"/>

    <TextView
        android:id="@+id/sysstemView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
Community
  • 1
  • 1
MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Thanks, I tried that with one check box and button and it worked. However, when I added more check boxes the TextView would only display the same text no matter which box I checked. I set different Strings and texts or each one so I'm not sure what is the problem. – Mira Aug 27 '18 at 23:14
  • @Mira you should add another question and include the code, especially the logic in regards to handling the checkboxes. – MikeT Aug 28 '18 at 00:09
  • I did please check it out – Mira Aug 28 '18 at 15:39
0

Just use SharedPreferences to save the TextView value and then when go to the Activity that contain the TextView get the saved value and set it to the TextView in the onCreate method

First dev
  • 495
  • 4
  • 17