2017-07-12 4 views
0

フラグメントのリサイクラビューにmySQLiteDBを表示しようとしています。私はMainActivityとしてFragment Activitiesクラスを使用しています。フラグメント内にリサイクラビューを設定しています。 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)  

は、任意の助けてくれてありがとう。

+0

あなたの質問の形式を確認し、がらくたのように見えます。 –

答えて

0

初期化する前に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である

はここにあなたの順序です。

SOLUTION:右クラッシュライン(Cursor cursor = fragmentActivity.get…)上記の行readDB = dbHelper.get…を移動

関連する問題