片段无法在View_pager tabLayout中加载

时间:2017-11-30 10:11:57

标签: android sqlite android-fragments android-viewpager

Android.i的新手尝试加载片段,该片段在View_ager中的SQLite数据库中插入值_Laout在Main_Activity.And中试图在view_pager第二个标签中显示第二个片段中的数据。但是当运行App..unable时它崩溃了在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;
    }
}

MainActivity

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

InsertFragment

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;
}

}

showfragment

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

2 个答案:

答案 0 :(得分:0)

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

您应该使用Callback代替这些代码。检查此link

答案 1 :(得分:0)

你的问题在这里:

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