Энэ удаагийн андройдийн хичээл бид нар ORMLite Database болон Custom Adapterийн анх жишээг үзсэн билээ.
Жишээгээр Оюутны нэр код харуулдаг app хийсэн билээ.
1.Анх Project-ээ үүсгэсний дараа ORMLite-ийн 2 library-ийг /libs гэсэн folder рүү хуулна.
2.Өөрийнхөө package дээрээ DatabaseHelper болон Student гэсэн модел классаа үүсгэнэ.
Student.class
package mn.csms.databasetest;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable
public class Student {
@DatabaseField(generatedId=true)
public int id;
@DatabaseField(unique=true,canBeNull=false)
public String code;
@DatabaseField
public String name;
}
DatabaseHelper.class
package mn.csms.databasetest;
import java.sql.SQLException;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static String databaseName = "student.db";
public static int databaseVersion = 1;
Dao<Student, Integer> studentDao = null;
public DatabaseHelper(Context context) {
super(context, databaseName, null, databaseVersion);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
// TODO Auto-generated method stub
try {
TableUtils.createTableIfNotExists(connectionSource, Student.class);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
try {
TableUtils.createTable(connectionSource, Student.class);
// onCreate(database);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Dao<Student, Integer> getStudentDao() throws SQLException {
if (studentDao == null){
studentDao = getDao(Student.class);}
return studentDao;
}
@Override
public void close() {
// TODO Auto-generated method stub
super.close();
studentDao = null;
}
}
Дараа нь activity_main.xml class дээрээ ListView view нэмнэ энгэснээр listview дээ бид нар custom adapter тавина.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/studentList"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
Тэгээд adapter дээрээ ашиглах шинэ student_list_item.xml гэсэн xml layout үүсгэнэ.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp" >
<TextView
android:id="@+id/studentName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@android:color/black"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/studentCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="@+id/delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Delete" />
</LinearLayout>
Үүний дараа MainActivity.class
package mn.csms.databasetest;
import java.sql.SQLException;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DatabaseHelper helper;
private String[] studentName = { "Jargal", "Uguumur", "Alge", "Tseegii" };
private String[] studentCode = { "D.SW10D00" };
private List<Student> students;
private ListView lv;
private StudentAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.studentList);
helper = new DatabaseHelper(this);
try {
students = helper.getStudentDao().queryForAll();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//herev database hooson bol shine ugugluudee nemne
if (students.size()==0) {
for (int i = 0; i < studentName.length; i++) {
Student student = new Student();
student.name = studentName[i];
student.code = studentCode[0] + i;
Log.i("student", student.code);
try {
//helper class iig ashiglaj nemj bna
helper.getStudentDao().create(student);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
//Database iin buh ugudliig List<Student> turultei avch bna
students = helper.getStudentDao().queryForAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("size", students.size()+"");
//custom adapter buyu student-d zoriulsan adapter classiig duudaj bna
adapter=new StudentAdapter(getApplicationContext(),0, 0, students);
lv.setAdapter(adapter);
}
//Custom adapter class
private class StudentAdapter extends ArrayAdapter<Student> {
public StudentAdapter(Context context, int resource,int text,
List<Student> objects) {
super(context, resource, text,objects);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = null;
final Student student = getItem(position);
if (view == null) {
//R.layout.student_list_item layoutiig inflate hiij oruulj irj bna
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.student_list_item, null);
holder = new Holder();
holder.name = (TextView) view.findViewById(R.id.studentName);
holder.code = (TextView) view.findViewById(R.id.studentCode);
holder.delete = (Button) view.findViewById(R.id.delete);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.name.setText(student.name);
holder.code.setText(student.code);
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//delete buttong darahad
adapter.remove(student);
Toast.makeText(getApplicationContext(), student.name+" ugugdul amjilttai ustlaa", Toast.LENGTH_SHORT);
}
});
return view;
}
}
//studented zoriulsan viewiig class turultei zarlaj uguh heregtei
class Holder {
TextView name;
TextView code;
Button delete;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Заз тэгээд миний хичээл дууслаа source кодийг нь энэ линкээр татаж аваарай :)
Маш их баярлалаа.
ReplyDelete