使用sqlite无法从listview复选框中获取多个项目

时间:2016-11-09 10:17:58

标签: android sqlite listview checkbox multiple-choice

我有一个listView,可以选择多个复选框。我从listview中获取值,在sqlite中执行查询。当我单击删除按钮时,我需要删除所选项目,但它不起作用。它必须有最少的4个复选框选项才能转到带有进程按钮的另一个活动。有解决方案吗这是我的功能代码:

page_1.class

public class page_1 extends AppCompatActivity {

Toolbar toolbar;
public ListView lvwSample;
ListAdapter adapter;
private gejala item;
private DatabaseHelper dbHelper;
private ArrayList<gejala> agjl;
private List<gejala> gejalas;
ArrayList<gejala> arrayList=new ArrayList<gejala>();
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_page_1);
    toolbar = (Toolbar)findViewById(R.id.toolBar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    //final Button buttonhapus = (Button)findViewById(R.id.buttonhapus);
    //final Button buttonprses = (Button)findViewById(R.id.buttonproses);
    final CheckBox chkChecked = (CheckBox)findViewById(R.id.chkChecked);

    gejalas = getgejalas();

    dbHelper = new DatabaseHelper(this);
    try {
        dbHelper.checkAndCopyDatabase();
        dbHelper.open();
    } catch (SQLiteException e){
        Log.d("AAAAAA", "CCCCCCCCCCCCCC");
    }

    try {
        final Cursor cursor = dbHelper.QueryData("select nama_gejala from gejala");
        Log.d("mantap", String.valueOf(cursor.getCount()));
        if(cursor != null){
            if (cursor.moveToFirst()){
                do{
                    //arrayList = new ArrayList<gejala>();
                    item = new gejala("", false);
                    arrayList.add(item);
                    item.setNama_gejala(cursor.getString(0));
                    adapter = new ListAdapter(this, R.layout.item, arrayList);
                    lvwSample = (ListView)findViewById(R.id.lvwSample);
                    lvwSample.setAdapter(adapter);
                    lvwSample.getCheckedItemPosition();
                    lvwSample.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                    lvwSample.setItemsCanFocus(false);
                    adapter.notifyDataSetChanged();
                    lvwSample.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            item = (gejala)parent.getItemAtPosition(position);
                            //item = arrayList.get(position);

                            boolean lastChecked = item.isChecked();
                            item.setChecked(!lastChecked);
                            adapter.notifyDataSetChanged();
                            lvwSample.invalidate();

                        }
                    });
                }
                while (cursor.moveToNext());
            }
        }
    } catch (SQLiteException e){
        Log.d("AAAAAA", "BBBBBBBBB");
    }

}

listAdapter.class

public class ListAdapter extends BaseAdapter {
private Activity activity;
int id;
private ArrayList<gejala> gejalas;

public ListAdapter(Activity activity, int item, ArrayList<gejala> gejalas) {
    this.gejalas = gejalas;
    this.activity = activity;

}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return gejalas.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return gejalas.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}
@SuppressLint("InflateParams")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView==null){
        LayoutInflater mInflater = (LayoutInflater) activity.getSystemService(
                Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.item, null);
    }

    //TextView tvwTitle=(TextView)convertView.findViewById(R.id.tvwTitle);
    CheckBox chkChecked=(CheckBox)convertView.findViewById(R.id.chkChecked);

    String nama_gejala = gejalas.get(position).getNama_gejala();
    boolean blnChecked = gejalas.get(position).isChecked();
    chkChecked.setText(nama_gejala);
    chkChecked.setChecked(blnChecked);
    chkChecked.setTag(gejalas);

    chkChecked.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean lastChecked = gejalas.get(position).isChecked();
            gejalas.get(position).setChecked(!lastChecked);
        }
    });
    return convertView;
}
}

gejala.class

public class gejala {
private String id_gejala;
private String nama_gejala;
private boolean blnChecked;

public gejala(String nama_gejala, boolean blnChecked) {
    this.setNama_gejala(nama_gejala);
    this.setChecked(blnChecked);
}
public String getId_gejala() {
    return id_gejala;
}

public void setId_gejala(String id_gejala) {
    this.id_gejala = id_gejala;
}

public String getNama_gejala() {
    return nama_gejala;
}

public void setNama_gejala(String nama_gejala) {
    this.nama_gejala = nama_gejala;
}

public boolean isChecked() {
    return blnChecked;
}

public void setChecked(boolean blnChecked) {
    this.blnChecked = blnChecked;
}
}

DatabaseHelper.class

public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static String DB_NAME = "tbcd.db";
private static String TABLE_GEJALA = "gejala";
private static String TABLE_Penyakit = "penyakit";
private static String TABLE_Relasi = "relasi";

private final Context mycontext;
private SQLiteDatabase db;

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, 1);
    if (android.os.Build.VERSION.SDK_INT >= 17) {
        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
    } else {
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    }
    this.mycontext = context;
}
public void create() throws IOException {
    boolean dbExist = checkDataBase();

    if (dbExist) {
        //do nothing - database already exist
    } else {
        // By calling this method and empty database will be created into the default system path
        // of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

private void copyDataBase() throws IOException {
    //Open your local db as the input stream
    InputStream myInput = mycontext.getAssets().open(DB_NAME);

    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
}
public boolean open() throws SQLiteException{
        String myPath = DB_PATH + DB_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    return false;
}
public void ExeSQLData(String sql) throws SQLiteException{
    db.execSQL(sql);
}
public Cursor QueryData(String query) throws SQLiteException{
    return db.rawQuery(query,null);
}
@Override
public synchronized void close() {
    if (db != null)
        db.close();
    super.close();
}

public boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String path = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
    }
    if (checkDB != null) checkDB.close();
        return checkDB != null ? true : false;
    }
public void checkAndCopyDatabase(){
    boolean dbExist=checkDataBase();
    if(dbExist){
        Log.d("TAG","Database already exist");
    }else{
        this.getReadableDatabase();
        try{
            copyDataBase();
        }catch (IOException e){
            Log.d("TAG","Error copying database");
        }
    }
}

public List<gejala> getgejalas() {
    ArrayList<gejala> arrayList=new ArrayList<gejala>();

    try {
        String query = "SELECT * FROM " + TABLE_GEJALA;
        SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = db.rawQuery(query, null);

        while (cursor.moveToNext()) {
            String id_gejala = cursor.getString(0);
            String nama_gejala = cursor.getString(1);

            gejala gjl = new gejala("", false);
            arrayList.add(gjl);

        }
    } catch(Exception e) {
        Log.d("DB", e.getMessage());
    }

    return arrayList;
}

}

page_1.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="tb.detectortbc.page_1"
android:background="@drawable/background3">

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:id="@+id/view">
    <include
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        layout="@layout/toolbar_layout"
        />

</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="85dp"
    android:layout_alignParentRight="true"
    android:layout_marginRight="65dp"
    android:layout_alignParentTop="true"
    android:layout_marginTop="80dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="400dp">
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="15dp"
    android:textSize="35dp"
    android:textStyle="bold"
    android:text="Pilih Gejala"
    android:id="@+id/pilihgejala"
    android:textColor="@color/colorTosca"
    android:textAlignment="center" />
</LinearLayout>

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/lvwSample"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="75dp"
    android:layout_alignParentTop="true"
    android:layout_marginTop="154dp"
    android:layout_alignParentRight="true"
    android:layout_marginRight="25dp"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="25dp"
    android:layout_alignParentEnd="true"
     />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="30dp"
    android:layout_alignParentTop="true"
    android:layout_marginTop="490dp"
    android:layout_centerHorizontal="true">
<Button
    android:layout_width="100dp"
    android:layout_height="50dp"
    android:layout_weight="10"
    android:text="Proses"
    android:textSize="20dp"
    android:background="@color/colorTosca"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:id="@+id/buttonproses"
    android:onClick="pilihan"
    android:layout_gravity="center"/>
    <Button
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="Hapus Pilihan"
        android:textSize="20dp"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:id="@+id/buttonhapus"
        android:onClick="delete"
        android:layout_gravity="center"/>
</LinearLayout>
</RelativeLayout>

item.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">

   <CheckBox
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/chkChecked"
       android:focusable="false"
       android:focusableInTouchMode="false"
       android:text="gejala"
       android:textSize="20dp"
       android:layout_alignParentLeft="true"    />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

private String getSelected() {
    StringBuffer sb = new StringBuffer();
    for (gejala gj : gejalaList) {
        if (gj.isChecked()) {
            sb.append(gj.getId_gejala());
            sb.append(",");
        }
    }
 return sb.toString();
}

现在,您可以创建返回的ArrayList的{​​{1}}。

String

在这里,您获得了所选列表项的列表。