0

New to Android.i try to load fragment which insert value in SQLite database in View_Pager tab_Layout which is in Main_Activity.And tried to display data in 2nd fragment in view_pager 2nd tab.but it crashes when run the App..unable to load the fragment in view_pager . here is my code i don't know what is the problem in this code.why it is not loading.

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
Sujal
  • 101
  • 1
  • 11

2 Answers2

0

I think the reason your app crashed because of these lines MainActivity main = new MainActivity(); main.m.insertStudent(Name, Subject, Email);

Instead of these code, you should use Callback. check this link

Sơn Phạm
  • 129
  • 1
  • 5
  • ya i guess there is some problem in this line..whenever i try to insert value it crashes. – Sujal Nov 30 '17 at 10:58
  • MainActivity mainActivity = (MainActivity) getActivity(); mainActivity.m.insertstudent(sname,ssubject,semail); we can use this too..but its not updating dynamically – Sujal Dec 02 '17 at 14:49
0

Your problem is here:

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
Viktor Yakunin
  • 2,927
  • 3
  • 24
  • 39
  • solved now its working ..but new problem occurred unable to insert the data..crashed when clicked insert button after filling it – Sujal Nov 30 '17 at 10:57