C08 Project Code
- SDCardPra
- SQLitePra
(1) activity_main.xml
<RelativeLayout
android:id="@+id/activity_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/root"
android:orientation="vertical" >
<EditText
android:id="@+id/txtData"
android:inputType="textPersonName" />
<Button
android:id="@+id/btnWriteSDFile"
android:text="Write SD File" />
<Button
android:id="@+id/btnReadSDFile"
android:text="Read SD File" />
<Button
android:id="@+id/btnClearScreen"
android:text="Clear Screen" />
<Button
android:id="@+id/btnClose"
android:text="Close" />
</LinearLayout>
</RelativeLayout>
(2) MainActivity.java
public class MainActivity extends Activity {
/** Called when the activity is first created. */
// GUI controls
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
private final String SD_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath();
public static final String FILE_PATH = "/fileio";
private final String INPUT_FILENAME = "file.xml";
String dirPath = SD_PATH+FILE_PATH+"/";
String filenameWithPath = SD_PATH+FILE_PATH+"/"+INPUT_FILENAME;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] perms = {"android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"};
int permsRequestCode = 200;
requestPermissions(perms, permsRequestCode);
findViews();
setListener();
File folder = new File(Environment.getExternalStorageDirectory() + FILE_PATH );
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
Log.i("jpyuMsg", " create fileio successfully");
} else {
// Do something else on failure
Log.i("jpyuMsg", Environment.getExternalStorageDirectory() + FILE_PATH);
Log.i("jpyuMsg", "failed to create fileio ");
}
}// onCreate
private void findViews() {
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClose = (Button) findViewById(R.id.btnClose);
}
void writeFileToSdcardv2(){
/* write on SD card file data in the text box */
try {
/* create a File object for the parent directory */
File newDir = new File(dirPath);
/* have the object build the directory structure, if needed. */
newDir.mkdirs();
File myFile = new File(filenameWithPath);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(
getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
void readFileFromSdcardv1(){
try {
File myFile = new File(filenameWithPath);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void setListener() {
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
writeFileToSdcardv2();
}// onClick
}); // btnWriteSDFile
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
readFileFromSdcardv1();
}// onClick
}); // btnReadSDFile
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen
btnClose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
finish();
}
}); // btnClose
}
}
(3) AndroidManifest.xml
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
(1) activity_mainsqlite.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/group" >
<Button
android:id="@+id/add"
android:text="Add New"
android:onClick="onClick"/>
<Button
android:id="@+id/delete"
android:text="Delete First"
android:onClick="onClick"/>
</LinearLayout>
<ListView
android:id="@android:id/list"
android:text="@string/hello" />
</LinearLayout>
(2) MainActivity.java
public class MainActivity extends ListActivity {
private CommentsDataSource datasource;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainsqlite);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
@SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.add:
String[] comments = new String[] { "Cool", "Very nice", "Hate it" };
int nextInt = new Random().nextInt(3);
// save the new comment to the database
comment = datasource.createComment(comments[nextInt]);
adapter.add(comment);
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(0);
datasource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
datasource.open();
super.onResume();
}
@Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
(3) MySQLiteHelper.java
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 3;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}
}
(4) CommentsDataSource.java
public class CommentsDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = {
MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_COMMENT };
public CommentsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Comment createComment(String comment) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
long insertId = database.
insert(MySQLiteHelper.TABLE_COMMENTS, null,values);
Cursor cursor = database.query
(MySQLiteHelper.TABLE_COMMENTS,
allColumns, MySQLiteHelper.
COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Comment newComment = cursorToComment(cursor);
cursor.close();
return newComment;
}
public void deleteComment(Comment comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
}
(5) Comment.java
public class Comment {
private long id;
private String comment;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
// Will be used by the ArrayAdapter in the ListView
@Override
public String toString() {
return comment;
}
}