片段无法加载到 View_pager tabLayout [重复]

Posted

技术标签:

【中文标题】片段无法加载到 View_pager tabLayout [重复]【英文标题】:Fragment Unable to load in View_pager tabLayout [duplicate] 【发布时间】:2018-05-14 05:28:53 【问题描述】:

android 新手。我尝试在 Main_Activity 中的 View_Pager tab_Layout 的 SQLite 数据库中加载插入值的片段。并尝试在 view_pager 第二个选项卡的第二个片段中显示数据。但是运行应用程序时它崩溃了..无法在 view_pager 中加载片段。这是我的代码,我不知道这段代码有什么问题。为什么它没有加载。

public class MyAdapter extends FragmentPagerAdapter

    String[] name="Insert","Show";


    @Override
    public CharSequence getPageTitle(int position) 
        return name[position];
    

    public MyAdapter(FragmentManager fm) 
        super(fm);
    

    @Override
    public Fragment getItem(int position) 

        switch (position)
        

            case 0:InsertFragment im=new InsertFragment();
            return im;


            case 1:ShowFragment sm=new ShowFragment();
            return sm;


        
        return null;


    @Override
    public int getCount() 
        return 2;
    

主活动

public class MainActivity extends AppCompatActivity 

TabLayout tabLayout;
ViewPager viewPager;
MyAdapter myAdapter;
MyDatabase m;

  @Override
  protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    tabLayout=(TabLayout) findViewById(R.id.tabLayout1);
    viewPager=(ViewPager) findViewById(R.id.viewPager);
    myAdapter=new MyAdapter(getSupportFragmentManager());
    //viewPager.setCurrentItem(0);
    viewPager.setAdapter(myAdapter);
    tabLayout.setupWithViewPager(viewPager);


    m=new MyDatabase(this);
    m.open();


    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();
        
    );

protected void onDestroy() 

    super.onDestroy();
    m.close();




@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);


插入片段

public class InsertFragment extends Fragment 

EditText name,sub,email;
Button fill1;


public InsertFragment() 
    // Required empty public constructor



@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    // Inflate the layout for this fragment
    View v= inflater.inflate(R.layout.fragment_insert, container, false);

    name=(EditText)v.findViewById(R.id.name);
    sub=(EditText)v.findViewById(R.id.sub);
    email=(EditText)v.findViewById(R.id.email);
    fill1=(Button)v.findViewById(R.id.fill);


    fill1.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 

            if(name.getText().toString().equals("") || sub.getText().toString().equals("")||
                    email.getText().toString().equals(""))
            
                Toast.makeText(getActivity(), "please Insert data", Toast.LENGTH_SHORT).show();
            
            else 
                String Name = name.getText().toString().trim();
                String Subject = sub.getText().toString().trim();
                String Email = email.getText().toString().trim();

                MainActivity main = new MainActivity();
                main.m.insertStudent(Name, Subject, Email);

                name.setText("");
                sub.setText("");
                email.setText("");
                name.requestFocus();
            
        
    );
    return v;



显示片段

public class ShowFragment extends Fragment 


RecyclerView rv;
LinearLayoutManager manager;
Cursor c;
MynewAdapter ma;



public class MynewAdapter extends RecyclerView.Adapter<MynewAdapter.ViewHolder>


    @Override
    public MynewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 

        View v=getActivity().getLayoutInflater().inflate(R.layout.row,parent,false);
        ViewHolder vh=new ViewHolder(v);

        return vh;
    

    @Override
    public void onBindViewHolder(MynewAdapter.ViewHolder holder, int position) 


        if(c!=null) 
            c.moveToPosition(position);
            int eno = c.getInt(0);
            String name1 = c.getString(1);
             String sub1=c.getString(2);
             String email1=c.getString(3);

            holder.tv1.setText("" + eno);
            holder.tv2.setText(name1);
            holder.tv3.setText(sub1);
            holder.tv4.setText(email1);

        
        

    @Override
    public int getItemCount() 
            if(c!=null)
            
                return c.getCount();
            
            else 
                return 0;
            
    

    public class ViewHolder extends RecyclerView.ViewHolder 

        public TextView tv1,tv2,tv3,tv4;
        public CardView cv;
        public ViewHolder(View itemView) 
            super(itemView);

            tv1=(TextView) itemView.findViewById(R.id.id);
            tv2=(TextView) itemView.findViewById(R.id.name);
            tv3=(TextView) itemView.findViewById(R.id.sub);
            tv4=(TextView) itemView.findViewById(R.id.email);
            cv=(CardView) itemView.findViewById(R.id.cv);
        
    



public ShowFragment() 
    // Required empty public constructor



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    // Inflate the layout for this fragment
    View v= inflater.inflate(R.layout.fragment_show, container, false);


    MainActivity mainActivity=(MainActivity) getActivity();
    //mainActivity.m.insertEmp(ename,esal,edesig);
    c=mainActivity.m.queryStudent();
    ma.notifyDataSetChanged();


    rv=(RecyclerView) v.findViewById(R.id.rv);

    manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);

    ma=new MynewAdapter();
    rv.setAdapter(ma);
    rv.setLayoutManager(manager);

    return v;

Logcat

E/AndroidRuntime: FATAL EXCEPTION: main                                              Process: com.sujalvivek.com.viewpagerdatabasrecyclerassignment, PID: 4931
                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'void com.sujalvivek.com.viewpagerdatabasrecyclerassignment.ShowFragment$MynewAdapter.notifyDataSetChanged()' on a null object reference

【问题讨论】:

欢迎来到***[SO],请阅读“How to create a Minimal, Complete, and Verifiable example”。 请发布你的日志 张贴在那里.. show_fragment notifyDataSetChange() 中存在空指针异常。如何解决它 【参考方案1】:

我认为您的应用程序崩溃的原因是因为这些行 MainActivity main = new MainActivity(); main.m.insertStudent(Name, Subject, Email);

您应该使用回调来代替这些代码。检查这个link

【讨论】:

是的,我想这行有一些问题..每当我尝试插入值时它都会崩溃。 MainActivity mainActivity = (MainActivity) getActivity(); mainActivity.m.insertstudent(sname,ssubject,semail);我们也可以使用它..但它不会动态更新【参考方案2】:

你的问题在这里:

ma.notifyDataSetChanged();//NullPointerException here because ma is not created yet
rv=(RecyclerView) v.findViewById(R.id.rv);
manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
ma=new MynewAdapter();//put this to the top of this block

【讨论】:

现在解决了它的工作..但是出现了无法插入数据的新问题..填充后单击插入按钮时崩溃

以上是关于片段无法加载到 View_pager tabLayout [重复]的主要内容,如果未能解决你的问题,请参考以下文章

导航抽屉背压片段无法加载

特定片段中的 Snackbar

片段无法转换为 java.util.concurrent.Executor 错误

在我旋转屏幕之前,LiveData 不会加载到片段中

从 RecyclerView 单击 CardView 加载片段

Android OnItemClick 无法将加载的 SQL 数据库加载到列表视图中