Write a diary using SQLite in android Development

Source: Internet
Author: User

Write a diary using SQLite in android Development

Use a database to store data.

The following is a small example.

The effect is as follows:



When no data is displayed in the LIstView, we need to tell the user that there is no data.

There are two methods:

1.

The activity inherits the ListActivity and is written in the layout file as follows:

 
                
  

2.

If (adapter. isEmpty () & textView = null) {textView = new TextView (MainActivity. this); textView. setText ("the host is very lazy and nothing is left"); textView. setVisibility (View. GONE); (ViewGroup) listView. getParent ()). addView (textView); listView. setEmptyView (textView);} else {listView. setAdapter (simpleCursorAdapter );}

Database usage (Android comes with SQLite. If you want to use other databases, you must use Web Server ):

Inherit from SQLiteOpenHelper.

Public DBHelper (Context context) // Database Name, database version public void onCreate (SQLiteDatabase db) /// create public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) // update the database

The Code is as follows:

Cn.edu. bzu. diary. activity

MainActivity. java

Public class MainActivity extends Activity {ListView listView; Cursor diaries; // Cursor TextView textView = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listView = (ListView) findViewById (R. id. listview); refreshList (); this. registerForContextMenu (listView);}/*** refresh Adapter */public void refreshList () {DiaryDao diaryDao = new DiaryDao (this); diaries = diaryDao. getAllDairies (); SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter (MainActivity. this, R. layout. item, diaries, new String [] {"title", "created"}, new int [] {R. id. title, R. id. created}); if (simpleCursorAdapter. isEmpty () & textView = null) {textView = new TextView (MainActivity. this); textView. setText ("the host is very lazy and nothing is left"); textView. setVisibility (View. GONE); (ViewGroup) listView. getParent ()). addView (textView); listView. setEmptyView (textView);} else {listView. setAdapter (simpleCursorAdapter) ;}}@ Overridepublic void onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo) {menu. setHeaderTitle ("operation"); menu. add (0, 1, Menu. NONE, "edit"); menu. add (0, 2, Menu. NONE, "delete"); super. onCreateContextMenu (menu, v, menuInfo) ;}@ Overridepublic boolean onContextItemSelected (MenuItem item) {// onContextItemSelectedAdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item. getMenuInfo (); switch (item. getItemId () {case 1: Intent intent = new Intent (); Bundle bundle = new Bundle (); bundle. putInt ("id", (int) menuInfo. id); intent. putExtras (bundle); intent. setClass (MainActivity. this, diaryeditaciti.pdf. class); startActivity (intent); break; case 2: DiaryDao dao = new DiaryDao (MainActivity. this); dao. delete (int) menuInfo. id); // menuInfo. the id is consistent with the database ID refreshList (); break;} return super. onContextItemSelected (item);}/*** refresh the Adapter by using the lifecycle in the exit log adding process */@ Overrideprotected void onResume () {super. onResume (); refreshList () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. main, menu); return true;}/*** enter the "Diary add page" through the menu */@ Overridepublic boolean onOptionsItemSelected (MenuItem item) {switch (item. getItemId () {case R. id. save: Intent intent = new Intent (); intent. setClass (MainActivity. this, diaryaddaciti.pdf. class); startActivity (intent); break;} return super. onOptionsItemSelected (item );}}


Diaryaddaciti.pdf. java

Public class diaryaddaciti#extends Activity {DiaryDao diaryDao = new DiaryDao (diaryaddaciti.pdf. this); Button button; EditText editText, editText2; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. diaryadd_aciti.pdf); editText = (EditText) findViewById (R. id. et_diaryadd); // The title editText2 = (EditText) findViewById (R. id. et02_diaryadd); // content button = (Button) findViewById (R. id. but) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. diary_add_acitivity, menu); return true;} public void click (View view) {String title = editText. getText (). toString (); String content = editText2.getText (). toString (); Diary diary = new Diary (title, content, Tool. dateChange (new Date (); DiaryDao diaryDao = new DiaryDao (this); diaryDao. save (diary); finish ();}}

Diaryeditaciti.pdf. java

Public class DiaryEditAcitivity extends Activity {DiaryDao diaryDao = new DiaryDao (diaryeditaciti.pdf. this); Button button; EditText editText, editText2; int id; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. diaryadd_aciti.pdf); editText = (EditText) findViewById (R. id. et_diaryadd); // The title editText2 = (EditText) findViewById (R. id. et02 _ Diaryadd); // content button = (Button) findViewById (R. id. but); Bundle bundle = this. getIntent (). getExtras (); if (bundle! = Null) {id = bundle. getInt ("id"); Diary diary = diaryDao. getDiaryById (id); editText. setText (diary. getTitle (); editText2.setText (diary. getContent () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. diary_add_acitivity, menu); return true;} public void click (View view) {String title = editText. getText (). toString (); String content = editText2.getText (). toString (); Diary diary = new Diary (title, content, Tool. dateChange (new Date (); diary. setId (id); DiaryDao diaryDao = new DiaryDao (this); diaryDao. update (diary); finish ();}}

Cn.edu. bzu. diary. daoDiaryDao. java

Public class DiaryDao {private DBHelper dbHelper; private SQLiteDatabase sqLiteDatabase; public DiaryDao (Context context) {dbHelper = new DBHelper (context );} /*** Add a diary * @ param Diary */public void save (diary) {String SQL = "insert into diary (title, content, created) values (?,?,?) "; SqLiteDatabase = dbhelper.getwritabledatabase(;;sqlitedatabase.exe cSQL (SQL, new String [] {diary. getTitle (), diary. getContent (), diary. getDatetime ()});}/*** delete the id of the diary ** @ param id */public void delete (Integer id) {sqLiteDatabase = dbHelper. getWritableDatabase (); // The result is that sqlitedatabase.exe cSQL ("delete from diary where _ id =? ", New Object [] {id});}/*** update diary ** @ param Diary */public void update (diary) {sqLiteDatabase = dbHelper. getWritableDatabase (); // The result is that sqlitedatabase.exe cSQL ("update diary set title = ?, Content = ?, Created =? Where _ id =? ", New Object [] {diary. getTitle (), diary. getContent (), diary. getDatetime (), diary. getId ()});}/*** returns a cursor. You can also use the comments section to return a List set (using SimpleAdapter), where the cursor is used, the main reason is that * The ID in AdapterContextMenuInfo is consistent with that in the database * @ return cursor */public Cursor getAllDairies () {// Diary diary = null; // List
 
  
Diaries = new ArrayList
  
   
(); SqLiteDatabase = dbHelper. getReadableDatabase (); Cursor cursor = sqLiteDatabase. rawQuery ("select * from diary", null);/** while (cursor. moveToNext () {String title = * cursor. getString (cursor. getColumnIndex ("title"); String content = * cursor. getString (cursor. getColumnIndex ("content"); String created = * cursor. getString (cursor. getColumnIndex ("created"); diary = new * Diary (title, content, cr Eated); diaries. add (diary);} */return cursor;}/*** obtain the total number of records */public long count () {long count = 0; sqLiteDatabase = dbHelper. getReadableDatabase (); Cursor cursor = sqLiteDatabase. rawQuery ("select count (*) from diary", null); cursor. moveToFirst (); count = cursor. getLong (0); return count;} public Diary getDiaryById (int id) {sqLiteDatabase = dbHelper. getWritableDatabase (); Diary diary = null; Cursor cursor = SqLiteDatabase. rawQuery ("select * from diary where _ id =? ", New String [] {id +" "}); if (cursor. moveToFirst () {String title = cursor. getString (cursor. getColumnIndex ("title"); String content = cursor. getString (cursor. getColumnIndex ("content"); String created = cursor. getString (cursor. getColumnIndex ("created"); diary = new Diary (title, content, created);} return diary ;}}
  
 

Cn.edu. bzu. diary. dbDBHelper. java

Public class DBHelper extends SQLiteOpenHelper {public static final String DATABASE_NAME = "diary. db "; public static final int VERSION = 1; // Database Name, database VERSION public DBHelper (Context context) {super (context, DATABASE_NAME, null, VERSION ); // TODO Auto-generated constructor stub} // create a database, field: id (Primary Key), title, content, created; @ Overridepublic void onCreate (SQLiteDatabase db) {// TODO Auto-generated method stubdb.exe cSQL ("create table diary (_ id integer primary key autoincrement, title varchar (20), content varchar (1000), created) ") ;}// used for database updates @ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub }}

Cn.edu. bzu. diary. entityDiary. java

public class Diary {private Integer id;private String title;private String content;private String datetime;public Diary(){}public Diary(String title,String content,String datetime){this.title = title;this.content = content;this.datetime = datetime;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getDatetime() {return datetime;}public void setDatetime(String datetime) {this.datetime = datetime;}@Overridepublic String toString() {return "Diary [title=" + title + ", content=" + content + ", datetime="+ datetime + "]";}}

Cn.edu. bzu. diary. toolsTool. java
Public class Tool {/*** time display style * @ param date * @ return */public static String dateChange (Date date) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("MM dd, yyyy, hh: mm: ss seconds"); return simpleDateFormat. format (date );}}

Code











Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.