成语展示

来源:互联网 发布:鞋类进销存软件 编辑:程序博客网 时间:2024/04/26 03:31

新建一个db包,在其下新建一个DBOpenHelper类

package happyidiom.bztc.edu.com.happyidiom.db;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.os.Environment;import android.util.Log;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import happyidiom.bztc.edu.com.happyidiom.R;/** * Created by Administrator on 2017/5/4. */public class DBOpenHelper {    private final int BUFFER_SIZE = 400000;    public static final String DB_NAME = "idioms.db";    public static final String PACKAGE_NAME = "happyidiom.bztc.edu.com.happyidiom";    public static final String DB_PATH = "/data"            + Environment.getDataDirectory().getAbsolutePath() +"/"            + PACKAGE_NAME+ "/databases";    private Context context;    public DBOpenHelper(Context context) {        this.context = context;    }    public SQLiteDatabase openDatabase() {        try {            File myDataPath = new File(DB_PATH);            if (!myDataPath.exists()){                myDataPath.mkdirs();            }            String dbfile=myDataPath+"/"+DB_NAME;            if (!(new File(dbfile).exists())) {                InputStream is = context.getResources().openRawResource(                        R.raw.idioms);                FileOutputStream fos =new FileOutputStream(dbfile);                byte[] buffer = new byte[BUFFER_SIZE];                int count = 0;                while ((count = is.read(buffer)) > 0) {                    fos.write(buffer, 0, count);                }                fos.close();                is.close();            }            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,                    null);            return db;        } catch (FileNotFoundException e) {           Log.e("Database", "File not found");            e.printStackTrace();        } catch (IOException e) {            Log.e("Database", "IO exception");            e.printStackTrace();        }        return null;    }}

搭建AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="happyidiom.bztc.edu.com.happyidiom">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".activity.StudyAnimalActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <uses-library android:name="android.test.runner"/>    </application>    <instrumentation        android:name="android.test.InstrumentationTestRunner"        android:targetPackage="cn.edu.bztc.happyidom"></instrumentation></manifest>

新建一个test包,在其下新建DBOpenHelperTest继承AndroidTestCase

package happyidiom.bztc.edu.com.happyidiom.test;import android.test.AndroidTestCase;import happyidiom.bztc.edu.com.happyidiom.db.DBOpenHelper;/** * Created by Administrator on 2017/5/4. */public class DBOpenHelperTest extends AndroidTestCase {    public void testDBCopy(){        DBOpenHelper dbOpenHelper=new DBOpenHelper(getContext());        dbOpenHelper.openDatabase();    }}

新建一个entity包,在entity包下新建一个Animal类

package happyidiom.bztc.edu.com.happyidiom.entity;/** * Created by Administrator on 2017/5/4. */public class Animal {    private int id;    private String name;    private String pronounce;    private String explain;    private String antonym;    private String homoionym;    private String derivation;    private String examples;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPronounce() {        return pronounce;    }    public void setPronounce(String pronounce) {        this.pronounce = pronounce;    }    public String getExplain() {        return explain;    }    public void setExplain(String explain) {        this.explain = explain;    }    public String getAntonym() {        return antonym;    }    public void setAntonym(String antonym) {        this.antonym = antonym;    }    public String getHomoionym() {        return homoionym;    }    public void setHomoionym(String homoionym) {        this.homoionym = homoionym;    }    public String getDerivation() {        return derivation;    }    public void setDerivation(String derivation) {        this.derivation = derivation;    }    public String getExamples() {        return examples;    }    public void setExamples(String examples) {        this.examples = examples;    }}

在entity包下再创建一个AnimalDao类

package happyidiom.bztc.edu.com.happyidiom.entity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import java.util.ArrayList;import java.util.List;import happyidiom.bztc.edu.com.happyidiom.db.DBOpenHelper;/** * Created by Administrator on 2017/5/5. */public class AnimalDao {    private static AnimalDao animalDao;    private SQLiteDatabase db;    private AnimalDao(Context context) {        DBOpenHelper dbHelper = new DBOpenHelper(context);        db=dbHelper.openDatabase();    }    public synchronized static AnimalDao getInstance(Context context) {        if (animalDao == null) {            animalDao= new AnimalDao(context);        }        return animalDao;    }    public List<Animal> getAllAnimals() {        List<Animal> list = new ArrayList<>();        Cursor cursor=db.query("animal",null,null,null,null,null,null);        if (cursor.moveToFirst()) {            do {                Animal animal=new Animal();                animal.setId(cursor.getInt(cursor.getColumnIndex("_id")));                animal.setName(cursor.getString(cursor                        .getColumnIndex("name")));                animal.setPronounce(cursor.getString(cursor                        .getColumnIndex("pronounce")));                animal.setAntonym(cursor.getString(cursor                        .getColumnIndex("antonym")));                animal.setHomoionym(cursor.getString(cursor                        .getColumnIndex("homoionym")));                animal.setDerivation(cursor.getString                        (cursor.getColumnIndex("derivation")));                animal.setExamples(cursor.getString                        (cursor.getColumnIndex("examples")));                list.add(animal);            } while (cursor.moveToNext());        }        return list;    }}

编写单元测试类AnimalDaoTest 继承 AndroidTestCase

package happyidiom.bztc.edu.com.happyidiom.test;import android.test.AndroidTestCase;import java.util.List;import happyidiom.bztc.edu.com.happyidiom.entity.Animal;import happyidiom.bztc.edu.com.happyidiom.entity.AnimalDao;/** * Created by Administrator on 2017/5/5. */public class AnimalDaoTest extends AndroidTestCase{    public void testGetAllAnimals(){        AnimalDao animalDao=  AnimalDao.getInstance(getContext());        List<Animal> animals=animalDao.getAllAnimals();        System.out.println(animals.size());        for(Animal animal:animals){            System.out.println(animal.getName());        }    }}

在layout下新建activity_animal.xml文件,主要添加了一个ListView控件

<?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:background="@drawable/bg_animal"    android:orientation="vertical">    <ListView        android:id="@+id/lvAnimalList"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layoutAnimation="@anim/anim_layout_listview"        android:listSelector="#00000000"        /></LinearLayout>

在layout目录下新建animal_item.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="10dp">    <TextView        android:text="助人为乐"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/tvName"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:gravity="center"        android:textAppearance="?android:attr/textAppearanceLarge" />    <ImageButton        android:id="@+id/btnSave"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@null"        android:layout_alignParentRight="true"        android:layout_alignTop="@+id/tvName"        android:src="@drawable/btnsave"        /></RelativeLayout>

在res目录下新建anim目录,在下面创建anim_listview.xml文件

<?xml version="1.0" encoding="utf-8"?><alpha xmlns:android="http://schemas.android.com/apk/res/android"    android:duration="1000"    android:fromAlpha="0.0"    android:toAlpha="1.0"></alpha>

创建anim_layout_listview.xml文件

<?xml version="1.0" encoding="utf-8"?><layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"    android:animation="@anim/anim_listview"    android:animationOrder="random"    android:delay="0.2"></layoutAnimation>

创建adapter包,在其下创建一个AnimalAdapter类

package happyidiom.bztc.edu.com.happyidiom.adapter;import android.content.Context;import android.support.annotation.NonNull;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageButton;import android.widget.TextView;import java.util.List;import happyidiom.bztc.edu.com.happyidiom.R;import happyidiom.bztc.edu.com.happyidiom.entity.Animal;/** * Created by Administrator on 2017/5/4. */public class AnimalAdapter extends ArrayAdapter<Animal> {    private int resourceId;    public AnimalAdapter(Context context, int resource, List<Animal> objects) {        super(context, resource, objects);        resourceId=resource;    }    @NonNull    @Override    public View getView(int position, View convertView, ViewGroup parent) {        Animal animal = getItem(position);        View view;        ViewHolder viewHolder;        if (convertView == null) {            view = LayoutInflater.from(getContext()).inflate(resourceId, null);            viewHolder = new ViewHolder();            viewHolder.tvName= (TextView) view                    .findViewById(R.id.tvName);            viewHolder.btnSave=(ImageButton) view                    .findViewById(R.id.btnSave);            view.setTag(viewHolder);        } else {            view = convertView;            viewHolder = (ViewHolder) view.getTag();        }        viewHolder.tvName.setText(animal.getName());        viewHolder.btnSave.setFocusable(false);        viewHolder.btnSave.setFocusableInTouchMode(false);        return view;    }    class ViewHolder {        TextView tvName;        ImageButton btnSave;    }}

在activity包下新建StudyAnimalActivity继承自Activity

package happyidiom.bztc.edu.com.happyidiom.activity;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ListView;import java.util.List;import happyidiom.bztc.edu.com.happyidiom.R;import happyidiom.bztc.edu.com.happyidiom.adapter.AnimalAdapter;import happyidiom.bztc.edu.com.happyidiom.entity.Animal;import happyidiom.bztc.edu.com.happyidiom.entity.AnimalDao;import happyidiom.bztc.edu.com.happyidiom.unil.DialogUtil;/** * Created by Administrator on 2017/5/5. */public class StudyAnimalActivity extends Activity {    private List<Animal> animalList;    private AnimalDao animalDao;    private ListView lvAnimalList;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_animal);        initAnimals();        lvAnimalList = (ListView) findViewById(R.id.lvAnimalList);        AnimalAdapter animalAdapter = new AnimalAdapter(this,                R.layout.animal_item, animalList);        lvAnimalList.setAdapter(animalAdapter);        lvAnimalList.setOnItemClickListener(new AdapterView.OnItemClickListener() {            @Override            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {                Animal animal = animalList.get(position);                String result = animal.getName() + "\n" + animal.getPronounce() + "\n【解释】:" + animal.getExplain() + "\n【近义词】:" + animal.getHomoionym() + "\n【反义词】:" + animal.getAntonym() + "\n【来源】:" + animal.getDerivation() + "\n【示例】:" + animal.getExamples();                DialogUtil.showDialog(result, StudyAnimalActivity.this);            }        });    }    private void initAnimals() {        animalDao = AnimalDao.getInstance(this);       animalList=animalDao.getAllAnimals();    }}

在layout下新建布局文件dialog_info.xml

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="@drawable/bg_ling"        android:orientation="vertical" >        <TextView            android:id="@+id/tvIdiomInfo"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="Medium Text"            android:textAppearance="?android:attr/textAppearanceMedium" />    </LinearLayout></ScrollView>

在util包下新建DialogUtil类

package happyidiom.bztc.edu.com.happyidiom.unil;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.view.LayoutInflater;import android.view.View;import android.widget.TextView;import happyidiom.bztc.edu.com.happyidiom.R;/** * Created by Administrator on 2017/5/5. */public class DialogUtil {    public static void showDialog(String result,Context context) {        AlertDialog.Builder builder = new AlertDialog.Builder(context);       LayoutInflater layoutInflater = LayoutInflater.from(context);       View view = layoutInflater.inflate(R.layout.dialog_info, null);        builder.setView(view);       TextView tvIdiomInfo = (TextView) view.findViewById(R.id.tvIdiomInfo);        tvIdiomInfo.setText(result);        builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){            @Override            public void onClick(DialogInterface dialog, int which) {                dialog.dismiss();            }        });        builder.create().show();    }}

实验结果
这里写图片描述

这里写图片描述
实验过程遇到的问题

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)' on a null object reference                      at happyidiom.bztc.edu.com.happyidiom.entity.AnimalDao.getAllAnimals(AnimalDao.java:34)                      at happyidiom.bztc.edu.com.happyidiom.activity.StudyAnimalActivity.initAnimals(StudyAnimalActivity.java:52)                      at happyidiom.bztc.edu.com.happyidiom.activity.StudyAnimalActivity.onCreate(StudyAnimalActivity.java:30)                      at android.app.Activity.performCreate(Activity.java:6664)                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)?                      at android.app.ActivityThread.-wrap12(ActivityThread.java)?                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)?                      at android.os.Handler.dispatchMessage(Handler.java:102)?                      at android.os.Looper.loop(Looper.java:154)?                      at android.app.ActivityThread.main(ActivityThread.java:6077)?                      at java.lang.reflect.Method.invoke(Native Method)?                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)?                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)?

出现问题的原因:DBOpenHelper中的包名路径与实际建立的包名的路径不同,所以调试不成功

0 0
原创粉丝点击