TrustyThar
TrustyThar

Reputation: 3

How to start a new activity on click in Android?

public void onClick(View view) {
    TextView snt = (TextView)
            view.findViewById(R.id.shape_name_text);
    String Selected = snt.getText().toString();
    String triangle = getResources().getString(R.string.triangle);
    if (Selected.equals(triangle)) {


        Intent intent = new Intent(this, TriCalculator.class);
        startActivity(intent);
    }

}

My intent is showing several errors and I can't figure out what to do next.

Upvotes: 0

Views: 72

Answers (3)

codeMagic
codeMagic

Reputation: 44571

Listing the errors would be helpful but here are at least two:

This line

TextView snt = (TextView) view.findViewById(R.id.shape_name_text);

is telling it to look in the View clicked (probably a Button) for your TextView which it is obviously not there. Assuming shape_name_text is in the same layout as yourButtonjust removeview`

TextView snt = (TextView) findViewById(R.id.shape_name_text);

Second problem is in this line

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

this refers to the Listener if you are in an inner-class. Change that to

Intent intent = new Intent(v.getContext(), TriCalculator.class);

Edit

As blackbelt pointed out in a comment, the first part of the answer is assuming you have attached the OnClickListener on a View and not a ViewGroup which contains the View you are then trying to initialize.

Another Edit

It seems (through a deleted comment) that the proper Intent import wasn't added

import android.content.Intent;

Upvotes: 1

NoGall
NoGall

Reputation: 5246

public void onClick(View view) {
TextView snt = (TextView)
        view.findViewById(R.id.shape_name_text);
String Selected = snt.getText().toString();
String triangle = getResources().getString(R.string.triangle);
if (Selected.equals(triangle)) {


    Intent intent = new Intent(this, TriCalculator.class);
    startActivity(intent);
}
}

In the code you posted above, you're actually telling the OS that you want to call another OnClickListener, by passing this as a parameter for your new Intent. In order for it to work, you will need to change it to something like:

Intent intent = new Intent(MainActivity.this, TriCalculator.class);

or

Intent intent = new Intent(getAppplicationContext(), TriCalculator.class);

(There are other options also)

:) Hope this helps!

Upvotes: 0

sunil
sunil

Reputation: 701

Use This:

findViewById(R.id.shape_name_text);  

remove view.

Upvotes: 0

Related Questions