您的位置:首页 > 数据库

玩家信息管理(SQLite+Fragment加强)

2016-01-05 15:55 274 查看
一丶效果演示:






二丶需求分析

1.设计简单玩家包涵以下属性

GamePlay:

关卡

分数

游戏ID

2.实现游戏玩家数据的增删改

三丶功能设计

1.展现玩家基本数据

2.分数降序排列

3.管理员可增删改玩家信息

四丶技术实现

1.SQLitem完成数据的基本功能

2.Activity和Fragment交互

3ListView显示玩家信息

五丶代码展示

1.创建entity文件夹存放实体类GamePlayer.java并创建get set toSring方法

public class GamePlayer {
    private String player;
    private int score;
    private int level;
    private int id;
    public GamePlayer() {
    }

    public GamePlayer(String player, int score, int level) {
        this.player = player;
        this.score = score;
        this.level = level;
    }

    public GamePlayer(String player, int score, int level, int id) {
        this.player = player;
        this.score = score;
        this.level = level;
        this.id = id;
    }

    public String getPlayer() {
        return player;
    }

    public void setPlayer(String player) {
        this.player = player;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "GamePlayer{" +
                "player='" + player + '\'' +
                ", score=" + score +
                ", level=" + level +
                ", id=" + id +
                '}';
    }
}

2.创建db文件夹存放数据库部分(DatabaseAdapter DatabaseHelper GameMetaData)

GameMetaData 数据库元数据

public final class GameMetaData {
    private GameMetaData() {
    }

    //定义表 和 列字段名
    public static abstract class GamePlay implements BaseColumns {
        public static final String TABLE_NAME = "player_table";
        public static final String PLAYER = "player";
        public static final String SCORE = "score";
        public static final String LEVEL= "level";
    }
}

DatabaseAdapter 数据库操作

public class DatabaseAdapter {
    private DatabaseHelper dbHelper;

    public DatabaseAdapter(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    //添加操作
    public void add(GamePlayer gamePlayer) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(GameMetaData.GamePlay.PLAYER, gamePlayer.getPlayer());
        values.put(GameMetaData.GamePlay.SCORE, gamePlayer.getScore());
        values.put(GameMetaData.GamePlay.LEVEL, gamePlayer.getLevel());

        db.insert(GameMetaData.GamePlay.TABLE_NAME, null, values);
        db.close();
    }

    //删除操作
    public void delete(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String whereClause = GameMetaData.GamePlay._ID + "=?";
        String[] whereArgs = {String.valueOf(id)};

        db.delete(GameMetaData.GamePlay.TABLE_NAME, whereClause, whereArgs);
        db.close();
    }

    //更新操作
    public void update(GamePlayer gamePlayer) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(GameMetaData.GamePlay.PLAYER, gamePlayer.getPlayer());
        values.put(GameMetaData.GamePlay.SCORE, gamePlayer.getScore());
        values.put(GameMetaData.GamePlay.LEVEL, gamePlayer.getLevel());

        String whereClause = GameMetaData.GamePlay._ID + "=?";
        String[] whereArgs = {String.valueOf(gamePlayer.getId())};
        db.update(GameMetaData.GamePlay.TABLE_NAME, values, whereClause, whereArgs);
        db.close();
    }

    //查询
    public GamePlayer findById(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = db.query(true, GameMetaData.GamePlay.TABLE_NAME, null, GameMetaData.GamePlay._ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);

        GamePlayer gamePlayer = null;
        if (cursor.moveToNext()) {
            gamePlayer = new GamePlayer();

            gamePlayer.setPlayer(cursor.getString(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.PLAYER)));
            gamePlayer.setId(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay._ID)));
            gamePlayer.setLevel(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.LEVEL)));
            gamePlayer.setScore(cursor.getInt(cursor.getColumnIndexOrThrow(GameMetaData.GamePlay.SCORE)));
        }
        cursor.close();
        db.close();
        return gamePlayer;
    }

    public ArrayList<GamePlayer> findAll() {

        String sql = "select _id,player,score,level from player_table order by score desc";
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.rawQuery(sql, null);

        ArrayList<GamePlayer> gamePlayers = new ArrayList<>();
        GamePlayer gamePlayer = null;

        while (c.moveToNext()) {
            gamePlayer = new GamePlayer();
            gamePlayer.setPlayer(c.getString(c.getColumnIndexOrThrow(GameMetaData.GamePlay.PLAYER)));
            gamePlayer.setId(c.getInt(c.getColumnIndexOrThrow(GameMetaData.GamePlay._ID)));
            gamePlayer.setScore(c.getInt(c.getColumnIndexOrThrow(GameMetaData.GamePlay.SCORE)));
            gamePlayer.setLevel(c.getInt(c.getColumnIndexOrThrow(GameMetaData.GamePlay.LEVEL)));

            gamePlayers.add(gamePlayer);
        }
        c.close();
        db.close();

        return gamePlayers;
    }

    //查询总记录数
    public int getCount() {
        int count = 0;
        String sql = "select count(_id) from player_table";
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor c = db.rawQuery(sql, null);

        c.moveToFirst();
        count = c.getInt(0);//取第一条
        c.close();
        db.close();
        return count;
    }
}

DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "game.db";
    private static final int VERSION = 1;

    //创建表 sql
    private static final String CREATE_TABLE_PLAYER = "CREATE TABLE IF NOT EXISTS player_table(" +
            "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
            "player TEXT,score INTEGER,level INTEGER)";

    //删除表
    private static final String DROP_TABLE_PLAYER = "DROP TABLE IF EXISTS player_table";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_PLAYER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE_PLAYER);
        db.execSQL(CREATE_TABLE_PLAYER);
    }
}

3.以Fragment的形式呈现并完善功能,创建Fragment存放用到的Fragment(AddFragment GamePlayFragment UpdateFragment)

AddFragment用于完成添加游戏玩家功能,这里利用弹窗的形式,和菜单

activity.xml为空

menu_main1229

<menu 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" tools:context=".Main1229Activity">
    <item android:id="@+id/add" android:title="@string/add"
        android:icon="@android:drawable/ic_menu_add"
        android:orderInCategory="100" app:showAsAction="always" />
</menu>

AddFragment

public class AddFragment extends DialogFragment {
    private AddFragmentListener addFragmentListener;
    //定义接口,方便与activity交互 :
    public static interface AddFragmentListener {
        public void add(GamePlayer gamePlayer);
    }
    public AddFragment(){
    }
    //获取 主页面的activity
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            addFragmentListener = (AddFragmentListener) activity;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }

    //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失
    public static AddFragment newInstance() {
        AddFragment frag = new AddFragment();
        return frag;
    }
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        //定义一个对话框视图
        final View view = LayoutInflater.from(getActivity()).inflate(R.layout.create_game_dialog, null);

        return new AlertDialog.Builder(getActivity())
                .setIcon(android.R.drawable.ic_input_add)
                .setView(view)
                .setTitle("新增游戏玩家")
                .setPositiveButton("保存",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //获取界面 组件对象
                                EditText et_player = (EditText) view.findViewById(R.id.editText2_player);
                                EditText et_score = (EditText) view.findViewById(R.id.editText_cscore);
                                EditText et_level = (EditText) view.findViewById(R.id.edit_level);

                                //接收用户的输入填充对象
                                GamePlayer gamePlayer = new GamePlayer();
                                gamePlayer.setPlayer(et_player.getText().toString());
                                gamePlayer.setScore(Integer.parseInt(et_score.getText().toString()));
                                gamePlayer.setLevel(Integer.parseInt(et_level.getText().toString()));

                                addFragmentListener.add(gamePlayer);//调用activity方法 进行数据库添加操作
                                dialog.dismiss();
                            }
                        }
                )
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();//隐藏对话框
                    }
                }).create();
    }
}

create_game_dialog.xml

<?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="vertical"
    android:weightSum="1">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText2_player"
        android:hint="请输入玩家名称"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText_cscore"
        android:hint="请输入玩家分数"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_level"
        android:hint="请输入玩家关卡数"
        />
</LinearLayout>

GamePlayFragment 完成玩家信息的现实及触发更改等内容

Fragment_game_play.xml

<FrameLayout 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"
    tools:context="com.jin.administrator.my1229application.fragment.GamePlayFragment">
    <!--数据列表显示容器-->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:layout_gravity="center"
        android:choiceMode="none"
        />
</FrameLayout>

game_player_list_item_layout.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"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="序号:"
        android:id="@+id/textView" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="玩家:"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="分数:"
        android:id="@+id/textView3"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="关卡:"
        android:id="@+id/textView4"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="not data"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/textView_id"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="not data"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/textView_player"
        android:layout_below="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="not data"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/textView_score"
        android:layout_below="@+id/textView2"
        android:layout_toRightOf="@+id/textView2"
        android:layout_toEndOf="@+id/textView2" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="not data"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/textView_level"
        android:layout_toRightOf="@+id/textView3"
        android:layout_toEndOf="@+id/textView3"
        android:layout_below="@+id/textView_score"/>
</RelativeLayout>

listview_content_mrnu.xml(弹窗上面的menu)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/delete_menu"
        android:orderInCategory="100"
        android:title="删除"
        android:icon="@android:drawable/ic_menu_delete"/>
    <item android:id="@+id/update_menu"
        android:orderInCategory="100"
        android:title="修改"
        android:icon="@android:drawable/ic_menu_edit"/>
</menu>

GamePlayFragment

public class GamePlayFragment extends Fragment {
    //适配器对象
    GamePlayerAdapter gamePlayerAdapter;
    //接口对象
    private GamePlayerFragmentListener gamePlayerFragmentListener;
    //定义接口
    public static interface GamePlayerFragmentListener {
        public void showGamePlayerFragment();//作用:显示列表 界面
        public void showUpdateFragment(int id);//作用:更新数据的  从当前页面到更新页面,需要将本页的id带到更新页面上去 界面
        public void delete(int id);
        public ArrayList<GamePlayer> findAll();
    }
    //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失
    public static GamePlayFragment newInstance() {
        GamePlayFragment fragment = new GamePlayFragment();
        return fragment;
    }
    public GamePlayFragment(){
    }

    //获取 主页面的activity
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            gamePlayerFragmentListener = (GamePlayerFragmentListener) activity;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }

    }
    /**************长按 每个item 时弹出菜单 ***********************************/
    /**
     * 创建 菜单项
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        menu.setHeaderTitle("修改/删除");//菜单标题
        menu.setHeaderIcon(android.R.drawable.ic_menu_edit);

        //实例化 菜单项
        getActivity().getMenuInflater().inflate(R.menu.listview_context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete_menu:
                //获取菜单 信息对象
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                //获取前当前item的指定组件,  targetView :当前点击的item视图
                TextView textView_id = (TextView) info.targetView.findViewById(R.id.textView_id);
                //获取组件上的内容,即id
                int id = Integer.parseInt(textView_id.getText().toString());
                //调用 activity的删除方法,删除指定的 id 数据
                gamePlayerFragmentListener.delete(id);
                //重新查询视图列表数据
                changeData();
                break;
            case R.id.update_menu:
                info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                textView_id = (TextView) info.targetView.findViewById(R.id.textView_id);
                id = Integer.parseInt(textView_id.getText().toString());
                //调用 activity的更新方法,显示更新的视图
                gamePlayerFragmentListener.showUpdateFragment(id);
                break;
        }
        return super.onContextItemSelected(item);
    }
    /************************显示列表 fragment 实例会调以下方法*************************/
    /**
     * 在这里实例化 适配器对象,并填充数据
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //从数据库中获取列表数据
        ArrayList<GamePlayer> gamePlayers = gamePlayerFragmentListener.findAll();
        //实例化 适配器
        gamePlayerAdapter = new GamePlayerAdapter(getActivity(), gamePlayers);
    }
    /**
     * 自定义 listView布局
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //实例化 fragment布局
        View view = inflater.inflate(R.layout.fragment_game_play, container, false);

        ListView listView = (ListView) view.findViewById(R.id.listView);
        //注册上下文,因为长按时,要弹出菜单
       registerForContextMenu(listView);

        //        自定义布局
        listView.setAdapter(gamePlayerAdapter);//设置 适配器
        return view;
    }

    //自定义适配器
    private static class GamePlayerAdapter extends BaseAdapter {
        private Context context;
        //列表 数据
        private ArrayList<GamePlayer> gamePlayers;
        //重新设置
        public void setGamePlayers(ArrayList<GamePlayer> gamePlayers) {
            this.gamePlayers = gamePlayers;
        }

        public GamePlayerAdapter(Context context, ArrayList<GamePlayer> gamePlayers) {
            this.context = context;
            this.gamePlayers = gamePlayers;
        }

        @Override
        public int getCount() {
            return gamePlayers.size();
        }

        @Override
        public Object getItem(int position) {
            return gamePlayers.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            //节省性能,使用ViewHolder减少对象的查找
            ViewHolder vh = null;

            if (convertView == null) {//convertView:缓存item  减少对象的创建
                //实例化 item 布局
                convertView=LayoutInflater.from(context).inflate(R.layout.game_player_list_item_layout, null);

                vh = new ViewHolder();
                vh.tv_id = (TextView) convertView.findViewById(R.id.textView_id);
                vh.tv_player = (TextView) convertView.findViewById(R.id.textView_player);
                vh.tv_score = (TextView) convertView.findViewById(R.id.textView_score);
                vh.tv_level = (TextView) convertView.findViewById(R.id.textView_level);

                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }

            //组件数据填充
            GamePlayer g = gamePlayers.get(position);
            vh.tv_id.setText(String.valueOf(g.getId()));
            vh.tv_player.setText(g.getPlayer());
            vh.tv_score.setText(String.valueOf(g.getScore()));
            vh.tv_level.setText(String.valueOf(g.getLevel()));

            return convertView;
        }
    }

    //用于保存每一次查找的组件,避免下次重复查找
    private static class ViewHolder {
        TextView tv_id;
        TextView tv_player;
        TextView tv_score;
        TextView tv_level;
    }

    //重新查询数据
    public void changeData() {
        //从数据库查询数据,并填充到适配器中
        gamePlayerAdapter.setGamePlayers(gamePlayerFragmentListener.findAll());

        //让适配器重新加载数据 ,通知视内容更变
        gamePlayerAdapter.notifyDataSetChanged();

    }

    /**
     * 销毁时,置空
     */
    @Override
    public void onDetach() {
        super.onDetach();
        gamePlayerFragmentListener = null;
    }
}

UpdateFragment (完成数据的更新)

fragment_update.xml

<RelativeLayout
    android:id="@+id/relative_layout"
    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"
    tools:context="Fragments.UpdateFragment"
    >
    <TextView
        android:id="@+id/textView1_id"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_gravity="left|top"
        android:text="序号:"/>
    <TextView
        android:id="@+id/textView1_player"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_below="@+id/textView1_id"
        android:text="玩家:"
        />
    <EditText
        android:id="@+id/editText2_player"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/textView1_player"
        android:layout_alignTop="@+id/textView1_player"
        android:layout_alignBottom="@+id/textView1_player"
        android:hint="请输入玩家名称"
        />
    <TextView
        android:id="@+id/textView1_score"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_below="@+id/editText2_player"
        android:text="分数:"/>
    <EditText
        android:id="@+id/editText2_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2_player"
        android:layout_toRightOf="@+id/textView1_player"
        android:hint="请输入玩家分数"
        />
    <TextView
        android:id="@+id/textView1_level"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_below="@+id/editText2_score"
        android:text="关卡:"/>
    <EditText
        android:id="@+id/editText2_level"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2_score"
        android:layout_toRightOf="@+id/textView1_player"
        android:hint="请输入关卡数"
        />
    <TextView
        android:id="@+id/textView2_id"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textView1_id"/>
    <TextView
        android:id="@+id/textView_into"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="115dp"
        android:text="提示:这里为更新信息"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button_save"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_weight="1"
            android:text="更新"
            />
        <Button
            android:id="@+id/button_cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/button_save"
            android:layout_weight="1"
            android:text="取消"
            />
    </LinearLayout>
</RelativeLayout>

UpdateFragment

public class UpdateFragment extends Fragment implements View.OnClickListener {
    private EditText et_player;
    private EditText et_score;
    private EditText et_level;
    private GamePlayer gamePlayer;
    //activity 实现的接口
    private  UpdateFragmentListener updateFragmentListener;
    //定义接口
    public static interface UpdateFragmentListener {
        public GamePlayer findById(int id); //作用:查询

        public void update(GamePlayer gamePlayer);//作用:更新
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            updateFragmentListener = (UpdateFragmentListener) activity;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }
    //保证 activity 给 fragment 传参时,旋转屏幕参数不丢失
    public static UpdateFragment newInstance(int id) {
        UpdateFragment updateFragment = new UpdateFragment();
        Bundle b = new Bundle();
        b.putInt("id", id);
        updateFragment.setArguments(b);//保存传入的参数
        return updateFragment;
    }
    /*******************实例化 fragment 时,调用以下方法****************************/
    /**
     * 实例化时 查询数据
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int id = getArguments().getInt("id");

        //activity 从数据库中查询指定id的对象数据
        gamePlayer = updateFragmentListener.findById(id);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //实例化 fragment布局
        View view = inflater.inflate(R.layout.fragment_update, container, false);
        //查找界面 组件
        TextView tv_id = (TextView) view.findViewById(R.id.textView2_id);
        et_player = (EditText) view.findViewById(R.id.editText2_player);
        et_score = (EditText) view.findViewById(R.id.editText2_score);
        et_level = (EditText) view.findViewById(R.id.editText2_level);
        //界面按钮
        Button button_save = (Button) view.findViewById(R.id.button_save);
        Button button_cancel = (Button) view.findViewById(R.id.button_cancel);
        //注册监听事件
        button_save.setOnClickListener(this);
        button_cancel.setOnClickListener(this);
        //组件内容填充
        tv_id.setText(String.valueOf(gamePlayer.getId()));
        et_player.setText(gamePlayer.getPlayer());
        et_score.setText(String.valueOf(gamePlayer.getScore()));
        et_level.setText(String.valueOf(gamePlayer.getLevel()));
        return view;
    }

    /**************** fragment 上按钮的监听事件 *************************/
    /**
     * 按钮 监听事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_save:
                save();
                break;
            case R.id.button_cancel:
                getActivity().getFragmentManager().popBackStack();//弹出 栈
                break;
        }

    }

    //数据提交到数据库
    private void save() {
        GamePlayer g = new GamePlayer();

        //组件的输入内容添加 到数据库中
        g.setId(gamePlayer.getId());
        g.setPlayer(et_player.getText().toString());
        g.setScore(Integer.parseInt(et_score.getText().toString()));
        g.setLevel(Integer.parseInt(et_level.getText().toString()));

        //调用 activity中的更新方法
        updateFragmentListener.update(g);
        getActivity().getFragmentManager().popBackStack(); //出栈
    }

    @Override
    public void onDetach() {
        super.onDetach();
        updateFragmentListener = null;
    }
}

最后MainActivity(完成跟Fragment之间的交互及数据库方法)

mainActivity.xml(装Fragment)

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Main1229Activity">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main_layout"/>
</RelativeLayout>

MainActivity

public class Main1229Activity extends AppCompatActivity implements AddFragment.AddFragmentListener,
        GamePlayFragment.GamePlayerFragmentListener,UpdateFragment.UpdateFragmentListener{
    //操作数据库
    private DatabaseAdapter dbAdapter;
    //要交互的 fragment
    private GamePlayFragment gamePlayerFragment; //显示数据界面
    private UpdateFragment updateFragment; //更新数据界面
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1229);
        dbAdapter = new DatabaseAdapter(this);//实例化操作数据库类
        //显示列表数据
        showGamePlayerFragment();
    }
    /**
     * 实例化菜单 布局
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main1229, menu);
        return true;
    }
    /**
     * 当点击菜单项按钮时触发
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.add://添加按钮的操作
               AddFragment createGamePlayerFragment=AddFragment.newInstance();
                createGamePlayerFragment.show(getFragmentManager(),null);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    //添加
    @Override
    public void add(GamePlayer gamePlayer) {
        dbAdapter.add(gamePlayer);
        gamePlayerFragment.changeData();//添加后,重新加载数据
    }
    //显示列表
    @Override
    public void showGamePlayerFragment() {
        //获取 显示数据列表的fragment对象
        gamePlayerFragment = GamePlayFragment.newInstance();// 会调用:onCreateView方法
        //开启事务
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        //将 activity 中的布局文件 替换成 fragment
        ft.replace(R.id.main_layout, gamePlayerFragment);
        ft.addToBackStack(null);
        ft.commit();
    }
    //显示更新fragment
    @Override
    public void showUpdateFragment(int id) {
        updateFragment = UpdateFragment.newInstance(id);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.main_layout, updateFragment);
        ft.addToBackStack(null);
        ft.commit();
    }
    //删除
    @Override
    public void delete(int id) {
        dbAdapter.delete(id);
        gamePlayerFragment.changeData();//删除后 重新加载数据
    }
    //查找所有
    @Override
    public ArrayList<GamePlayer> findAll() {
        return dbAdapter.findAll();
    }
    //查找一个
    @Override
    public GamePlayer findById(int id) {
        return dbAdapter.findById(id);
    }
    //更新数据
    @Override
    public void update(GamePlayer gamePlayer) {
        dbAdapter.update(gamePlayer);
        gamePlayerFragment.changeData();//更新后 重新加载数据
    }
    /****************手机按键 监听事件*******************************/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if(getFragmentManager().getBackStackEntryCount()==1){//当 栈中只是一个fragment时,就结束程序
                finish();
                return true;
            }else {
                getFragmentManager().popBackStack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}

六丶小总结

1.熟悉掌握了SQLite的基本用法

2.加强了Fragment与Activity的交互

3.由于刚入门开始借用了有很多小错误的代码,找BUG各种挣扎,拖到现在才完成对于本节的学习
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: