2013-08-02 32 views
0

我目前有一個列表視圖是從SQL Lite數據庫中獲取其數據。我無法弄清楚如何使數據以最新的信息出現在頂部,最舊的信息出現在底部。 這是我這是顯示列表視圖主類和我將對DBAdapter從數據庫顯示列表視圖數據與最新的結果在頂部和最舊的底部

主:

package com.ArielR.Spot; 

import java.util.ArrayList; 
import java.util.Arrays; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.content.Intent; 
import android.widget.SimpleCursorAdapter; 
import android.widget.Toast; 
import android.database.Cursor; 
import android.view.MenuInflater; 
import android.view.MenuItem; 

public class main extends Activity { 
/** Called when the activity is first created. */ 

DBAdapter SpotDB; 
String Name; 
String URL; 
String Description; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Bundle extras = getIntent().getExtras(); 
    openDB(); 
    if (extras != null) { 
     Name= extras.getString("name"); 
     URL= extras.getString("url"); 
     Description= extras.getString("description"); 
     if(Name.equals("") || URL.equals("") || Description.equals("")){ 
      Toast.makeText(this, "Invalid Submission", Toast.LENGTH_LONG).show(); 
      populateListViewfromDB(); 
     } 
     else{ 

      populateListViewfromDB(); 
     } 
    } 

    } 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    closeDB(); 
} 

private void openDB() { 
    SpotDB = new DBAdapter(this); 
    SpotDB.open(); 
    addRow(); 
    populateListViewfromDB(); 
} 
private void closeDB() { 
    SpotDB.close(); 
} 

public void addRow() { 
    long newid = SpotDB.insertRow(Name, URL, Description); 
    populateListViewfromDB(); 
} 


public void AddNew() { 
    Intent intent = new Intent(); 
    intent.setClass(this, AddNewItem.class); 
    startActivity(intent); 
} 


public void populateListViewfromDB() { 
    Cursor cursor = SpotDB.getAllRows(); 

    startManagingCursor(cursor); 

    String[] FromFieldNames= new String[] 
      {DBAdapter.KEY_NAME, DBAdapter.KEY_URL, DBAdapter.KEY_DESCRIPTION}; 
    int[] ToViewIDs= new int[] 
      {R.id.Name, R.id.URL, R.id.Description}; 

    SimpleCursorAdapter myCursorAdapter = 
      new SimpleCursorAdapter(
        this, 
        R.layout.row, 
        cursor, 
        FromFieldNames, 
        ToViewIDs 
      ); 

    ListView list = (ListView) findViewById(R.id.listView); 
    list.setAdapter(myCursorAdapter); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.main, menu); 
    return super.onCreateOptionsMenu(menu); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle presses on the action bar items 
    switch (item.getItemId()) { 
     case R.id.action_search: 
      AddNew(); 
      return true; 
    } 
    return true; 
} 
} 

將對DBAdapter:

package com.ArielR.Spot; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 



public class DBAdapter { 

///////////////////////////////////////////////////////////////////// 
// Constants & Data 
///////////////////////////////////////////////////////////////////// 
// For logging: 
private static final String TAG = "DBAdapter"; 

// DB Fields 
public static final String KEY_ROWID = "_id"; 
public static final int COL_ROWID = 0; 
/* 
* CHANGE 1: 
*/ 
// TODO: Setup your fields here: 
public static final String KEY_NAME = "Name"; 
public static final String KEY_URL = "URL"; 
public static final String KEY_DESCRIPTION = "Description"; 

// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...) 
public static final int COL_NAME = 1; 
public static final int COL_URL = 2; 
public static final int COL_DESCRIPTION = 3; 


public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_URL,    KEY_DESCRIPTION}; 

// DB info: it's name, and the table we are using (just one). 
public static final String DATABASE_NAME = "SpotDb"; 
public static final String DATABASE_TABLE = "main"; 
// Track DB version if a new version of your app changes the format. 
public static final int DATABASE_VERSION = 2; 

private static final String DATABASE_CREATE_SQL = 
     "create table " + DATABASE_TABLE 
       + " (" + KEY_ROWID + " integer primary key autoincrement, " 

     /* 
     * CHANGE 2: 
     */ 
       // TODO: Place your fields here! 
       // + KEY_{...} + " {type} not null" 
       // - Key is the column name you created above. 
       // - {type} is one of: text, integer, real, blob 
       //  (http://www.sqlite.org/datatype3.html) 
       // - "not null" means it is a required field (must be given a value). 
       // NOTE: All must be comma separated (end of line!) Last one must have NO comma!! 
       + KEY_NAME + " text not null, " 
       + KEY_URL + " text not null, " 
       + KEY_DESCRIPTION + " text not null" 

       // Rest of creation: 
       + ");"; 

// Context of application who uses us. 
private final Context context; 

private DatabaseHelper myDBHelper; 
private SQLiteDatabase db; 

///////////////////////////////////////////////////////////////////// 
// Public methods: 
///////////////////////////////////////////////////////////////////// 

public DBAdapter(Context ctx) { 
    this.context = ctx; 
    myDBHelper = new DatabaseHelper(context); 
} 

// Open the database connection. 
public DBAdapter open() { 
    db = myDBHelper.getWritableDatabase(); 
    return this; 
} 

// Close the database connection. 
public void close() { 
    myDBHelper.close(); 
} 

// Add a new set of values to the database. 
public long insertRow(String name, String url, String description) { 
    /* 
    * CHANGE 3: 
    */ 
    // TODO: Update data in the row with new fields. 
    // TODO: Also change the function's arguments to be what you need! 
    // Create row's data: 
    ContentValues initialValues = new ContentValues(); 
    initialValues.put(KEY_NAME, name); 
    initialValues.put(KEY_URL, url); 
    initialValues.put(KEY_DESCRIPTION, description); 

    // Insert it into the database. 
    return db.insert(DATABASE_TABLE, null, initialValues); 
} 

// Delete a row from the database, by rowId (primary key) 
public boolean deleteRow(long rowId) { 
    String where = KEY_ROWID + "=" + rowId; 
    return db.delete(DATABASE_TABLE, where, null) != 0; 
} 

public void deleteAll() { 
    Cursor c = getAllRows(); 
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID); 
    if (c.moveToFirst()) { 
     do { 
      deleteRow(c.getLong((int) rowId)); 
     } while (c.moveToNext()); 
    } 
    c.close(); 
} 

// Return all data in the database. 
public Cursor getAllRows() { 
    String where = null; 
    Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, 
      where, null, null, null, null, null); 
    if (c != null) { 
     c.moveToFirst(); 
    } 
    return c; 
} 

// Get a specific row (by rowId) 
public Cursor getRow(long rowId) { 
    String where = KEY_ROWID + "=" + rowId; 
    Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, 
      where, null, null, null, null, null); 
    if (c != null) { 
     c.moveToFirst(); 
    } 
    return c; 
} 

// Change an existing row to be equal to new data. 
public boolean updateRow(long rowId, String name, String url, String description) { 
    String where = KEY_ROWID + "=" + rowId; 

    /* 
    * CHANGE 4: 
    */ 
    // TODO: Update data in the row with new fields. 
    // TODO: Also change the function's arguments to be what you need! 
    // Create row's data: 
    ContentValues newValues = new ContentValues(); 
    newValues.put(KEY_NAME, name); 
    newValues.put(KEY_URL, url); 
    newValues.put(KEY_DESCRIPTION, description); 

    // Insert it into the database. 
    return db.update(DATABASE_TABLE, newValues, where, null) != 0; 
} 



///////////////////////////////////////////////////////////////////// 
// Private Helper Classes: 
///////////////////////////////////////////////////////////////////// 

/** 
* Private class which handles database creation and upgrading. 
* Used to handle low-level database access. 
*/ 
private static class DatabaseHelper extends SQLiteOpenHelper 
{ 
    DatabaseHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase _db) { 
     _db.execSQL(DATABASE_CREATE_SQL); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) { 
     Log.w(TAG, "Upgrading application's database from version " + oldVersion 
       + " to " + newVersion + ", which will destroy all old data!"); 

     // Destroy old database: 
     _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 

     // Recreate new database: 
     onCreate(_db); 
    } 
} 
} 

回答

0

getAllRows()呼叫db.query()你可以給一個orderBy參數。假設KEY_ROWID反映了從最舊到最新的順序,orderBy參數可以是KEY_ROWID + " DESC"

+0

這會發生其中一個空參數還是會添加一個新參數?你能舉一個新的db.query()的例子嗎? –

+0

@ArielRakovitsky這將取代'null'參數之一。你可以查看'SQLiteDatabase.query()'的文檔來找出哪些必須被替換。 query()有多種變體,但只有一種變量具有9個參數。 –

+0

非常感謝你們!下載應用程序,它應該在大約一週內名爲Spot –

0

獲取列表或地圖您的數據庫數據,並把單子在你的ListView適配器

相關問題