2017-08-12 22 views
-2

私の質問は簡単です。私のアプリは、sqliteデータベースにデータを追加することができますが、今私はListView私のアプリケーションに自分のデータを表示するコードに取り組んでいます。以下のコードを使用すると、ListViewコードを使用すると、データベースから自分のデータを表示できますか?私はSQLiteDatabaseデータベースを使用します。 の代わりに DbAdapter db;。私はちょうどそれがListViewコードを使用してsqliteデータベースから私のデータを表示することが可能かどうかを知りたい。ListView形式のデータを表示するandroid studio sqlite

public class SalesActivity extends AppCompatActivity implements View.OnClickListener{ 
    TextView editDescription; 
    EditText editDate,editTime,editBarcode,editQuantity,editRetail,editAmount; 
    Button btnView,btnAdd; 
    SQLiteDatabase db; 

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

     setContentView(R.layout.sales); 
     editDate = (EditText)findViewById(R.id.editDate); 
     editTime = (EditText)findViewById(R.id.editTime); 
     editBarcode = (EditText)findViewById(R.id.editBarcode); 
     editDescription = (TextView) findViewById(R.id.editDescription); 
     editRetail = (EditText) findViewById(R.id.editRetail); 
     editQuantity = (EditText)findViewById(R.id.editQuantity); 
     editAmount = (EditText)findViewById(R.id.editAmount); 

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
     SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss a"); 
     editDate.setText(sdf.format(new Date())); 
     editTime.setText(stf.format(new Date())); 

     btnView = (Button)findViewById(R.id.btnView); 
     btnView.setOnClickListener(this); 

     btnAdd = (Button)findViewById(R.id.btnAdd); 
     btnAdd.setOnClickListener(this); 

     db = openOrCreateDatabase("ProductDB", Context.MODE_PRIVATE,null); 
     db.execSQL("CREATE TABLE IF NOT EXISTS product2(id INTEGER PRIMARY KEY AUTOINCREMENT, date VARCHAR, time VARCHAR, barcode VARCHAR, description VARCHAR, quantity VARCHAR, retail VARCHAR, amount VARCHAR)"); 
    } 
    public void onClick(View view){ 
     if(view==btnView){ 
      if(editBarcode.getText().toString().trim().length()==0){ 
       showMessage("","Please insert Barcode"); 
       return; 
      } 
      else{ 
       Cursor c = db.rawQuery("select * from product where " + 
         "barcode ='"+editBarcode.getText()+"'",null); 
       if(c.moveToFirst()){ 
        editDescription.setText(c.getString(1)); 

        editRetail.setText(c.getString(2)); 


       } 
      } 
     } 
     if(view==btnAdd){ 
      if(editDate.getText().toString().trim().length()==0 || 
        editTime.getText().toString().trim().length()==0 || 
        editBarcode.getText().toString().trim().length()==0 || 
        editDescription.getText().toString().trim().length()==0 || 
        editQuantity.getText().toString().trim().length()==0 || 
        editRetail.getText().toString().trim().length()==0 || 
        editAmount.getText().toString().trim().length()==0 
        ){ 
       showMessage("","Please insert all fields"); 
       return; 
      } 
      else{ 
       db.execSQL("INSERT INTO product2(date,time,barcode,description,quantity,retail,amount)"+ 
         "VALUES('"+editDate.getText()+ 
         "','"+editTime.getText()+ 
         "','"+editBarcode.getText()+ 
         "','"+editDescription.getText()+ 
         "','"+editQuantity.getText()+ 
         "','"+editRetail.getText()+ 
         "','"+editAmount.getText()+"')"); 
       showMessage("","Record added"); 
       clearText(); 
      } 
     } 

    } 
    public void clearText(){ 
     editDate.setText(""); 
     editTime.setText(""); 
     editBarcode.setText(""); 
     editDescription.setText(""); 
     editQuantity.setText(""); 
     editRetail.setText(""); 
     editAmount.setText(""); 

     editBarcode.requestFocus(); 
    } 
    public void showMessage(String title,String message){ 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setCancelable(true); 
     builder.setTitle(title); 
     builder.setMessage(message); 
     builder.show(); 
    } 


} 
+0

['SimpleCursorAdapter'](https://developer.android.com/reference/android/widget/SimpleCursorAdapter.html)のように' CursorAdapter'を使用してください。 –

+0

[listviewのデータをアンドロイドのsqliteデータベースから表示](https://stackoverflow.com/questions/30369253/show-data-in-listview-from-sqlite-database-in-android)の可能な複製 – Sufian

答えて

0

最初の活動

package com.example.admin.myapplicationdd; 

    import android.content.Context; 
    import android.database.Cursor; 
    import android.database.sqlite.SQLiteDatabase; 
    import android.support.annotation.IdRes; 
    import android.support.v7.app.AppCompatActivity; 
    import android.os.Bundle; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.RadioButton; 
    import android.widget.RadioGroup; 
    import android.widget.Toast; 

    public class Adddata extends AppCompatActivity { 
    EditText firstname,lastname; 
     RadioGroup rg; 
     RadioButton male,female; 
     String malefemale; 
     Button submitdata; 
    SQLiteDatabase db; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_adddata); 
      db=openOrCreateDatabase("mydemodata", Context.MODE_PRIVATE,null); 
      db.execSQL("create table if not exists demo(fname varchar2(20),lname varchar2(20),gender varchar2(20))"); 
     firstname=(EditText)findViewById(R.id.firstname); 
      male=(RadioButton)findViewById(R.id.male); 
      female=(RadioButton)findViewById(R.id.female); 
      lastname=(EditText)findViewById(R.id.lastname); 
      rg=(RadioGroup)findViewById(R.id.rg); 
      submitdata=(Button)findViewById(R.id.submit); 
      rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
       @Override 
       public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) { 
        if(male.isChecked()){ 
    malefemale="male"; 

        } 
       else if (female.isChecked()){ 
         malefemale="female"; 
        } 
       } 
      }); 
      submitdata.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
    db.execSQL("insert into demo values('"+firstname.getText().toString()+"','"+lastname.getText().toString()+"','"+malefemale+"')"); 
        Toast.makeText(getApplicationContext(),"insert success",Toast.LENGTH_SHORT).show(); 
       String s="select * from demo"; 
        Cursor c; 
        StringBuffer sb=new StringBuffer(); 
        c=db.rawQuery(s,null); 
        if(c.moveToFirst()){ 
         do{ 
    sb.append(c.getString(c.getColumnIndex("fname"))); 
    sb.append(c.getString(c.getColumnIndex("lname"))); 
          sb.append(c.getString(c.getColumnIndex("gender"))); 

         } 
         while (c.moveToNext()); 
         Toast.makeText(getApplicationContext(),sb,Toast.LENGTH_SHORT).show(); 
        } 
       } 
      }); 
     } 
    } 

リストビューの活動

package com.example.admin.myapplicationdd; 

    import android.content.Context; 
    import android.database.Cursor; 
    import android.database.sqlite.SQLiteDatabase; 
    import android.os.Bundle; 
    import android.support.v7.app.AppCompatActivity; 
    import android.widget.ListView; 
    import android.widget.SimpleAdapter; 
    import android.widget.Toast; 

    import java.util.ArrayList; 
    import java.util.HashMap; 


    public class ListData extends AppCompatActivity { 
    ListView mylist; 
     ArrayList<HashMap<String,String>> al; 
     SQLiteDatabase db; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_list_data); 
      mylist=(ListView)findViewById(R.id.mylist); 
      db=openOrCreateDatabase("mydemodata", Context.MODE_PRIVATE,null); 

      al=new ArrayList<HashMap<String,String>>(); 
      HashMap<String,String> hm; 
      String s="select * from demo"; 
      Cursor c; 
      StringBuffer sb=new StringBuffer(); 
      c=db.rawQuery(s,null); 
      if(c.moveToFirst()){ 
       do{ 
        hm=new HashMap<String, String>(); 
        hm.put("fname",c.getString(c.getColumnIndex("fname"))); 
        hm.put("lname",c.getString(c.getColumnIndex("lname"))); 
        hm.put("gender",c.getString(c.getColumnIndex("gender"))); 
    al.add(hm); 
       } 
       while (c.moveToNext()); 
       Toast.makeText(getApplicationContext(),sb,Toast.LENGTH_SHORT).show(); 
      } 
    String from[]={"fname","lname","gender"}; 
      int to[]={R.id.myfirstname,R.id.mylastname,R.id.mygender}; 
      SimpleAdapter ad=new SimpleAdapter(getApplicationContext(),al,R.layout.lists,from,to); 
    mylist.setAdapter(ad); 
     } 
    } 

私はあなたが

この例のヘルプをホップカスタムリストビューから

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    > 
<TextView 
    android:id="@+id/myfirstname" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="firstname" 
    android:textColor="@android:color/black" 
    android:textSize="20dp"/> 
    <TextView 
     android:id="@+id/mylastname" 

     android:textColor="@android:color/black" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Lastname" 
     android:textSize="20dp"/><TextView 
    android:id="@+id/mygender" 

    android:textColor="@android:color/black" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="gender" 
    android:textSize="20dp"/> 
</LinearLayout> 

をxmlファイルを作成します

0

私のコードを共有していますが、違いは私はあらかじめデータベースを使用しています。
次に、あなたのSalesActivity.javaでこのカーソルを使用SQLiteDatabase.java

public Cursor getNames() { 

     SQLiteDatabase db = getReadableDatabase(); 
     SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); 
     int i =3; //id no 
     String [] sqlSelect = {"1 _id", "Name"};//_id and Name are rows in my db's table 
     String sqlTables = "BusNames";//table name 
     String selection = "_id = ?"; 
     String[] selectionArgs = { ""+i }; 
     qb.setTables(sqlTables); 
     Cursor c = qb.query(db, sqlSelect, selection, selectionArgs, 
       null, null, null);//this query is basically "select Name from table where id=3"  
     c.moveToFirst(); 
     return c; 

    } 

でこのカーソル機能を使用することができます。
これらの変数を宣言します。

private Cursor names; 
    private SQLiteDatabase db; 

これらの行をonCreate機能にコピーします。また

 db = new SQLiteDatabase(this); 
     names = db.getNames(); 
     final ListAdapter adapter = new SimpleCursorAdapter(this, 
       android.R.layout.simple_list_item_1, 
       names, 
       new String[] {"Name"}, 
       new int[] {android.R.id.text1});//this is blank default id 
     final ListView listView = (ListView) findViewById(R.id.listV2);//id of ListView 
     listView.setAdapter(adapter); 


、あなたのSQLiteDatabase.javaでこの関数をコピーします。

@Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     names.close(); 
     db.close(); 
    } 

これにより、データベースのアイテムがリストビューに表示されます。しかし、あなたのデータベースに応じてクエリを変更することを忘れないでください。「テーブルから名前を選択します(id = 3)」を印刷します。

関連する問題