SQLiteDatabase不显示信息ImageButton崩溃应用程序

时间:2016-04-06 04:53:39

标签: java android listview android-fragments android-sqlite

我为我的班级项目创建卡路里应用程序。我试图实现一个数据库来存储用户添加的卡路里信息,这些信息将显示在列表视图中。用户将在add_entry片段中输入卡路里,并显示在listview中的fragment_home页面上。

问题:我不确定是否使用条目添加片段将信息正确添加到数据库,以便在列表视图中显示信息。这是我第一次使用Android Studio / App。

问题2: 出于某些原因,当我点击我的homefragment应用程序上的图像按钮崩溃时 它不会去add_entry片段

logcat的:

         04-06 00:33:41.213 30567-30567/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: com.example.treycoco.calorietracker, PID: 30567
                                                                                 java.lang.IllegalStateException: Could not find method Click(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'AddItems'
                                                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
                                                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                                     at android.view.View.performClick(View.java:5697)
                                                                                     at android.view.View$PerformClick.run(View.java:22526)
                                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:158)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

FragmentHome.java

                  public class FragmentHome extends Fragment implements
         View.OnClickListener  {

        public static final String ARG_SECTION_NUMBER = "section_number";
        public static final String ARG_ID = "_id";
        private TextView label;
        private int sectionNumber = 0;
        private Calendar fragmentDate;
         ListView  listview;
         ImageButton AddEntrybtn;
           CalorieDatabase calorieDB;

            private android.support.v4.app.FragmentManager fragmentManager;
       private FragmentTransaction fragmentTransaction;

           public FragmentHome() {
            // Required empty public constructor
          }
        @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

      View myView = inflater.inflate(R.layout.fragment_home, container,
         false);
      label= (TextView) myView.findViewById(R.id.section_label);
        AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
          return myView;
             }

            @Override
         public void onActivityCreated(Bundle savedInstanceState) {
          super.onActivityCreated(savedInstanceState);

            Bundle username = getActivity().getIntent().getExtras();



           String username1 = username.getString("Username");

          TextView userMain= (TextView) getView().findViewById(R.id.User);

        userMain.setText(username1);

        openDataBase();

    }



          private  void openDataBase (){


      calorieDB= new CalorieDatabase(getActivity());
       calorieDB.open();


     }

   private void closeDataBase(){
         calorieDB.close();
       };


       private  void populateLVFromDB(){

    Cursor cursor = calorieDB.getAllRows();




    String[] fromFieldNames = new String[]
            {CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
    int[] toViewIDs = new int[]
            {R.id.foodEditText,     R.id.caloriesEditText,           };


                   SimpleCursorAdapter myCursorAdapter =
                   new SimpleCursorAdapter(
                      getActivity(),        
                     R.layout.row_item,
                       cursor,                  
                      fromFieldNames,           
                        toViewIDs                
                      );


         listview = (ListView) getActivity().findViewById(R.id.listView);
          listview.setAdapter(myCursorAdapter);


             }


              @Override
          public void onResume() {
             super.onResume();
         // set label to selected date.  Get date from Bundle.
    int dayOffset = sectionNumber - FragmentHomeDayViewPager.pagerPageToday;
    fragmentDate = Calendar.getInstance();
    fragmentDate.add(Calendar.DATE, dayOffset);
    SimpleDateFormat sdf = new SimpleDateFormat(appMain.dateFormat);

           String labelText = sdf.format(fragmentDate.getTime());
          switch (dayOffset) {
               case 0:
             labelText += " (Today)";
                 break;
              case 1:
                 labelText += " (Tomorrow)";
                   break;
              case -1:
              labelText += " (Yesterday)";
                 break;
              }
            label.setText(labelText);

   }



           @Override
          public void onDestroy() {
                super.onDestroy();

             }


                @Override
            public void onDetach() {
                super.onDetach();

         startActivity( new Intent(getContext(),MainActivity.class));
          }


         @Override
          public void onClick(View v) {
              switch (v.getId()) {
                   case R.id.AddItems:

            AddEntry addEntry    = new AddEntry();

            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                    .commit();


            break;
             }


         }
        }

CalorieDatabase.java

                    public class CalorieDatabase {

             private static final String TAG = "DBAdapter";


         public static final String KEY_ROWID = "_id";
             public static final int COL_ROWID = 0;


        public static final String KEY_NAME = "Description";

       public static final String KEY_CalorieValue = "Calories";


           public static final int COL_NAME = 1;
              public static final int COL_CalorieValue= 2;



        public static final String[] ALL_KEYS = new String[] {KEY_ROWID,
          KEY_NAME, KEY_CalorieValue};

        public static final String DATABASE_NAME = "CalorieDb";
      public static final String DATABASE_TABLE = "Calorie_Info";

          public static final int DATABASE_VERSION = 1;

           private static final String DATABASE_CREATE_SQL =
              "create table " + DATABASE_TABLE
                + " (" + KEY_ROWID + " integer primary key autoincrement, "


                + KEY_NAME + " text not null, "
                + KEY_CalorieValue + " integer not null, "


                + ");";


         private final Context context;

        private DatabaseHelper myDBHelper;
            private SQLiteDatabase db;



            public CalorieDatabase(Context ctx) {
              this.context = ctx;
               myDBHelper = new DatabaseHelper(context);
              }

           public CalorieDatabase open() {
              db = myDBHelper.getWritableDatabase();
                return this;
              }


            public void close() {
              myDBHelper.close();
           }


        public long insertRow(String description, int CalorieVal) {


           ContentValues initialValues = new ContentValues();
           initialValues.put(KEY_NAME, description);
           initialValues.put(KEY_CalorieValue, CalorieVal);


          return db.insert(DATABASE_TABLE, null, initialValues);
             }


            public boolean deleteRow(long rowId) {
                String where = KEY_ROWID + "=" + rowId;
               return db.delete(DATABASE_TABLE, where, null) != 0;
                  }

                   public void deleteAll() {
                 Cursor c = getAllRows();
                 long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
                 if (c.moveToFirst()) {
                     do {
                    deleteRow(c.getLong((int) rowId));
                   } while (c.moveToNext());
             }
               c.close();
               }


              public Cursor getAllRows() {
               String where = null;
                 Cursor c =     db.query(true, DATABASE_TABLE, ALL_KEYS,
            where, null, null, null, null, null);
               if (c != null) {
                     c.moveToFirst();
                 }
                    return c;
                          }


                 public Cursor getRow(long rowId) {
             String where = KEY_ROWID + "=" + rowId;
               Cursor c =   db.query(true, DATABASE_TABLE, ALL_KEYS,
               where, null, null, null, null, null);
                if (c != null) {
                     c.moveToFirst();
                    }
                   return c;
                    }


              public boolean updateRow(long rowId, String description, int 
          CalorieValue) {
               String where = KEY_ROWID + "=" + rowId;


             ContentValues newValues = new ContentValues();
            newValues.put(KEY_NAME, description);
                newValues.put(KEY_CalorieValue, CalorieValue);



         return db.update(DATABASE_TABLE, newValues, where, null) != 0;
                  }

           private static class DatabaseHelper extends SQLiteOpenHelper
             {
                  DatabaseHelper(Context context) {
                   super(context, DATABASE_NAME, null, DATABASE_VERSION);
                    }

                             @Override
                  public void onCreate(SQLiteDatabase _db) {
                     _db.execSQL(DATABASE_CREATE_SQL);
                        }

                        @Override
             public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
                     newVersion) {
               Log.w(TAG, "Upgrading application's database from version " +
            oldVersion
                + " to " + newVersion + ", which will destroy all old
                 data!");


                     _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);


                      onCreate(_db);
                    }
               }
        }

AddEntry.java

                      public class AddEntry extends Fragment implements
                   View.OnClickListener  {

               EditText DescriptionET,CalorieET;


              ImageButton savebtn;

           String description , calorieAmt;
             CalorieDatabase calorieDB;
             public AddEntry() {
             // Required empty public constructor
             }





               @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
                 // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_add_entry, container, false);
               }


           @Override
      public void onViewCreated(View view, Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);

      DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
       CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);



           }

               @Override
                 public void onClick(View v) {
                     switch (v.getId()) {


                      case R.id.SaveBtn:

                      description = DescriptionET.getText().toString();
                      calorieAmt=CalorieET.getText().toString();





                         break;


                     case R.id.CancelBtn:


                          break;
                      }
                      }



                @Override
          public void onDestroy() {
                super.onDestroy();

            }

             @Override
          public void onDetach() {
                super.onDetach();
              }

                   }

4 个答案:

答案 0 :(得分:0)

尝试替换此内容,从语句中删除最后的逗号(,)

 private static final String DATABASE_CREATE_SQL =
              "create table " + DATABASE_TABLE
                + " (" + KEY_ROWID + " integer primary key autoincrement, "
                + KEY_NAME + " text not null, "
                + KEY_CalorieValue + " integer not null "
                + ");";

答案 1 :(得分:0)

从上一个字段中删除,

private static final String DATABASE_CREATE_SQL =
              "create table " + DATABASE_TABLE
                + " (" + KEY_ROWID + " integer primary key autoincrement, "
                + KEY_NAME + " text not null, "
                + KEY_CalorieValue + " integer not null "
                + ");";

答案 2 :(得分:0)

private static final String DATABASE_NAME =" CalorieDb.db";

然后在oncreat()

中调用下面的方法
public void checkDB() {
    try {

        //android default database location is : /data/data/youapppackagename/databases/
        String packageName = this.getPackageName();
        String destPath = "/data/data/" + packageName + "/databases";
        String fullPath = "/data/data/" + packageName + "/databases/"
                + DATABASE_NAME;

        //this database folder location
        File f = new File(destPath);

        //this database file location
        File obj = new File(fullPath);

        //check if databases folder exists or not. if not create it
        if (!f.exists()) {
            f.mkdirs();
            f.createNewFile();
        }

        //check database file exists or not, if not copy database from assets
        if (!obj.exists()) {
            this.CopyDB(fullPath);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();

    }
}

Unintall应用程序和清理并重建项目然后我认为解决您的问题。

答案 3 :(得分:-2)

private static final String DATABASE_CREATE_SQL =
          " create table " + DATABASE_TABLE
            + " ( " + KEY_ROWID + " integer primary key autoincrement, "
            + KEY_NAME + " text not null, "
            + KEY_CalorieValue + " integer not null, "
            + " ); ";

添加空格“)”