java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'

时间:2019-09-08 06:11:48

标签: android nullpointerexception

我想在textview的片段上显示字符串(已解析的json文件)。

我从导航抽屉活动开始了项目。

解析成功,但是

  

java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'

发生错误

我该如何解决?

MainAcitvity.java

TextView tv=(TextView)findViewById(R.id.text_slideshow);
StringBuilder sb=new StringBuilder();
String json = null;

        try {

            InputStream is = getAssets().open("tour.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");


            Log.i("TEST", "afterfileio");

            JSONParser parser=new JSONParser();
            JSONObject jsonObject= (JSONObject) parser.parse(json);
            JSONObject jsonObject1=(JSONObject)jsonObject.get("facilityConveInfo");
            JSONArray jsonArray = (JSONArray) jsonObject1.get("row");




            Log.i("TEST", ""+jsonArray.size() + "");
            for (int i = 0; i < jsonArray.size(); i++) {


                JSONObject subJsonObject = (JSONObject) jsonArray.get(i);
                String FACILITY_NM =subJsonObject.get("FACILITY_NM").toString(); 


                sb.append(FACILITY_NM);

            }
            tv.setText(sb.toString());

fragment_slideshow.xml

<TextView
    android:id="@+id/text_slideshow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:textAlignment="center"
    android:textSize="20sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

SlideFragment.java

public class SlideshowFragment extends Fragment {

    private SlideshowViewModel slideshowViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        slideshowViewModel =
                ViewModelProviders.of(this).get(SlideshowViewModel.class);
        View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
        final TextView textView = root.findViewById(R.id.text_slideshow);
        slideshowViewModel.getText().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
    return root;

1 个答案:

答案 0 :(得分:0)

在我看来,您从未创建过该片段,所以sb引用了null。

  1. 创建片段
  2. 初始化片段(新);
  3. 启动片段事务,类似这样

    FragmentTransaction fragmentTransaction = 
    getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, yourFragment);
    fragmentTransaction.commit();
    

祝你好运