简体   繁体   中英

Problem with filling Activity's TextView from the Adapter class

I have an adapter that fills my RecyclerView. Due to onClick, when I am clicking on RecyclerView's Item, I store the DataBase's data that match the query and start new Activity. For example, I want to fill one Activity's TextView with data from a column named "name". But when I am clicking on RecyclerView's Item - application crashes. How can I solve this problem? (I can provide more code or information if you need.)

MyAdapter.java code:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements View.OnClickListener {
private ArrayList<MyObject> mItems = new ArrayList<>();
public String nametext;
DatabaseHelper myDB;
Main3Activity my3;
int idactivity;
String nameactivity;
int yearactivity;
int monthactivity;
int dayactivity;**




@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
    MyViewHolder vh=new MyViewHolder(view);
    view.setOnClickListener(this);

    return vh;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    holder.bindData(getItem(position));
}

@Override
public int getItemCount() {
    return mItems.size();
}

public void updateData(ArrayList<MyObject> items) {
    mItems = new ArrayList<>(items);
    notifyDataSetChanged();
}

private MyObject getItem(int position) {
    if (position >= 0 && position < mItems.size())
        return mItems.get(position);

    return null;
}

@Override
public void onClick(View v) {
    idactivity = 0;
    nameactivity = null;
    yearactivity = 0;
    monthactivity = 0;
    dayactivity = 0;

    myDB = new DatabaseHelper(v.getContext());
    my3 = new Main3Activity();
    TextView clickedName=(TextView)v.findViewById(R.id.title);
     nametext = clickedName.getText().toString();
    Toast.makeText(v.getContext(),nametext,Toast.LENGTH_LONG).show();
    Cursor c = myDB.showDataonSelect(nametext);



    if(c.moveToFirst()) {

        idactivity = c.getInt(0) ;
        nameactivity = c.getString(1) ;
        yearactivity = c.getInt(2) ;
        monthactivity = c.getInt(3) ;
        dayactivity = c.getInt(4);

    }
    TextView txt1 = my3.getTxt1();
    txt1.setText(nameactivity);


    Intent myIntent = new Intent(v.getContext(), Main3Activity.class);

    v.getContext().startActivity(myIntent);


}



class MyViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    TextView subTitle;

    MyViewHolder(View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.title);
        subTitle = itemView.findViewById(R.id.sub_title);
    }

    void bindData(MyObject myObject) {
        if (myObject == null)
            return;

        title.setText(myObject.title);
        subTitle.setText(myObject.subTitle);
    }
} }

Main3Activity.java code:

public class Main3Activity extends AppCompatActivity{


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

}
public TextView getTxt1(){
    TextView txt1 = findViewById(R.id.textView3);
    return txt1;
}}

logcat with exception message which appears on crash:

2019-06-06 18:12:27.721 15509-15509/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 15509
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
    at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
    at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
    at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
    at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
    at com.example.myapplication.Main3Activity.getTxt1(Main3Activity.java:18)
    at com.example.myapplication.MyAdapter.onClick(MyAdapter.java:90)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I want to fill Activity's TextView from MyAdapter's onClick method.

It seems you want to open Main3Activity when user clicks on an item, using item's title. The way of doing this is passing an extra to the activity (also called argument for fragments)

First you should implement View.OnClickListener in MyViewHolder:

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

also remove it from MyAdapter:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

then move your onClick method from MyAdapter inside MyViewHolder

Also in onClick method, don't use Main3Activity constructor. Just use Intent and add an extra with the title.

@Override
public void onClick(View v) {
    Intent myIntent = new Intent(v.getContext(), Main3Activity.class);
    myIntent.putExtra("TITLE_EXTRA", title.getText().toString())
    v.getContext().startActivity(myIntent);
}

Anything else in your onClick method move it to Main3Activity's onCreate or any other method.

To get TITLE_EXTRA in Main3Activity add this to your onCreate method:

private String title;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);
    ...
    if(getIntent() != null) {
        title = getIntent().getStringExtra("TITLE_EXTRA")
    }
    ...
}

Remove initialization of TextView TextView clickedName=(TextView)v.findViewById(R.id.title); from onClick and initialize it in your Holder class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM