如何从ListView Adapter类访问SQLite数据库

时间:2016-02-11 00:06:30

标签: java android sqlite listview android-adapter

我正在构建一个训练日志,其中包含用户在TrainingLogCreate中添加的两个字符串,这些字符串使用DBAdapter中的SQLite数据库添加到TrainingLog中的自定义listView(lv)。我的问题是我想从列表视图中删除一行,为此我需要通过自定义列表视图适配器(TrainingAdapter)添加一个按钮。但是,我不确定如何从TrainingLog(主片段)访问我的按钮,并在那里实现onClickListener方法。关于如何做到这一点的任何想法?

TrainingLog:

public class TrainingLog extends Fragment {

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

    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);
            String pos=c.getString(2);
            details.add(pos);
        }    
        db.close();  

        //TrainingAdapter adapter = new TrainingAdapter(this, players);  
        //adapter=new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_selectable_list_item,players);
        //lv.setAdapter(adapter);
         //ListAdapter myTrainingAdapter = new TrainingAdapter(this.getActivity(), players);    
       //lv.setAdapter(myTrainingAdapter);

        String[] playerArray = new String[players.size()];
        playerArray = players.toArray(playerArray);

        String[] detailArray =  new String[details.size()];
        detailArray = details.toArray(detailArray);

        ListAdapter myAdapter = new TrainingAdapter(this.getActivity(), playerArray, detailArray);
        lv.setAdapter(myAdapter);

        return rootView;
    }    

    @Override
    public void onResume() {
        super.onResume();    
        final DBAdapter db = new DBAdapter(this.getActivity());    
        players.clear();    
        ///OPEN
        db.openDB();    

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

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

        db.close();

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

        String[] playerArray = new String[players.size()];
        playerArray = players.toArray(playerArray);

        String[] detailArray =  new String[details.size()];
        detailArray = details.toArray(detailArray);

        ListAdapter myAdapter = new TrainingAdapter(this.getActivity(), playerArray, detailArray);
        lv.setAdapter(myAdapter);    
    }

    private void loadFragment()
    {
}

    @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:

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

TrainingAdapter:

public class TrainingAdapter extends ArrayAdapter<String> {    
    private final String[] playerArray;
    private final String[] detailArray;
    Button removeButton;    
    TrainingAdapter(FragmentActivity context, String[] playerArray, String[] detailArray) {
        super(context, R.layout.training_row, playerArray);   
        this.playerArray = playerArray;
        this.detailArray = detailArray;    
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater JohnsInflater = LayoutInflater.from(getContext());
        View customView = JohnsInflater.inflate(R.layout.training_row, parent, false);
        TextView exercizeTextView = (TextView) customView.findViewById(R.id.exercizeTextView);
        TextView detailTextView = (TextView) customView.findViewById(R.id.detailTextView);
        Button removeButton = (Button) customView.findViewById(R.id.deleteButton);

        removeButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                final DBAdapter db = new DBAdapter();

             }
         });

        exercizeTextView.setText(playerArray[position]);
        detailTextView.setText(detailArray[position]);    

        return customView;
    }
}

将对DBAdapter:

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

    //REMOVE FROM TABLE
    public long remove(String name,String pos)
    {
        try
        {
            ContentValues cv=new ContentValues();
            cv.remove(name);
            cv.remove(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);
    }
}

2 个答案:

答案 0 :(得分:0)

使用界面或广播,您可以这样做。

答案 1 :(得分:0)

创建一个界面,它就可以了。

  private View.OnClickListener delete;
 public void setDelete(View.OnClickListener delete){
        this.delete= delete;
    }
      removeButton.setTag(position);
    removeButton.setOnClickListener(delete);

现在,在您的activity类中实现onClickListener并调用adapter的methosd

public class TrainingLogCreate extends AppCompatActivity implements View.OnClickListener{

  @Override
 public void onClick(View view) {
     Object tag = (Integer) view.getTag();
     switch (view.getId()){
         case R.id.deleteButton:
          if (tag != null && tag instanceof Integer) {

                 int position = (Integer) tag;
         SQLiteDatabase dataBase = db.getWritableDatabase();
        dataBase.delete(DBAdapter.TABLE_NAME,
     DBAdapter.POSITION +"="+position, null);
            yourlistAdapter.notifyDataSetChanged();

尝试让我知道是否有任何问题。