繁体   English   中英

在swipeview片段的内部使用回收站视图

[英]Using a recycler view inside a fragment of a swipeview

我试图在片段的回收器视图中显示mySQLiteDB。 如果可以的话,我正在使用Fragment Activities类作为MainActivity。 我正在片段内设置回收站视图。 getAllFixedCosts方法未像我希望的那样显示所有数据。 这是整个片段活动:

    public class FragmentActivity extends AppCompatActivity {

    int MoneyAmount;
    String FixedCostItem;
    int FixedItemCostAmount;

      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment);

        SharedPreferences sharedPrefs = getSharedPreferences("MyPrefs", 0);
        String Money = (sharedPrefs.getString("AMOUNTMONEY", "WhatsUP"));
        MoneyAmount = Integer.parseInt(Money);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        Cursor cursor = getAllFixedCosts();
        mAdapter = new FixedCostsAdapter(this, cursor);

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    public Cursor getAllFixedCosts() {
        return readDB.query(
                FixedCostsContract.FixedCostsEntry.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                null);
    }

    public void addFixedCost(String FixedItem, String FixedCostAmount){
        if(FixedItem.length() == 0 ||
                FixedCostAmount.length() == 0){
            return;
        }


            FixedItemCostAmount = Integer.parseInt(FixedCostAmount);
        addFixedCostDB(FixedCostItem, FixedItemCostAmount);

        mAdapter.swapCursor(getAllFixedCosts());


    }


    private void addFixedCostDB(String FixedCostItem,int FixedCostItemAmount) {
        ContentValues cv = new ContentValues();
        cv.put(FixedCostsContract.FixedCostsEntry.COLUMN_COST_NAME, FixedCostItem);
        cv.put(FixedCostsContract.FixedCostsEntry.COLUMN_COST_AMOUNT, FixedCostItemAmount);
        mDB.insert(FixedCostsContract.FixedCostsEntry.TABLE_NAME, null, cv);
        mDB.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_, 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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
           switch (position){
               case 0:
                   FixedCosts fixedCosts = new FixedCosts();

                   return fixedCosts;
           }
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Fixed Costs";
                case 1:
                    return "Long term investments";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
    }
}

滑动视图的第一个片段应该具有一个回收站视图,该视图显示来自SQLiteDB的数据,但是在调用时崩溃。 这是片段:

public class FixedCosts extends Fragment {
SQLiteDatabase mDB;
SQLiteDatabase readDB;
FixedCostsAdapter mAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
    SharedPreferences sharedPrefs = this.getActivity().getSharedPreferences("MyPrefs", 0);
    Button launchDialog = (Button) view.findViewById(R.id.AddNewFixedCostsButton);
    launchDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment dialog = new InfoDialogFragment();
            dialog.show(getFragmentManager(), "dialog");
        }
    });
    FragmentActivity fragmentActivity = new FragmentActivity();




    String amount = (sharedPrefs.getString("AMOUNTMONEY", "WhatsUP"));
    String TextAmount = "$"+amount;
    RecyclerView FCRecycler = (RecyclerView) view.findViewById(R.id.FixedCostsRV);
    FixedCostsDbHelper dbHelper = new FixedCostsDbHelper(getActivity());
    mDB = dbHelper.getWritableDatabase();
    Cursor cursor = fragmentActivity.getAllFixedCosts();
    mAdapter = new FixedCostsAdapter(getActivity(), cursor);
    FCRecycler.setAdapter(mAdapter);
    readDB = dbHelper.getReadableDatabase();
    FCRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));



        TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
        TitletextView.setText(TextAmount);

        return view;
    }
}

我试图通过发送将其作为参数来获取用户输入的数据。 这是获取SQLiteDB数据的对话框片段:

public class InfoDialogFragment extends DialogFragment {

public InfoDialogFragment() {
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    final AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
    final LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.info_dialogfrag, null);
    adb.setView(view);
    final EditText itemET = (EditText)view.findViewById(R.id.getItem);
    final EditText itemAmountET = (EditText)view.findViewById(R.id.getItemAmount);



            adb
            /*.setIcon()*/
            .setTitle("Fixed Cost")
            .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String FixedCostItem = itemET.getText().toString();
                    String FixedCostItemAmount = itemAmountET.getText().toString();
                    if(FixedCostItem.length() == 0 || FixedCostItemAmount.length() == 0){
                        Toast.makeText(getActivity(),"Enter Item and Amount", Toast.LENGTH_SHORT).show();
                    }else{
                        FragmentActivity fragmentActivity = new FragmentActivity();
                        fragmentActivity.addFixedCost(FixedCostItem, FixedCostItemAmount);
                        dialog.dismiss();


                    }



                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                        InfoDialogFragment.this.getDialog().cancel();
                    }
                });
        return adb.create();
    }
}

最后,我有一个适配器,给出了NullPointerException。 我认为这堂课是对的,但是在此过程中,它会受到其他因素的影响。 这是适配器:

public class FixedCostsAdapter extends RecyclerView.Adapter<FixedCostsAdapter.FixedCostViewHolder> {

private Cursor mCursor;
private Context mContext;

public FixedCostsAdapter(Context context, Cursor cursor) {
    this.mContext = context;
    this.mCursor = cursor;
}
public void swapCursor(Cursor newCursor) {
    // Always close the previous mCursor first
    if (mCursor != null) mCursor.close();
    mCursor = newCursor;
    if (newCursor != null) {
        // Force the RecyclerView to refresh
        this.notifyDataSetChanged();
    }
}

@Override
public FixedCostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View view = inflater.inflate(R.layout.recyclerviewlayout, parent, false);
    return new FixedCostViewHolder(view);
}

@Override
public void onBindViewHolder(FixedCostViewHolder holder, int position) {
    if (!mCursor.moveToPosition(position))
        return; // bail if returned null

    // Update the view holder with the information needed to display
    String name = mCursor.getString(mCursor.getColumnIndex(FixedCostsContract.FixedCostsEntry.COLUMN_COST_NAME));
    int costAmount = mCursor.getInt(mCursor.getColumnIndex(FixedCostsContract.FixedCostsEntry.COLUMN_COST_AMOUNT));
    // COMPLETED (6) Retrieve the id from the cursor and
    long id = mCursor.getLong(mCursor.getColumnIndex(FixedCostsContract.FixedCostsEntry._ID));

    // Display the guest name
    holder.item.setText(name);
    // Display the party count
    holder.amount.setText(String.valueOf(costAmount));
    // COMPLETED (7) Set the tag of the itemview in the holder to the id
    holder.itemView.setTag(id);
}

@Override
public int getItemCount() {
    return mCursor.getCount();
}

class FixedCostViewHolder extends RecyclerView.ViewHolder {
        TextView item;
        TextView amount;

        public FixedCostViewHolder(View itemView) {
            super(itemView);
            item = (TextView)itemView.findViewById(R.id.textItem);
            amount = (TextView)itemView.findViewById(R.id.textAmount);
        }
    }
}

错误日志:

07-12 18:54:13.289 12915-12915/com.example.android.budgetcrunch 

    E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                      Process: com.example.android.budgetcrunch, PID: 12915


        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.budgetcrunch/com.example.android.budgetcrunch.FragmentActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)' on a null object reference
                                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
                                                                                          at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
                                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                                          at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)' on a null object reference
                                                                                          at com.example.android.budgetcrunch.FragmentActivity.getAllFixedCosts(FragmentActivity.java:79)
                                                                                          at com.example.android.budgetcrunch.FragmentActivity.onCreate(FragmentActivity.java:66)
                                                                                          at android.app.Activity.performCreate(Activity.java:6942)
                                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
                                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988) 
                                                                                          at android.app.ActivityThread.-wrap14(ActivityThread.java) 
                                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631) 
                                                                                          at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                          at android.os.Looper.loop(Looper.java:154) 
                                                                                          at android.app.ActivityThread.main(ActivityThread.java:6682) 
                                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
                                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 

感谢您的任何帮助。

您正在初始化readDB之前调用它。

这是您的错误:

java.lang.NullPointerException: com.example.android.budgetcrunch.FragmentActivity.getAllFixedCosts(FragmentActivity.java:79)

初始化之前,您正在调用方法getAllFixedCosts()

这是您的顺序:

Cursor cursor = fragmentActivity.getAllFixedCosts(); // THIS CRASHES
mAdapter = new FixedCostsAdapter(getActivity(), cursor);
FCRecycler.setAdapter(mAdapter);
readDB = dbHelper.getReadableDatabase(); // THIS INITIALIZES THE DB

因此, getAllFixedCosts()正在执行:

return readDB.query(…

但是readDB在您调用时为null。

解决方案:将行readDB = dbHelper.get…移动到崩溃的行的正上方( Cursor cursor = fragmentActivity.get…

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM