dimanche 13 septembre 2015

Sharing same database in all Activities in Android (SQLLite)

This is my ProfileActivity (wherein user input their profile info like name, age , gender and birthdate) I have succesfully implement in creating database, storing their profile info on it.

ProfileActivity

public class ProfileActivity extends AppCompatActivity {

//datepicker
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;

//submit button
private Button submit;

static final int DATE_DIALOG_ID = 100;

//variables for database
EditText name,age;
RadioGroup rg;
TextView bday;
MyDBAdapter dbhandler;


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

    //set customize font
    TextView tx = (TextView)findViewById(R.id.header_notification);
    Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/custom.ttf");
    tx.setTypeface(custom_font);

    TextView tx2 = (TextView)findViewById(R.id.submit);
    Typeface custom_font2 = Typeface.createFromAsset(getAssets(), "fonts/text.ttf");
    tx2.setTypeface(custom_font2);

    setDate();
    submit();

    name = (EditText) findViewById(R.id.input_name);
    age = (EditText) findViewById(R.id.input_age);
    //radio group
    rg=(RadioGroup)findViewById(R.id.radiogrp);
    bday = (TextView) findViewById(R.id.showBirthDate);

    //create database
    dbhandler = new MyDBAdapter(this);
}


public void addUser(){
    String addname=name.getText().toString();
    int addage=Integer.parseInt(age.getText().toString());
    String addgender= ((RadioButton)this.findViewById(rg.getCheckedRadioButtonId())).getText().toString();
    String addbday = bday.getText().toString();

    long id2=dbhandler.insertData(addname,addage,addgender,addbday);
    if(id2<0){
        MessageTo.message(this, "Unsuccessful");
    }else{
        MessageTo.message(this, "Successful");
    }
}

public void viewDetails(){
     String data=dbhandler.getAllData();
     MessageTo.message(this, data);
}

public void submit(){

    submit = (Button) findViewById(R.id.submit);

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(ProfileActivity.this, MainMenuActivity.class);
            startActivity(myIntent);

            addUser();
            viewDetails();
        }
    });

}

public void setDate(){

    dateView = (TextView) findViewById(R.id.showBirthDate);
    /* Typeface custom_font5 = Typeface.createFromAsset(getAssets(), "fonts/text.ttf");
    dateView.setTypeface(custom_font5); */

    calendar = Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);

    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);
    showDate(year, month+1, day);

}

@SuppressWarnings("deprecation")
public void setDate(View view) {
    showDialog(DATE_DIALOG_ID);
    /*
    Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
            .show();
    */
}

@Override
protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    if (id == DATE_DIALOG_ID) {
        return new DatePickerDialog(this, myDateListener, year, month, day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        // arg1 = year
        // arg2 = month
        // arg3 = day
        showDate(arg1, arg2+1, arg3);
    }
};

private void showDate(int year, int month, int day) {
    dateView.setText(new StringBuilder().append(month).append("/")
            .append(day).append("/").append(year));
}

@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_profile, 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);
}

}

I tried to display that stored data into another activity so that. BUT FAILED.......

ManageProfileActivity

public class ManageProfileActivity extends AppCompatActivity {

private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
private ImageButton back;
static final int DATE_DIALOG_ID = 100;

//variables for database
EditText name,age;
RadioGroup rg;
RadioButton male;
RadioButton female;
TextView bday;
MyDBAdapter dbadapter;
MyDBHandler dbhandler;

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

    //set customize font
    TextView tx = (TextView)findViewById(R.id.header_notification);
    Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/custom.ttf");
    tx.setTypeface(custom_font);

    TextView tx2 = (TextView)findViewById(R.id.edit);
    Typeface custom_font2 = Typeface.createFromAsset(getAssets(), "fonts/text.ttf");
    tx2.setTypeface(custom_font2);

    TextView tx3 = (TextView)findViewById(R.id.delete);
    Typeface custom_font3 = Typeface.createFromAsset(getAssets(), "fonts/text.ttf");
    tx3.setTypeface(custom_font3);

    setDate();
    back();

    name = (EditText) findViewById(R.id.input_name);
    age = (EditText) findViewById(R.id.input_age);
    //radio group
    rg=(RadioGroup)findViewById(R.id.radiogrp);
    male =(RadioButton)findViewById(R.id.male);
    female =(RadioButton)findViewById(R.id.female);
    bday = (TextView) findViewById(R.id.showBirthDate);

    //user profile
    getDetail();
    dbadapter = new MyDBAdapter(this);

}

public void getDetail(){
    int id = 1;

    SQLiteDatabase db=dbhandler.getWritableDatabase();

    //columns
    String[] columns={dbhandler.COLUMN_NAME,dbhandler.COLUMN_AGE,dbhandler.COLUMN_GENDER,dbhandler.COLUMN_BIRTHDATE};
    Cursor cursor=db.query(dbhandler.TABLE_PROFILE,columns,dbhandler.COLUMN_ID+" = '"+id+"'",null,null,null,null);
    while(cursor.moveToNext()){
        int index1=cursor.getColumnIndex(dbhandler.COLUMN_NAME);
        int index2=cursor.getColumnIndex(dbhandler.COLUMN_AGE);
        int index3=cursor.getColumnIndex(dbhandler.COLUMN_GENDER);
        int index4=cursor.getColumnIndex(dbhandler.COLUMN_BIRTHDATE);
        String username=cursor.getString(index1);
        String userage=cursor.getString(index2);
        String usergender=cursor.getString(index3);
        String userbday=cursor.getString(index4);
    }

}

//Back button
public void back(){

    back = (ImageButton) findViewById(R.id.backbtn);

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(ManageProfileActivity.this, SettingsActivity.class);
            startActivity(myIntent);
        }
    });
}

public void setDate(){

    dateView = (TextView) findViewById(R.id.showBirthDate);
    /* Typeface custom_font5 = Typeface.createFromAsset(getAssets(), "fonts/text.ttf");
    dateView.setTypeface(custom_font5); */

    calendar = Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);

    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);
    showDate(year, month+1, day);

}

@SuppressWarnings("deprecation")
public void setDate(View view) {
    showDialog(DATE_DIALOG_ID);
    /*
    Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
            .show();
    */
}

@Override
protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    if (id == DATE_DIALOG_ID) {
        return new DatePickerDialog(this, myDateListener, year, month, day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        // arg1 = year
        // arg2 = month
        // arg3 = day
        showDate(arg1, arg2+1, arg3);
    }
};

private void showDate(int year, int month, int day) {
    dateView.setText(new StringBuilder().append(month).append("/")
            .append(day).append("/").append(year));
}


@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_manage_profile, 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);
}

}

This is my MyDBAdapter (a class that handles the database)

MyDBAdapter

public class MyDBAdapter{

MyDBHandler dbhandler;
public MyDBAdapter(Context context){
    dbhandler = new MyDBHandler(context);
}

public long insertData(String name, int age, String gender,String bday){
    SQLiteDatabase db=dbhandler.getWritableDatabase();
    ContentValues values=new ContentValues();
    values.put(MyDBHandler.COLUMN_NAME, name);
    values.put(MyDBHandler.COLUMN_AGE, age);
    values.put(MyDBHandler.COLUMN_GENDER, gender);
    values.put(MyDBHandler.COLUMN_BIRTHDATE, bday);
    long id2=db.insert(MyDBHandler.TABLE_PROFILE, null, values);
    return id2;
}

public String getAllData(){
    SQLiteDatabase db=dbhandler.getWritableDatabase();

    //columns
    String[] columns={MyDBHandler.COLUMN_ID,MyDBHandler.COLUMN_NAME,MyDBHandler.COLUMN_AGE,MyDBHandler.COLUMN_GENDER,MyDBHandler.COLUMN_BIRTHDATE};
    Cursor cursor=db.query(MyDBHandler.TABLE_PROFILE,columns,null,null,null,null,null);
    StringBuffer buffer = new StringBuffer();
    while(cursor.moveToNext()){
        int cid=cursor.getInt(0);
        String name=cursor.getString(1);
        String age=cursor.getString(2);
        String gender=cursor.getString(3);
        String bday=cursor.getString(4);
        buffer.append(cid+" "+name+" "+age+" "+gender+" "+bday+"\n");
    }

    return buffer.toString();
}

public String getData(int id){
    SQLiteDatabase db=dbhandler.getWritableDatabase();

    //columns
    String[] columns={MyDBHandler.COLUMN_NAME,MyDBHandler.COLUMN_AGE,MyDBHandler.COLUMN_GENDER,MyDBHandler.COLUMN_BIRTHDATE};
    Cursor cursor=db.query(MyDBHandler.TABLE_PROFILE,columns, MyDBHandler.COLUMN_ID+" = '"+id+"'",null,null,null,null);
    StringBuffer buffer = new StringBuffer();
    while(cursor.moveToNext()){
        int index1=cursor.getColumnIndex(MyDBHandler.COLUMN_NAME);
        int index2=cursor.getColumnIndex(MyDBHandler.COLUMN_AGE);
        int index3=cursor.getColumnIndex(MyDBHandler.COLUMN_GENDER);
        int index4=cursor.getColumnIndex(MyDBHandler.COLUMN_BIRTHDATE);
        String username=cursor.getString(index1);
        String userage=cursor.getString(index2);
        String usergender=cursor.getString(index3);
        String userbday=cursor.getString(index4);
        buffer.append(username+" "+userage+" "+usergender+" "+userbday+"\n");
    }
    return buffer.toString();
}



 static class MyDBHandler extends SQLiteOpenHelper{
   private static final int DATABASE_VERSION = 8;
   private static final String DATABASE_NAME = "profile.db";
   public static final String TABLE_PROFILE = "profile";
   public static final String COLUMN_ID = "_id";
   public static final String COLUMN_NAME = "name";
   public static final String COLUMN_AGE = "age";
   public static final String COLUMN_GENDER = "gender";
   public static final String COLUMN_BIRTHDATE = "birthdate";
   private Context context;

   public MyDBHandler(Context context) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
       this.context=context;
       MessageTo.message(context,"constructor called");
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE_PROFILE ="CREATE TABLE " + TABLE_PROFILE + "("
               + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
               + COLUMN_NAME + " TEXT,"
               + COLUMN_AGE + " INTEGER, "
               + COLUMN_GENDER + " TEXT,"
               + COLUMN_BIRTHDATE + " TEXT" + ")";

       db.execSQL(CREATE_TABLE_PROFILE);
       MessageTo.message(context, "onCreate called");
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       MessageTo.message(context, "onUpgrade called");
       db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROFILE);
       onCreate(db);
   }

Can you tell me how to display the data in ManageProfileActivity? I only want to display one single row in the database. I'm new to Android. THANKS FOR HELP.

Aucun commentaire:

Enregistrer un commentaire