ListView在恢复后没有重新填充

时间:2016-02-10 00:24:39

标签: java android sqlite listview android-fragments

我正在创建一个列表视图,该视图由Sqlite数据库填充(由我的" DBAdapter"类创建)。我正在构建的这个日志以包含listView的片段开始,该片段打开一个活动(" TrainingLogCreate.java"通过添加按钮),向用户显示两个editText框(一个当前未使用)。当我回到片段时,数据被写入sqlite数据库,但是在我返回导航抽屉并选择日志之前,新数据不会出现,日志会重新加载片段然后在列表中显示新信息视图。无论如何,当活动解散并且片段恢复时,我可以重新填充listView吗?

将对DBAdapter:

    package com.hardingsoftware.hrcfitness;

/**
 * Created by John on 2/9/16.
 */



public class DBAdapter {

    //COLUMNS
    static final String ROWID="id";
    static final String NAME = "name";
    static final String POSITION = "position";

    //DB PROPERTIES
    static final String DBNAME="m_DB";
    static final String TBNAME="m_TB";
    static final int DBVERSION='1';

    static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name TEXT NOT NULL,position TEXT NOT NULL);";

    final Context c;
    SQLiteDatabase db;
    DBHelper helper;

    public DBAdapter(FragmentActivity ctx) {
        // TODO Auto-generated constructor stub

        this.c=ctx;
        helper=new DBHelper(c);
    }



    // INNER HELPER DB CLASS
    private static class DBHelper extends SQLiteOpenHelper
    {

        public DBHelper(Context context ) {
            super(context, DBNAME, null, DBVERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            try
            {
                db.execSQL(CREATE_TB);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

            Log.w("DBAdapetr","Upgrading DB");

            db.execSQL("DROP TABLE IF EXISTS m_TB");

            onCreate(db);
        }

    }

    // OPEN THE DB
    public DBAdapter openDB()
    {
        try
        {
            db=helper.getWritableDatabase();

        }catch(SQLException e)
        {
            Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        return this;
    }


    //CLOSE THE DB
    public void close()
    {
        helper.close();
    }

    //INSERT INTO TABLE
    public long add(String name,String pos)
    {
        try
        {
            ContentValues cv=new ContentValues();
            cv.put(NAME, name);
            cv.put(POSITION, pos);

            return db.insert(TBNAME, ROWID, cv);

        }catch(SQLException e)
        {
            e.printStackTrace();
        }

        return 0;
    }

    //GET ALL VALUES

    public Cursor getAllNames()
    {
        String[] columns={ROWID,NAME,POSITION};

        return db.query(TBNAME, columns, null, null, null, null, null);
    }




}

培训日志:

    package com.hardingsoftware.hrcfitness;


/**
 * Created by John on 2/3/16.
 */

public class TrainingLog extends Fragment {

    ListView lv;
    ArrayList<String> players = new ArrayList<String>();
    ArrayAdapter<String> adapter;
    ArrayAdapter<String> clearAdapter;

    public TrainingLog() {
        // Required empty public constructor
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View rootView = inflater.inflate(R.layout.fragment_training_log, container, false);
        lv = (ListView) rootView.findViewById(R.id.myListView);
        final DBAdapter db = new DBAdapter(this.getActivity());
        setHasOptionsMenu(true);

        players.clear();

        //OPEN
        db.openDB();



        //RETRIEVE
        Cursor c=db.getAllNames();

        while(c.moveToNext())
        {
            String name=c.getString(1);
            players.add(name);
        }



        db.close();




        adapter=new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_selectable_list_item,players);
        lv.setAdapter(adapter);
        /* ListAdapter myTrainingAdapter = new TrainingAdapter(this.getActivity(), exercizeActivity, exercizeDetail);
        ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
        myListView.setAdapter(myTrainingAdapter); */


        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();

        final DBAdapter db = new DBAdapter(this.getActivity());



        /* //OPEN
        db.openDB();

        getContext().deleteDatabase("db");

        //RETRIEVE
        Cursor c=db.getAllNames();

        while(c.moveToNext())
        {
            String name=c.getString(1);
            players.add(name);
        }



        db.close();

        lv.setAdapter(clearAdapter);


        adapter=new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_selectable_list_item,players);


        lv.setAdapter(adapter); */

    }

    @Override
    public void onCreateOptionsMenu(
            Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.traning_menu_itemdetail, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_add:
                Intent trainingCreateIntent = new Intent (getContext(), TrainingLogCreate.class);
                startActivity(trainingCreateIntent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


}

TrainingLogCreate:

    package com.hardingsoftware.hrcfitness;


/**
 * Created by John on 2/6/16.
 */
public class TrainingLogCreate extends AppCompatActivity {


    EditText nameTxt;
    EditText posTxt;
    Button savebtn;
    Context context = this;

    public TrainingLogCreate() {
        // Required empty public constructor
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.training_log_create);

        savebtn = (Button) findViewById(R.id.saveButton);
        nameTxt = (EditText) findViewById(R.id.exercizeActivity);
        posTxt = (EditText) findViewById(R.id.exercizeDetails);
        final DBAdapter db=new DBAdapter(this);



        savebtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {

                // TODO Auto-generated method stub

                //OPEN
                db.openDB();

                //INSERT
                long result=db.add(nameTxt.getText().toString(), posTxt.getText().toString());

                if(result > 0)
                {
                    nameTxt.setText("");
                    posTxt.setText("");
                }else
                {
                    Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
                }


                //CLOSE DB
                db.close();

                //Close Fragment


                finish();

            }
        });



    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater mif = getMenuInflater();
        mif.inflate(R.menu.training_create_menu, menu);
        getActionBar().show();
        return super.onCreateOptionsMenu(menu);




    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_save:
                //add save functionality
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

从BaseAdapter或CusrsorAdapter实现DBAdapter。每当在DB中更新数据时,都会根据您的实现调用dataSetChanged或SwapeCursor。

请参阅以下链接以了解实施情况。

Cursor adapter and sqlite example

How to update ListView in case of CursorAdapter usage?