Tzen Szen Toh Tzen Szen Toh - 3 months ago 7
Android Question

Trouble displaying data from previous fragment in new activity

I have some trouble with displaying a string from a previous fragment in a new activity on click. The string is displayed as "isnull".

Any help would be much appreciated. The relevant code is below.

Skill Activity:

public class Skill extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skill);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

Intent in = getIntent();
String skill = in.getStringExtra("skill");

TextView dispSkill = (TextView) findViewById(R.id.skill);
dispSkill.setText("this skill is" + skill);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

}


RVAdapter (of previous fragment):

public static class AssessViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {

CardView cv;
TextView assessName;
TextView pracName;
TextView required;
TextView reqnum;

AssessViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
assessName = (TextView)itemView.findViewById(R.id.assessment);
pracName = (TextView) itemView.findViewById(R.id.details);
required = (TextView) itemView.findViewById(R.id.required);
reqnum = (TextView) itemView.findViewById(R.id.reqnum);

itemView.setOnClickListener(this);
}

@Override
public void onClick(View v) {
Context context = v.getContext();

Intent intent = new Intent(context, Skill.class);
context.startActivity(intent);

String assessName = ((TextView) v.findViewById(R.id.assessment))
.getText().toString();
intent.putExtra(KEY_SKILL, assessName);

System.out.println(assessName);
}
}

Answer

As I pointed out in comment below your question, problem is that you are calling startActivity before data are attached to intent, so move context.startActivity(intent); at the end of onClick method at it should work

@Override
public void onClick(View v) {
    Context context = v.getContext();

    Intent intent = new Intent(context, Skill.class);

    String assessName = ((TextView) v.findViewById(R.id.assessment))
            .getText().toString();
    intent.putExtra(KEY_SKILL, assessName);

    System.out.println(assessName);
    context.startActivity(intent);
}
Comments