2014-01-23 4 views
1

Я следую этому руководству http://anujarosha.wordpress.com/2011/12/12/how-to-insert-data-in-to-a-sqlite-database-in-android/, однако, когда я пытался, я не мог найти свою базу данных в DDMS. Почему это так?Не удается найти базу данных в DDMS

Я не уверен, что это проблема с кодом, однако нет журнала регистрации ошибок. Это мой код

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; 
} 
} 

mainactivity.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 
}}} 
+0

Тестируете это в устройстве или эмуляторе? – Vigbyor

+0

Я тестирую его в эмуляторе – Chloe

+0

Где вы проверяете базу данных? Вы должны создать экземпляр «AndroidOpenDbHelper» в своей деятельности, тогда будет создана только база данных. – GrIsHu

ответ

2

Вы не инициализировать кнопки, Вы только объявили их в деятельности

Button saveButton = null; 
Button cancelButton = null; 

Позже вы необходимо инициализировать их в соответствии с методом onCreate(),

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

Затем вам нужно добавить OnClickListener

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

Первый Инициализировать Ваше ButtonfindViewById с помощью (// Ваш идентификатор здесь)

Второй реализации OnClickListener для Вашего Button, чтобы сохранить содержимое в Database

Проверьте свой File Explorer для вашей базы данных:

1) Windows-->ShowView-->File Explorer

2) data--->data--->you package Name---.databases

3) if Created you will see your database

+0

@Chloe Вы следили за моим ответом, кстати? :) Позвольте мне знать, если вы все еще не нашли его – nitesh

1

Проверить o ут базы данных с вашего Eclipse, выполнив следующие шаги:

  • Window -> Open Perspective -> DDMS
  • Открыть File Explorer окна
  • Исследовать (данные/данные/прикладную PACAKGE имя/баз данных) ** каталога.
  • Внутри у вас есть ваша база данных с именем (myDB), которое вы предоставили.

также инициализировать кнопки для мыши слушателем также ..

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

    setContentView(R.layout.activity_main); 
    saveButton = (Button) findViewById (R.id.yourID); 
    cancelButton = (Button) findViewById (R.id.you ID); 

    saveButton.setOnClickListener(this); 
    cancelButton.setOnClickListener(this); 
} 
+0

как упоминание, я ИМЕЛ! BUT CANT FIND – Chloe

+0

Это означает, что ваша база данных не создана. Вы создали экземпляр класса AndroidOpenDbHelper? – GrIsHu

+0

@GrIsHu, я очень впечатлен: D – Vigbyor

0

Goto File Explorer для Windows> показать вид> Проводник File> Данные> пакет> имя базы данных, чтобы увидеть вашу базу данных в эмуляторе

Смежные вопросы