-1

I'm trying to start an activity from my adapter's List on click and send info to show in the new activity's fragment, but it crashes.

I tried to make the setTitle and other methods @nullable but didn't work

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder viewHolder, int position) {

        Article currentArticle = articles.get(position);
        Log.e("article", currentArticle.getTitle());
        String pubDateString;
        try {
            String sourceDateString = currentArticle.getPubDate();

            SimpleDateFormat sourceSdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
            Date date = sourceSdf.parse(sourceDateString);

            SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy", Locale.getDefault());
            pubDateString = sdf.format(date);

        } catch (ParseException e) {
            e.printStackTrace();
            pubDateString = currentArticle.getPubDate();
        }

        viewHolder.title.setText(currentArticle.getTitle());

        Picasso.get()
                .load(currentArticle.getImage())
                .placeholder(R.drawable.placeholder)
                .into(viewHolder.image);

        viewHolder.pubDate.setText(pubDateString);

        StringBuilder categories = new StringBuilder();
        for (int i = 0; i < currentArticle.getCategories().size(); i++) {
            if (i == currentArticle.getCategories().size() - 1) {
                categories.append(currentArticle.getCategories().get(i));
            } else {
                categories.append(currentArticle.getCategories().get(i)).append(", ");
            }
        }

        viewHolder.category.setText(categories.toString());

        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("SetJavaScriptEnabled")
            @Override
            public void onClick(View view) {
                //show article content inside a dialog
                articleView = new WebView(mContext);

                articleView.getSettings().setLoadWithOverviewMode(true);

                String title = articles.get(viewHolder.getAdapterPosition()).getTitle();
                String content = articles.get(viewHolder.getAdapterPosition()).getContent();

                articleView.getSettings().setJavaScriptEnabled(true);
                articleView.setHorizontalScrollBarEnabled(false);
                articleView.setWebChromeClient(new WebChromeClient());
                articleView.loadDataWithBaseURL(null, "<style>img{display: inline; height: auto; max-width: 100%;} " +

                        "</style>\n" + "<style>iframe{ height: auto; width: auto;}" + "</style>\n" + content, null, "utf-8", null);

                mDetailFragment.setTitle(currentArticle.getTitle());
                mDetailFragment.setAuthor(currentArticle.getAuthor());
                mDetailFragment.setPubDate(currentArticle.getPubDate());
                mDetailFragment.setDescription(currentArticle.getDescription());
                mDetailFragment.setImage(currentArticle.getImage());
                mDetailFragment.setContent(currentArticle.getContent());
                mDetailFragment.setLink(currentArticle.getLink());
                mContext.startActivity(new Intent(mContext,DetailActivity.class));
            }
        });
    }

here's my logcat

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.rssreader, PID: 20126 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.rssreader.Controllers.Fragments.DetailFragment.setTitle(java.lang.String)' on a null object reference at com.example.rssreader.Adapters.ArticleAdapter$1.onClick(ArticleAdapter.java:141) at android.view.View.performClick(View.java:6294) at android.view.View$PerformClick.run(View.java:24770) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

this is my detail fragment: public class DetailFragment extends Fragment {

    @BindView(R.id.detail_title) TextView title;
    @BindView(R.id.detail_author) TextView author;
    @BindView(R.id.detail_date) TextView pubDate;
    @BindView(R.id.detail_description) TextView description;
    @BindView(R.id.detail_image) TextView image;
    @BindView(R.id.detail_content) TextView content;
    @BindView(R.id.detail_link) TextView link;

    public DetailFragment() {   }

    public static DetailFragment newInstance () {
        return (new DetailFragment());
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.fragment_detail, container, false);

        ButterKnife.bind(this, view);
        return view;

    }
    public void setTitle(String s){ title.setText(s); }
    public void setAuthor(String s){
        author.setText(s);
    }
    public void setPubDate(String s){
        pubDate.setText(s);
    }
    public void setDescription(String s){
        description.setText(s);
    }
    public void setImage(String s){
        image.setText(s);
    }
    public void setContent(String s){ content.setText(s); }
    public void setLink(String s){
        link.setText(s);
    }

}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • how you set your `mDetailFragment`? – Alexander Dadukin Jun 03 '19 at 09:26
  • why you have considered that `@nullable` should made `null`-safety checks? its just a contract which should be followed by a coder. – Alexander Dadukin Jun 03 '19 at 09:27
  • post this class also DetailFragment – Quick learner Jun 03 '19 at 09:28
  • Welcome to SO!. The mDetailFragment is null, it is evident from the crash logs. Please check the initialization of mDetailFragment. Further, you are trying to modifying the mDetailFragment inside the adapter, I won't encourage that. It's better to use a listener in your fragment/activity to do that sort of updation. Further, if you want to set particular values in your target activity, pass the values as bundle in the intent. – Rahul Shukla Jun 03 '19 at 09:34
  • @AlexanderDadukin i just posted it – Aziz Boubaker Jun 03 '19 at 10:04
  • @Quicklearner i just posted it. – Aziz Boubaker Jun 03 '19 at 10:05
  • @RahulShukla thanks, but can you give me an example please? i'm not sure i know how to make the listener. and how do I pass the values as bundle in the intent, since the intent is passed to an activity and the values i want to pass are in the adapter and trying to modify the fragment – Aziz Boubaker Jun 03 '19 at 10:08
  • It still not clear, how you provide your fragment into RecyclerAdapter – Alexander Dadukin Jun 03 '19 at 10:39

2 Answers2

0

Your mDetailFragment is null that´s why NullPointerException. Why you even handling the mDetailFragment in the adapter onBindViewHolder??

You could create an Intent populating it with the values you right now setting in the mDetailFragment, and then the DetailActivity will handle your Fragment

Intent i = new Intent(mContext, DetailActivity.class);                      
i.putExtra("setTitle", currentArticle.getTitle());
i.putExtra("setAuthor", currentArticle.getAuthor());
startActivity(i);

This way your sending all information to the DetailActivity when you start the DetailActivity.

You use it like this example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Textv txt = (TextView)findViewById(R.id.tv2);
    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    txt.setText(bundle.get("setTitle");
}
Erik
  • 5,039
  • 10
  • 63
  • 119
0

Your app crashes at below line,because you do not have initialize DetailFragment object

  // initialize here mDetailFragment object
  DetailFragment mDetailFragment=new DetailFragment();
  if(currentArticle.getTitle()!=null && !TextUtils.isEmpty(currentArticle.getTitle())){
 mDetailFragment.setTitle(currentArticle.getTitle());
}
Dharmender Manral
  • 1,504
  • 1
  • 6
  • 7