0

I am creating a list view which is being populated by a Sqlite database (created by my "DBAdapter" class). This log that I am building begins with a fragment containing the listView, which opens up an activity ("TrainingLogCreate.java" via an add button) that presents the user with two editText boxes (one not currently used). When I go back to the fragment, the data is written to the sqlite database, but the new data does not appear until I go back into my nav drawer and select the log, which reloads the fragment and then displays the new information in the list view. Is there anyway I can have the listView re-populate when the activity dismisses and the fragment is resumed?

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);
    }




}

Training Log:

    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);
        }
    }
}
John Harding II
  • 564
  • 1
  • 6
  • 20

1 Answers1

0

Implement your DBAdapter from BaseAdapter or CusrsorAdapter. Whenever data updated in DB call dataSetChanged or SwapeCursor depending on your implementation.

Please refer following link for implementation.

Cursor adapter and sqlite example

How to update ListView in case of CursorAdapter usage?

Community
  • 1
  • 1
Rakesh
  • 756
  • 1
  • 9
  • 19