android - 在 DDMS 中找不到数据库

标签 android

我正在关注本教程 http://anujarosha.wordpress.com/2011/12/12/how-to-insert-data-in-to-a-sqlite-database-in-android/ , 然而, 当我尝试时,我无法在 DDMS 中找到我的数据库。 为什么会这样?

不知道是不是代码问题,但是没有eror log。 这是我的代码

AndroidDBHelper.java

public class AndroidOpenDbHelper extends  SQLiteOpenHelper {

    // Database attributes
            public static final String DB_NAME = "myDB";
            public static final int DB_VERSION = 2;
            // Table attributes
            public static final String TABLE_NAME_LOG = "fuelLog";
            public static final String KEY_ROWID = "_id";
            public static final String KEY_DATE = "date";
            public static final String KEY_PRICE = "fuelprice";
            public static final String KEY_FUEL = "fuelpump";
            public static final String KEY_COST = "tcost";
            public static final String KEY_ODM = "odometer";
            public static final String KEY_CON = "fcon";

            public AndroidOpenDbHelper(Context context) {
                super(context, DB_NAME, null, DB_VERSION);
            }
            // Called when the database is created for the first time. 
            //This is where the creation of tables and the initial population of the tables should happen.


            @Override
            public void onCreate(SQLiteDatabase db) {
                // TODO Auto-generated method stub
                // We need to check whether table that we are going to create is already exists.
                //Because this method get executed every time we created an object of this class. 
                //"create table if not exists TABLE_NAME ( BaseColumns._ID integer primary key autoincrement, FIRST_COLUMN_NAME text not null, SECOND_COLUMN_NAME integer not null);"
                String SQL_createTable = "create table if not exists " + TABLE_NAME_LOG + " ( " + BaseColumns._ID + " integer primary key autoincrement, " 
                                                                        + KEY_DATE + " text not null, "
                                                                        + KEY_PRICE + " text not null, "
                                                                        + KEY_FUEL + " text not null, "
                                                                        + KEY_COST + " text not null, "
                                                                        + KEY_ODM + " text not null, "
                                                                        + KEY_CON + " text not null);";
                // Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
                db.execSQL(SQL_createTable);

            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if(oldVersion == 1 && newVersion == 2){
                        // Upgrade the database
                    }       
                }
            }

fuelLogPojo.java

public class fuelLogPojo {
     private String date;
     private String price;
     private String pump;
     private String cost;
     private String odometer;
     private String fcon;


     public String getdate() {
             return date;
     }
     public void setdate(String date) {
             this.date = date;
     }

     public String getprice() {
             return price;
     }
     public void setprice(String price) {
             this.price = price;
     }

     public String getpump() {
             return pump;
     }
     public void setpump(String pump) {
             this.pump = pump;
     }

     public String getcost() {
         return cost;
 }
 public void setcost(String cost) {
         this.cost = cost;
 }

 public String getodometer() {
     return odometer;
}
public void setodometer(String odometer) {
     this.odometer = odometer;
}

public String getfcon() {
  return fcon;
}
public void setfcon(String fcon) {
  this.fcon = fcon;
}
}

主要 Activity .java

public class MainActivity extends Activity {

    // TableLayout tablelayout_Log = null;
    Button saveButton = null;
    Button cancelButton = null;
   // Button searchButton = null;
    static EditText dateEdit; 
    EditText priceEdit;
    EditText pumpEdit;
    TextView costView;
    EditText odometerEdit;
    TextView fconView;
     TextWatcher textWatcher;
     String priceEditStr ="",pumpEditStr="";
     String  odmEditStr = "";
     String lastOdm = "";

double result;
double resultCon;
private int mYear;
private int mMonth;
private int mDay;

static final int DATE_DIALOG_ID = 0;


private ArrayList fuelLogArrayList;

    public boolean isNumeric(String str)
    {
        return str.matches("-?\\d+(\\.\\d+)?"); 
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        costView = (TextView)findViewById(R.id.tcost);
        dateEdit = (EditText)findViewById(R.id.date);
        priceEdit = (EditText)findViewById(R.id.fuelprice);
        pumpEdit = (EditText)findViewById(R.id.fuelpump);
        odometerEdit = (EditText)findViewById(R.id.odometer);
        fconView = (TextView)findViewById(R.id.fcon);
        fuelLogArrayList = new ArrayList();

       // DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
       // lastOdm = dbAdaptor.getLastOdometer();
//Check that your database is enable to fetch the value or not? 
//Toast.makeText(getApplicationContext()," "+lastOdm,Toast.LENGTH_LONG).show();

        dateEdit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               // showDialog(DATE_DIALOG_ID);
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datePicker");
            }
        });


           priceEdit.addTextChangedListener(new TextWatcher() {

               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it
                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !priceEdit.getText().toString().trim().equalsIgnoreCase(null))
                        priceEditStr = priceEdit.getText().toString().trim();
                   if(!pumpEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(null))
                        pumpEditStr = pumpEdit.getText().toString().trim();

                  if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                  {
                    result = Double.parseDouble(priceEditStr) * Double.parseDouble(pumpEditStr);              
                    costView.setText(" "+result);
                  }

               }
           });

           pumpEdit.addTextChangedListener(new TextWatcher() {

               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it
                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase(""))
                        priceEditStr = priceEdit.getText().toString().trim();
                   if(!pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                        pumpEditStr = pumpEdit.getText().toString().trim();


                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                      {
                        result = Double.parseDouble(priceEditStr) * Double.parseDouble(pumpEditStr);              
                        costView.setText(" "+result);
                      }

               }
           });







           odometerEdit.addTextChangedListener(new TextWatcher() {
               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }



               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it

                   if(!odometerEdit.getText().toString().trim().equalsIgnoreCase(""))
                       odmEditStr = odometerEdit.getText().toString().trim();


                  if(!odometerEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase("") && !lastOdm.trim().equalsIgnoreCase(null) && !lastOdm.trim().equalsIgnoreCase(" "))
                     {

                       resultCon = Double.parseDouble(odmEditStr) / Double.parseDouble(pumpEditStr);              
                       fconView.setText(" "+resultCon);
                     }

               }
           });

    }

    public void onClick(View v) {
        if(v.getId() == R.id.cancelBTN){
            finish();
        }else if(v.getId() == R.id.saveBTN){
            // Get the values provided by the user via the UI


             String date = dateEdit.getText().toString();
             String price = priceEdit.getText().toString();
             String pump = pumpEdit.getText().toString();
             String tcost = costView.getText().toString();
             String odometer = odometerEdit.getText().toString();
             String fcon = fconView.getText().toString();


            // Pass above values to the setter methods in POJO class
             fuelLogPojo fuelLogPojoObj = new fuelLogPojo();
             fuelLogPojoObj.setdate(date);
             fuelLogPojoObj.setprice(price);
             fuelLogPojoObj.setpump(pump);
             fuelLogPojoObj.setcost(tcost);
             fuelLogPojoObj.setodometer(odometer);
             fuelLogPojoObj.setfcon(fcon);
            // Add an undergraduate with his all details to a ArrayList
             fuelLogArrayList.add(fuelLogPojoObj);

            // Inserting undergraduate details to the database is doing in a separate method
            insertLog(fuelLogPojoObj);

            // Release from the existing UI and go back to the previous UI
            finish();
        }
    }

    private void insertLog(fuelLogPojo fuelLogPojoObj) {


        // TODO Auto-generated method stub
        // First we have to open our DbHelper class by creating a new object of that
        AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(this);

        // Then we need to get a writable SQLite database, because we are going to insert some values
        // SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.
        SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();

        // ContentValues class is used to store a set of values that the ContentResolver can process.
        ContentValues contentValues = new ContentValues();

        // Get values from the POJO class and passing them to the ContentValues class
        contentValues.put(AndroidOpenDbHelper.KEY_DATE, fuelLogPojoObj.getdate());
        contentValues.put(AndroidOpenDbHelper.KEY_PRICE, fuelLogPojoObj.getprice());
        contentValues.put(AndroidOpenDbHelper.KEY_FUEL, fuelLogPojoObj.getpump());
        contentValues.put(AndroidOpenDbHelper.KEY_COST, fuelLogPojoObj.getcost());
        contentValues.put(AndroidOpenDbHelper.KEY_ODM, fuelLogPojoObj.getodometer());
        contentValues.put(AndroidOpenDbHelper.KEY_CON, fuelLogPojoObj.getfcon());

        // Now we can insert the data in to relevant table
        // I am going pass the id value, which is going to change because of our insert method, to a long variable to show in Toast
        long affectedColumnId = sqliteDatabase.insert(AndroidOpenDbHelper.TABLE_NAME_LOG, null, contentValues);

        // It is a good practice to close the database connections after you have done with it
        sqliteDatabase.close();

        // I am not going to do the retrieve part in this post. So this is just a notification for satisfaction ;-)
        Toast.makeText(this, "Values inserted column ID is :" + affectedColumnId, Toast.LENGTH_SHORT).show();        





    }

    public static class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {

        public EditText editText;
        DatePicker dpResult;

    public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker

    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    //return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {

        dateEdit.setText(String.valueOf(day) + "/"
                + String.valueOf(month + 1) + "/" + String.valueOf(year));
        // set selected date into datepicker also
}}}

最佳答案

你还没有初始化你的按钮,你只在你的 Activity 中声明了它们

Button saveButton = null;
Button cancelButton = null;

稍后您需要在 onCreate() 方法中初始化它们,如下所示,

saveButton = (Button) findViewById ( your ID );
cancelButton = (Button) findViewById ( you ID );

然后需要添加OnClickListener

saveButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);

关于android - 在 DDMS 中找不到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21308632/

相关文章:

php - 如何保护 PHP 和 Android 之间的连接

android - 带标签/标签的照片的云存储架构/解决方案

android - 如果 kotlin 协程作业需要相当长的时间才能完成,如何有效地显示加载对话框?

android - 如何禁用 ColumnHeader 和 RowHeader 并禁用 SelectedColor

处理视频时 Android MediaCodec : video file processing: add the original audio,

android - Lazy List 上的位图缓存(SoftReference,Hard)似乎无法正常工作 - Android

android从extends AsyncTask创建一个对象并将其发送到另一个 Activity

java - 销毁SurfaceView后如何返回主Activity?

android - 生成的客户端库上的 NoClassDefFoundError - GAE 云端点

android - Google Place api for android : How to know which is address, 城市或郊区从谷歌返回