gpt4 book ai didi

java - 我需要帮助来修复此 NPE

转载 作者:行者123 更新时间:2023-12-02 09:49:18 26 4
gpt4 key购买 nike

我正在尝试从 bundle 内的适配器中的意图获取值,但它似乎给了我一个空指针异常

我不确定,据我所知,获取额外 bundle 给了我一个 NPE,但不知道如何修复它 //首先是适配器 公共(public)类 ArticleAdapter 扩展 RecyclerView.Adapter {

    class MyViewHolder extends RecyclerView.ViewHolder {
TextView category;
TextView title;
ImageView image;
TextView pubDate;

MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.row_title);
image = (ImageView) view.findViewById(R.id.row_image);
pubDate = (TextView) view.findViewById(R.id.row_pubDate);
category = (TextView) view.findViewById(R.id.row_categories);
}
}
@NotNull
@Override
public MyViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row,parent, false);
return new MyViewHolder(v);
}


private List<Article> articles;

private Context mContext;
private WebView articleView;

public ArticleAdapter(List<Article> list, Context context) {
this.articles = list;
this.mContext = context;
}

public List<Article> getArticleList() {
return articles;
}


@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) {
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);

Intent intent = new Intent(mContext,DetailActivity.class);
intent.putExtra("setTitle",title);
intent.putExtra("setContent",content);
mContext.startActivity(intent);
}
});
}

@Override
public int getItemCount() {
return articles == null ? 0 : articles.size();
}
}
//the Activity code
public class DetailActivity extends AppCompatActivity {

DetailFragment mDetailFragment;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
DetailFragment mDetailFragment = (DetailFragment)getSupportFragmentManager().findFragmentByTag("TAG");
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mDetailFragment.setTitle((String) bundle.get("setTitle"));
showDetailFragment();
}

private void startTransactionFragment(Fragment fragment) {
if (!fragment.isVisible()) {
getSupportFragmentManager().beginTransaction().add(R.id.detail_activity_frame_layout, fragment).commit();
}
}
private void showDetailFragment() {
if (this.mDetailFragment == null) this.mDetailFragment = DetailFragment.newInstance();
this.startTransactionFragment(this.mDetailFragment);
}
}
//the fragment code
public class DetailFragment extends Fragment {

@BindView(R.id.detail_title) TextView title;
@BindView(R.id.detail_content) WebView content;
private WebView articleView;

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 setContent(String s){
articleView = new WebView(getContext());
articleView.getSettings().setLoadWithOverviewMode(true);
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" + s, null, "utf-8", null);

}

}
//and finally the xml code for both
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Controllers.Fragments.DetailFragment"
android:tag="TAG">
<TextView
android:id="@+id/detail_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TITLE"
android:textSize="50dp"/>
<WebView
android:id="@+id/detail_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ARTICLE"
android:textSize="20dp"
android:layout_gravity="center"/>

</LinearLayout>
//activity xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/detail_activity_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Controllers.Activities.DetailActivity">

</FrameLayout>

更新的堆栈跟踪:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.rssreader, PID: 25621 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rssreader/com.example.rssreader.Controllers.Activities.DetailActivity}: 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 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) 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) Caused by: 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.Controllers.Activities.DetailActivity.onCreate(DetailActivity.java:28) at android.app.Activity.performCreate(Activity.java:7009) at android.app.Activity.performCreate(Activity.java:7000) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)  at android.os.Handler.dispatchMessage(Handler.java:106)  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) 

最佳答案

发生这种情况是因为 mDetailFragment 未初始化。

堆栈跟踪显示 mDetailFragment = null

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.rssreader.Controllers.Fragments.DetailFragment.setTitle(java.lang.String)' on a null

基本上你需要做的就是这个

// Let's first dynamically add a fragment into a frame container, that is your xml like a LinearLayout
getSupportFragmentManager().beginTransaction().
replace(R.id.YOUR_XML, new DetailFragment(), "SOMETAG").
commit();
// Now later we can lookup the fragment by tag
DetailFragment mDetailFragment = (DetailFragment)
getSupportFragmentManager().findFragmentByTag("SOMETAG");

要使用片段,本教程中介绍了几种方法 Creating and Using Fragments

UPDATE

onCreate() 更改为如下所示:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
DetailFragment fragment = (DetailFragment)getSupportFragmentManager().findFragmentByTag("TAG");
if(fragment == NULL){
fragment = DetailFragment.newInstance();
}
fragment.setTitle((String) bundle.get("setTitle"));
startTransactionFragment(fragment);
}

我还没有测试过代码,只是从我的脑海中测试出来的。

关于java - 我需要帮助来修复此 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56426666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com