2017-08-12 42 views
-2

我的問題很簡單。我的應用程序可以將數據添加到sqlite數據庫,但現在我的工作ListView代碼顯示我的數據在我的應用程序。如果我使用下面的代碼,如果我使用ListView代碼,我可以顯示數據庫中的數據嗎?我使用SQLiteDatabase db;而不是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

使用'CursorAdapter',就像['SimpleCursorAdapter'](https://developer.android.com/reference/android/widget/SimpleCursorAdapter.html)一樣。 –

+0

[在android中顯示數據從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文件

<?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> 

我跳這個例子可以幫助您

0

我分享我的代碼,但區別是我使用prepopulated數據庫。
您可以使用此功能光標在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; 

    } 

然後用這個光標在SalesActivity.java
聲明這些變量。

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」。