Android intent force new activity

In Android, you can use the Intent class to start a new activity from another activity. Here's a step-by-step guide on how to do it:

Step 1: Create a new activity

Create a new Java class that extends the Activity class. For example, let's call it NewActivity.java.

Step 2: Define the intent

In the activity that you want to start the new activity from, create an Intent object. The Intent object specifies the action to be performed (in this case, starting a new activity) and the component to be used to perform the action (in this case, the NewActivity class).

Here's an example:

Intent intent = new Intent(this, NewActivity.class);

Step 3: Set any necessary data

You can set any necessary data to be passed to the new activity using the putExtra() method. For example:

intent.putExtra("key", "value");

Step 4: Start the intent

Use the startActivity() method to start the intent:

startActivity(intent);

Step 5: Handle the result (optional)

If you want to receive a result from the new activity, you can use the startActivityForResult() method instead of startActivity(). This method takes an Intent object and a request code as parameters.

In the new activity, you can use the setResult() method to set the result:

Intent resultIntent = new Intent();
resultIntent.putExtra("result", "result value");
setResult(RESULT_OK, resultIntent);

In the original activity, you can use the onActivityResult() method to handle the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
        String result = data.getStringExtra("result");
        // Handle the result
    }
}

Example code

Here's an example of how to start a new activity from another activity:

// Original activity
public class OriginalActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_original);

        // Create an intent to start the new activity
        Intent intent = new Intent(this, NewActivity.class);
        intent.putExtra("key", "value");

        // Start the intent
        startActivity(intent);
    }
}

// New activity
public class NewActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new);

        // Get the extra data passed from the original activity
        String key = getIntent().getStringExtra("key");

        // Do something with the data
        Log.d("NewActivity", "Received key: " + key);
    }
}

That's it! By following these steps, you can use the Intent class to start a new activity from another activity in Android.