THỰC HÀNH LẬP TRÌNH TRÊN THIẾT BỊ DI
ĐỘNG
LAB 7 + JSON
1/Bài 1
a. Hình ảnh chạy ứng dụng
b. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/txtTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:layout_marginBottom="40dp"
android:textSize="50dp"
android:text="0:00:00" />
<Button
android:id="@+id/btnStar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/purple_700"
android:textColor="@color/white"
android:layout_below="@id/txtTimer"
android:layout_marginLeft="30dp"
android:text="Start" />
<Button
android:id="@+id/btnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/purple_700"
android:textColor="@color/white"
android:layout_below="@id/txtTimer"
android:layout_centerHorizontal="true"
android:text="Pause" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/purple_700"
android:textColor="@color/white"
android:layout_alignParentRight="true"
android:layout_marginRight="30dp"
android:layout_below="@id/txtTimer"
android:layout_marginLeft="20dp"
android:text="Stop" />
</RelativeLayout>
c. MainActivity.java
package edu.huflit.project.btdonghobamgio_handle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button btnStar, btnPause, btnStop;
TextView txtTimer;
long lStarTime, lPauseTime, lSystemTime = 0L;
Handler handler = new Handler();
boolean isRun;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Find View
btnStar = findViewById(R.id.btnStar);
btnPause = findViewById(R.id.btnPause);
btnStop = findViewById(R.id.btnStop);
txtTimer = findViewById(R.id.txtTimer);
}
@Override
protected void onStart() {
super.onStart();
clickStar();
clickStop();
clickPause();
}
Runnable runnable = new Runnable() {
@Override
public void run() {
lSystemTime = SystemClock.uptimeMillis() - lStarTime;
long lUpdateTime = lPauseTime + lSystemTime;
long secs = (long) (lUpdateTime / 1000);
long mins = secs / 60;
secs = secs % 60;
long milliseconds = (long) (lUpdateTime % 1000);
txtTimer.setText("" + mins + ":" + String.format("%02d",
secs) + ":" + String.format("%03d", milliseconds));
handler.postDelayed(this, 0);
}
};
void clickStar()
{
btnStar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isRun)
return;
isRun = true;
lStarTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
}
});
}
void clickStop()
{
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isRun)
return;
isRun = false;
txtTimer.setText("0:00:00");
handler.removeCallbacks(runnable);
}
});
}
void clickPause()
{
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isRun)
return;
isRun = false;
lPauseTime += lSystemTime;
handler.removeCallbacks(runnable);
}
});
}
}
2/Bài 2
a. Hình ảnh chạy ứng dụng
a. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="15dp"
android:textColor="@color/black"
android:text="Sleep time in Seconds:" />
<EditText
android:id="@+id/edtTime"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@android:drawable/editbox_background_normal"
android:ems="10"
android:padding="10dp"
android:textSize="15dp"
android:inputType="number" />
<Button
android:id="@+id/btnRun"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/edtTime"
android:layout_centerHorizontal="true"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginTop="64dp"
android:textColor="@color/white"
android:backgroundTint="#5410EC"
android:background="@android:drawable/editbox_background"
android:text="Run async task" />
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnRun"
android:layout_centerHorizontal="true" />
</RelativeLayout>
b. MainActivity.java
package edu.huflit.project.asynctask;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private String resp;
ProgressDialog progressDialog;
TextView finalResult;
EditText time;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = findViewById(R.id.edtTime);
button = findViewById(R.id.btnRun);
finalResult = findViewById(R.id.tvResult);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = time.getText().toString();
runner.execute(sleepTime);
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String,
String>{
protected void onPreExecute(){
progressDialog = ProgressDialog
.show(MainActivity.this, "ProgressDialog",
"Wait for " + time.getText().toString() + "
seconds");
}
@Override
protected String doInBackground(String... params){
publishProgress("Sleeping...");
try{
int time = Integer.parseInt(params[0]) * 1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e){
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e){
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onProgressUpdate(String... text){
finalResult.setText(text[0]);
}
@Override
protected void onPostExecute(String result){
progressDialog.dismiss();
finalResult.setText(result);
}
}
}
3/Bài 3
a. Hình ảnh chạy ứng dụng
b. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textSize="35sp"
android:textColor="#0091EA"
android:layout_centerHorizontal="true" />
<EditText
android:id="@+id/edtTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:layout_centerVertical="true"
android:textColor="#0091EA"
android:textSize="25sp"
android:layout_centerHorizontal="true"
android:gravity="center"/>
<Button
android:id="@+id/btnRun"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_centerHorizontal="true"
android:background="#0091EA"
android:textColor="@color/white"
android:layout_below="@id/edtTime"
android:text="Bắt đầu" />
</RelativeLayout>
c. MainActivity.java
package edu.huflit.project.btdonghodemnguoc;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Integer num;
ProgressDialog progressDialog;
Button btnRun;
TextView tvResult;
EditText edtTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRun = findViewById(R.id.btnRun);
tvResult = findViewById(R.id.tvResult);
edtTime = findViewById(R.id.edtTime);
btnRun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int num =
Integer.parseInt(edtTime.getText().toString());
new Timer().execute(Integer.toString(num));
}
});
}
private class Timer extends AsyncTask<String, Integer, Void> {
@Override
protected Void doInBackground(String... params) {
try {
if (num == null)
return null;
else
while (num > 0)
{
Thread.sleep(10);
num = num - 1;
publishProgress(num);
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
try {
num = Integer.parseInt(edtTime.getText().toString()) *
100;
btnRun.setEnabled(false);
edtTime.setEnabled(false);
} catch (Exception e){
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int millis = values[0] % 100;
tvResult.setText(values[0] / 100 + ":" + ((millis +
"").length() != 2 ? "0" + millis : millis));
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
btnRun.setEnabled(true);
edtTime.setEnabled(true);
}
}
}
JSON
1/Bài 1
a. Hình ảnh chạy chương trình
b.Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:textSize="25sp"
android:textColor="@color/black"
android:hint="Tên sinh viên" />
<EditText
android:id="@+id/edtAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="25sp"
android:textColor="@color/black"
android:inputType="number"
android:hint="Tuổi sinh viên"/>
<EditText
android:id="@+id/edtAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="25sp"
android:textColor="@color/black"
android:inputType="text"
android:hint="Địa chỉ sinh viên" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp"
android:orientation="horizontal">
<Button
android:id="@+id/btnRead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:drawable/editbox_background_normal"
android:backgroundTint="#304FFE"
android:textColor="@color/white"
android:text="READJSON"/>
<Button
android:id="@+id/btnWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:drawable/editbox_background_normal"
android:backgroundTint="#304FFE"
android:textColor="@color/white"
android:text="WRITEJSON" />
<Button
android:id="@+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:drawable/editbox_background_normal"
android:backgroundTint="#304FFE"
android:textColor="@color/white"
android:text="DELETE" />
</LinearLayout>
<ListView
android:id="@+id/lvDs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"/>
</LinearLayout>
c.MainActivity.java
package edu.huflit.project.btjson;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<SinhVien> DSSV = new ArrayList<SinhVien>();
ListView mlvds;
Button mbtnRead, mbtnWrite, mbtnDelete;
EditText medtTen, medtTuoi, medtDiaChi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlvds = findViewById(R.id.lvDs);
mbtnRead = findViewById(R.id.btnRead);
mbtnWrite = findViewById(R.id.btnWrite);
mbtnDelete = findViewById(R.id.btnDelete);
medtTen = findViewById(R.id.edtName);
medtTuoi = findViewById(R.id.edtAge);
medtDiaChi = findViewById(R.id.edtAddress);
ArrayAdapter adap = new ArrayAdapter(this,
android.support.constraint.R.layout.support_simple_spinner_dropdown_item,
DSSV);
mlvds.setAdapter(adap);
mbtnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DSSV.removeAll(DSSV);
loadDataFromJSonToListView();
adap.notifyDataSetChanged();
}
});
mbtnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FileOutputStream fos = null;
String out = "{\nsinhvien:\n[";
try{
fos = openFileOutput("sinhvien.json",MODE_PRIVATE);
Gson gson = new Gson();
String json_output = new Gson().toJson(DSSV);
fos.write(json_output.getBytes());
Toast.makeText(MainActivity.this, "SAVE TO..." +
getFilesDir(), Toast.LENGTH_SHORT).show();
fos.close();
}
catch (FileNotFoundException e){
throw new RuntimeException(e);
}
catch (IOException e){
throw new RuntimeException(e);
}
Toast.makeText(MainActivity.this, "Done",
Toast.LENGTH_SHORT).show();
}
});
mbtnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (int i = mlvds.getChildCount() -1; i >= 0; i--) {
if
(DSSV.get(i).toString().equals(laydulieu().toString())) {
view = mlvds.getChildAt(i);
DSSV.remove(i);
break;
}
}
adap.notifyDataSetChanged();
}
});
mlvds.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int i, long l) {
medtTen.setText(DSSV.get(i).getHoTen());
medtTuoi.setText(Integer.toString(DSSV.get(i).getTuoi()));
medtDiaChi.setText(DSSV.get(i).getDiaChi());
}
});
}
private String loadJSon()
{
String json = null;
try {
InputStream is = getAssets().open("sinhvien.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String (buffer, "UTF-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
return json;
}
private void loadDataFromJSonToListView() {
try {
JSONObject jsonObject = new JSONObject(loadJSon());
JSONArray jsonArray = jsonObject.getJSONArray("sinhvien");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject sinhvienData = jsonArray.getJSONObject(i);
SinhVien sv = new SinhVien();
sv.setHoTen(sinhvienData.getString("ten"));
sv.setTuoi(sinhvienData.getInt("tuoi"));
sv.setDiaChi(sinhvienData.getString("diachi"));
DSSV.add(sv);
}
} catch (JSONException ex) {
throw new RuntimeException(ex);
}
}
private SinhVien laydulieu() {
SinhVien sv = new SinhVien();
sv.setHoTen(medtTen.getText().toString());
sv.setTuoi(Integer.parseInt(medtTuoi.getText().toString()));
sv.setDiaChi(medtDiaChi.getText().toString());
return sv;
}
}
d.SinhVien.java
package edu.huflit.project.btjson;
public class SinhVien {
private String HoTen;
private int Tuoi;
private String DiaChi;
public SinhVien(String hoTen, int tuoi, String diaChi) {
HoTen = hoTen;
Tuoi = tuoi;
DiaChi = diaChi;
}
public SinhVien() {
}
public String getHoTen() {
return HoTen;
}
public int getTuoi() {
return Tuoi;
}
public String getDiaChi() {
return DiaChi;
}
public void setHoTen(String hoTen) {
HoTen = hoTen;
}
public void setTuoi(int tuoi) {
Tuoi = tuoi;
}
public void setDiaChi(String diaChi) {
DiaChi = diaChi;
}
@Override
public String toString() {
return getHoTen() + " : " + getTuoi() + " : " + getDiaChi();
}
}
e.sinhvien.json
{
"sinhvien": [
{
"ten": "Xuân Anh",
"tuoi": 20,
"diachi": "TPHCM"
},
{
"ten": "Trần Bảo",
"tuoi": 19,
"diachi": "Long An"
},
{
"ten": "Nguyễn An",
"tuoi": 18,
"diachi": "Đồng Nai"
}
]
}
Bài 2
DBHelper.java
package com.example.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "QLSV.db";
private static final int DATABASE_VERSION = 1;
// SQL statement to create the "Sinhvien" table
private static final String CREATE_SINHVIEN_TABLE =
"CREATE TABLE Sinhvien ("
+ "HoTen TEXT,"
+ "Tuoi INTEGER,"
+ "Diachi TEXT)";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create the "Sinhvien" table
db.execSQL(CREATE_SINHVIEN_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Upgrade policy: simply discard the data and start over
db.execSQL("DROP TABLE IF EXISTS Sinhvien");
onCreate(db);
}
}
Mydatabase.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class MyDatabase {
private DBHelper dbHelper;
public MyDatabase(Context context) {
dbHelper = new DBHelper(context);
}
// add a Sinhvien to the database
public void addSinhvien(SinhVien sinhvien) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_HOTEN, sinhvien.getHoTen());
values.put(COLUMN_TUOI, sinhvien.getTuoi());
values.put(COLUMN_DIACHI, sinhvien.getDiaChi());
db.insert(TABLE_NAME, null, values);
db.close();
}
// remove a Sinhvien from the database
public void deleteSinhvien(SinhVien sinhvien) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COLUMN_ID + "=?", new String[]
{String.valueOf(sinhvien.getId())});
db.close();
}
// edit a Sinhvien in the database
public void editSinhvien(SinhVien sinhvien) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_HOTEN, sinhvien.getHoten());
values.put(COLUMN_TUOI, sinhvien.getTuoi());
values.put(COLUMN_DIACHI, sinhvien.getDiachi());
db.update(TABLE_NAME, values, COLUMN_ID + "=?", new String[]
{String.valueOf(sinhvien.getId())});
db.close();
}