2016-04-13 106 views
-3

我想製作一個報價應用程序,顯示報價,作者和收藏按鈕。從SQLite獲取數據到ListView的ArrayList

我有2個textViews一個自定義的ListView,和1個切換按鈕

我使用SQLite與預填充數據(所以我已經把所有的數據)

如何顯示報價和作者到2個textviews不使用SimpleCursorAdapter

我希望它使用ArrayList和ArrayAdapter

這是代碼

使

DatabaseOpenHelper.java

public class DatabaseOpenHelper extends SQLiteAssetHelper { 

private static final String DATABASE_NAME = "mqn.db"; 
private static final int DATABASE_VERSION = 1; 

private static final String TABLE_NAME = "quote"; 
public static final String COLUMN_ID = "_id"; 
public static final String COLUMN_QUOTES = "quotesText"; 
public static final String COLUMN_AUTHOR= "author"; 
public static final String COLUMN_FAV = "fav"; 
public static final String COLUMN_GENRE = "genre"; 

private SQLiteDatabase database; 

private final Context context; 

// database path 
private static String DATABASE_PATH; 

/** constructor (Menambil PATH ke file database) */ 
public DatabaseOpenHelper(Context ctx) { 
    super(ctx, DATABASE_NAME, null, DATABASE_VERSION); 
    this.context = ctx; 
    DATABASE_PATH = context.getFilesDir().getParentFile().getPath() 
      + "/databases/"; 

} 

/** 
* Creates a empty database on the system and rewrites it with your own 
* database. 
* */ 
public void create() throws IOException { 
    boolean check = checkDataBase(); 

    SQLiteDatabase db_Read = null; 

    // Creates empty database default system path 
    db_Read = this.getWritableDatabase(); 
    db_Read.close(); 
    try { 
     if (!check) { 
      copyDataBase(); 
     } 
    } catch (IOException e) { 
     throw new Error("Error copying database"); 
    } 
} 

/** 
* Check if the database already exist to avoid re-copying the file each 
* time you open the application. 
* 
* @return true if it exists, false if it doesn't 
*/ 
private boolean checkDataBase() { 
    SQLiteDatabase checkDB = null; 
    try { 
     String myPath = DATABASE_PATH + DATABASE_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READWRITE); 
    } catch (SQLiteException e) { 
     // database does't exist yet. 
    } 

    if (checkDB != null) { 
     checkDB.close(); 
    } 
    return checkDB != null ? true : false; 
} 

/** 
* Copies your database from your local assets-folder to the just created 
* empty database in the system folder, from where it can be accessed and 
* handled. This is done by transfering bytestream. 
* */ 
private void copyDataBase() throws IOException { 

    // Open your local db as the input stream 
    InputStream myInput = context.getAssets().open(DATABASE_NAME); 

    // Path to the just created empty db 
    String outFileName = DATABASE_PATH + DATABASE_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); 
    } 

    // Close the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

} 

/** Start DB from here */ 

/** open the database */ 
public void open() throws SQLException { 
    String myPath = DATABASE_PATH + DATABASE_NAME; 
    database = SQLiteDatabase.openDatabase(myPath, null, 
      SQLiteDatabase.OPEN_READWRITE); 
} 

/** close the database */ 
@Override 
public synchronized void close() { 
    if (database != null) 
     database.close(); 
    super.close(); 
} 

// insert a user into the database 
public long insertUser(String quotesText, String author, String fav) { 
    ContentValues initialValues = new ContentValues(); 
    initialValues.put(COLUMN_QUOTES, quotesText); 
    initialValues.put(COLUMN_AUTHOR, author); 
    initialValues.put(COLUMN_FAV, fav); 
    return database.insert(TABLE_NAME, null, initialValues); 
} 

// updates a user 
public boolean updateUser(long rowId, String fav) { 
    ContentValues args = new ContentValues(); 
    args.put(COLUMN_FAV, fav); 
    return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0; 
} 

// retrieves a particular user 
public Cursor getUser(long rowId) throws SQLException { 
    Cursor mCursor = database.query(true, TABLE_NAME, new String[] { 
        COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, 
      COLUMN_ID + " = " + rowId, null, null, null, null, null); 
    if (mCursor != null) { 
     mCursor.moveToFirst(); 
    } 

    return mCursor; 
} 

// delete a particular user 
public boolean deleteContact(long rowId) { 
    return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0; 
} 

// retrieves all users 
public Cursor getAllUsers() { 
    return database.query(TABLE_NAME, new String[] { COLUMN_ID, 
        COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null, 
      null, null, null); 
} 

public Cursor getCertain(String valueGenre) { 
    String WHERE = "genre = ?"; 
    String[] VALUE = new String[] {valueGenre}; 
    return database.query(TABLE_NAME, new String[]{COLUMN_ID, 
        COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE, 
      null, null, null); 
} 

quotes_listview(自定義的ListView)

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:id="@+id/linearLayout"> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="New Text" 
     android:id="@+id/txtQuote" 
     style="@style/QuotesFont" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_rowWeight="1" 
     android:layout_weight="1" 
     android:layout_margin="15dp" /> 



    <ToggleButton 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/heartImage" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" 
     android:layout_marginTop="30dp" 
     android:background="@drawable/fav" 
     android:textOff="" 
     android:textOn="" 
     android:layout_rowWeight="1" 
     android:layout_weight="3" 
     android:descendantFocusability="blocksDescendants" 
     android:layout_marginLeft="30dp" 
     android:layout_marginRight="15dp" /> 

</LinearLayout> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New Text" 
    android:id="@+id/txtAuthor" 
    style="@style/AuthorFont" 
    android:layout_below="@+id/linearLayout" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginLeft="15dp" 
    android:layout_marginBottom="5dp" /> 

<!--<TextView--> 
    <!--android:layout_width="wrap_content"--> 
    <!--android:layout_height="wrap_content"--> 
    <!--android:text="New Text"--> 
    <!--android:id="@+id/text2"--> 
    <!--android:layout_below="@+id/text1"--> 
    <!--android:layout_alignParentRight="true"--> 
    <!--android:layout_alignParentEnd="true"--> 
    <!--style="@style/AuthorFont"--> 
    <!--android:layout_marginBottom="10dp"--> 
    <!--android:layout_rowWeight="1"--> 
    <!--android:layout_weight="1" />--> 

ListOfQuotes.java

public class ListOfQuotes { 

private String quote; 
private String author; 
private int fav; 

public ListOfQuotes() { 
} 

public ListOfQuotes(String quote, String author, int fav) { 
    this.quote = quote; 
    this.author = author; 
    this.fav = fav; 
} 

public ListOfQuotes(String quote, String author) { 
    this.quote = quote; 
    this.author = author; 
} 

public String getQuote() { 
    return quote; 
} 

public void setQuote(String quote) { 
    this.quote = quote; 
} 

public String getAuthor() { 
    return author; 
} 

public void setAuthor(String author) { 
    this.author = author; 
} 

public int getFav() { 
    return fav; 
} 

public void setFav(int fav) { 
    this.fav = fav; 
} 
} 

QuotesAdapter.java

public class QuotesAdapter extends BaseAdapter { 

private Activity activity; 
private ArrayList<ListOfQuotes> data; 
private LayoutInflater inflater; 
boolean isSelected = false; 
ToggleButton imgHeart; 

public QuotesAdapter(Activity activity, ArrayList<ListOfQuotes> data) { 
    this.activity = activity; 
    this.data = data; 
    this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 


@Override 
public int getCount() { 
    return data.size(); 
} 

@Override 
public Object getItem(int position) { 
    return data.get(position); 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ListOfQuotes loq = data.get(position); 
    if(convertView == null) 
    { 
     convertView = inflater.inflate(R.layout.quotes_listview, null); 
    } 

    TextView txtQuotes = (TextView) convertView.findViewById(R.id.txtQuote); 
    TextView txtAuthors = (TextView) convertView.findViewById(R.id.txtAuthor); 
    imgHeart = (ToggleButton) convertView.findViewById(R.id.heartImage); 


    txtQuotes.setText(loq.getQuote()); 
    txtAuthors.setText(loq.getAuthor()); 

    return convertView; 
} 
} 

QuotesActivity.java

public class QuotesActivity extends AppCompatActivity { 

ListView quotesList; 
DatabaseOpenHelper myDbHelper; 

ArrayList<ListOfQuotes> arrQuotes; 
QuotesAdapter adapter; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_quotes); 

    myDbHelper = new DatabaseOpenHelper(this); 

    try { 
     // check if database exists in app path, if not copy it from assets 
     myDbHelper.create(); 
    } catch (IOException ioe) { 
     throw new Error("Unable to create database"); 
    } 

    try { 
     // open the database 
     myDbHelper.open(); 
     myDbHelper.getWritableDatabase(); 
    } catch (SQLException sqle) { 
     throw sqle; 
    } 

    arrQuotes = new ArrayList<ListOfQuotes>(); 
    quotesList = (ListView) findViewById(R.id.quotesList); 
    adapter = new QuotesAdapter(QuotesActivity.this, arrQuotes); 
    quotesList.setAdapter(adapter); 

我不知道如何在這之後做到這一點。

+0

使用'自定義列表View'用'基地Adapter'。 –

+0

是的,已經使用BaseAdapter自定義ListView,我只是不知道如何顯示它[已編輯我的帖子]。 –

+0

@HendraSetiawan - 看起來你已經完成了80%的編碼!這裏發生了什麼問題?您是否收到任何錯誤或ListView無法正常工作? –

回答

0

嘗試使用此代碼的工作,並把你的附加域.xml文件和java文件

ListViewActivity.java

public class ListViewActivity extends Activity 
{ 
    ListView listCustom; 
    private SQLiteDatabase db; 
    ProductDatabase customerDB; 
    ProductAdapter customAdapter; 
    static final String DATABASE_NAME = "login.db"; 
    public static String DB_PATH; 
    private ArrayList<LevelList> results = new ArrayList<LevelList>(); 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.product_list); 

     levelLists = new ArrayList<LevelList>(); 
     customerDB = new ProductDatabase(getApplicationContext()); 
     customerDB = customerDB.open(); 
     listCustom = (ListView) findViewById(R.id.listView1); 
     mainMenu(); 
    } 

    public void mainMenu() 
    { 
     results.clear(); 
     DB_PATH = "/data/data/com.gt.invoicemaker/databases/"; 
     String myPath = DB_PATH + DATABASE_NAME; 
     db = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY); 
      final Cursor c = db.rawQuery("SELECT ID AS _id, USERID, INAME, IPRICE FROM ITEM, null); 
      // Note: Master is the one table in External db. Here we trying to access the records of table from external db. 
     if (c != null) { 
       if (c.moveToFirst()) { 
        do { 
         LevelList results1 = new LevelList(); 
         int _id = c.getInt(c.getColumnIndex("_id")); 
         String userName = c.getString(c.getColumnIndex("INAME")); 

         results1.id = _id; 
         results1.item = userName; 
         results.add(results1); 
        }while (c.moveToNext()); 
       } 
     } 
       customAdapter = new ProductAdapter(getApplicationContext(), results); 
       listCustom.setAdapter(customAdapter); 
    } 
    } 
} 

ProductAdapter.java

public class ProductAdapter extends BaseAdapter { 

    private Context mContext; 
    private List<LevelList> listItem; 

     public ProductAdapter(Context c,List<LevelList> listItem) { 
      mContext = c; 
      this.listItem = listItem; 
     } 

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

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

     @Override 
     public long getItemId(int position) { 
      // TODO Auto-generated method stub 
      return position; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      // TODO Auto-generated method stub 
      LayoutInflater inflater = (LayoutInflater) mContext 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

      View rowView=inflater.inflate(R.layout.singleproduct, null,true); 

       TextView textView = (TextView) rowView.findViewById(R.id.single_product); 
       textView.setText(listItem.get(position).item); 
      return rowView; 
     } 
} 

product_list.xml

<?xml version="1.0" encoding="utf-8"?> 
     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" > 

        <ListView 
         android:id="@+id/listView1" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:layout_above="@+id/addnew" 
         android:layout_below="@+id/mainview" 
         android:layout_centerHorizontal="true" 
         android:layout_marginLeft="10dp" 
         android:layout_marginRight="10dp" 
         android:layout_marginTop="7dp" 
         android:layout_marginBottom="7dp" 
         android:scrollbars="none" > 

        </ListView> 

     </RelativeLayout> 

singleproduct.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" 
    android:orientation="vertical" > 

     <TextView 
      android:id="@+id/single_product" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_centerVertical="true" 
      android:textColor="@android:color/white" 
      android:layout_marginLeft="15dp" 
      android:text="" /> 

</LinearLayout> 

DataBaseHelper.java

public class DataBaseHelper extends SQLiteOpenHelper 
{ 
    public DataBaseHelper(Context context, String name,CursorFactory factory, int version) 
    { 
       super(context, name, factory, version); 
    } 
    // Called when no database exists in disk and the helper class needs 
    // to create a new one. 
    @Override 
    public void onCreate(SQLiteDatabase _db) 
    { 
      _db.execSQL(ProductDatabase.DATABASE_CREATE); 
    } 
    // Called when there is a database version mismatch meaning that the version 
    // of the database on disk needs to be upgraded to the current version. 
    @Override 
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
    { 
      // Log the version upgrade. 
      Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data"); 


      // Upgrade the existing database to conform to the new version. Multiple 
      // previous versions can be handled by comparing _oldVersion and _newVersion 
      // values. 
      // The simplest case is to drop the old table and create a new one. 
      _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE"); 
      // Create a new one. 
      onCreate(_db); 
    } 
}