Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 33

0
votes
answers
19 views
+10

Java的sqlite表創建,但沒有顯示在sqlite工作室

0

我有一個問題,試圖創建一個sqlite數據庫中創建一個名爲ticketDB,在我的程序中我想創建一個表在該數據庫這就是代碼的樣子。Java的sqlite表創建,但沒有顯示在sqlite工作室

try{ 

    Connection c = dbConnection.getConnection(); 
    Statement stmt = c.createStatement(); 

    String sql = "CREATE TABLE IF NOT EXISTS notes" + 
          "(ID INT PRIMARY KEY  NOT NULL," + 
          " NAME   TEXT NOT NULL, " + 
          " AGE   INT  NOT NULL, " + 
          " ADDRESS  CHAR(50), " + 
          " SALARY   REAL)"; 
    stmt.executeUpdate(sql); 
    stmt.close(); 
    c.close(); 

    }catch(Exception e2) {System.out.print(e2);} 

dbConnection是一個將連接到我的數據庫的類。當我運行代碼時,它顯示它連接到數據庫,但不顯示任何錯誤,所以即時通訊假設數據庫正在創建,但它不顯示在sqlite工作室。請幫助我一直在研究這個問題,但沒有結果。

+0

也許autocommit被禁用?嘗試添加'c.commit()'。 – Oleg

+0

你確定你已經連接到正確的文件嗎? –

+0

@CL。是的,我確定我連接到正確的文件。 – Noobgrammer

沙发
0
0
"jdbc:sqlite:ticketDB.sqlite" 

沒有路徑。您正在某個隨機目錄中創建一個新的數據庫文件。

+0

這不是問題,即使使用這個或實際上正確的路徑給我同樣的結果。 – Noobgrammer

0
votes
answers
14 views
+10

SQLite UPDATE命令不更新數據庫

-1

我想在用戶離開視圖後保存用戶的ScrollView位置。SQLite UPDATE命令不更新數據庫

我這樣做是通過嘗試捕獲getScrollY在之內的位置並將其保存到數據庫中,然後在用戶返回時檢索它。

我可以成功地添加和檢索位置(Log.i("scrolly", Integer.toString(scrollY))按預期返回),但ScrollView不會跳到正確的位置。

StoryBodyActivity的部分:

public class StoryBodyActivity extends AppCompatActivity { 

    private TextView storyBodyTextView; 
    private ScrollView storyBodyScrollView; 
    public int storyID; 
    Parcelable state; 
    int scrollY; 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_story_body, menu); 
     return true; 
    } 

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

     Bundle extras = getIntent().getExtras(); 

     String story = extras.getString("story"); 
     storyID = extras.getInt("story_id"); 
     Log.i("stories", Integer.toString(storyID)); 

     storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view); 
     storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view); 

     DatabaseHelper db = new DatabaseHelper(this); 
     scrollY = db.getScrollPosition(storyID); 
     Log.i("scrolly", Integer.toString(scrollY)); 

     storyBodyScrollView.scrollTo(0, scrollY); 

     String storyBody = db.getStoryBody(storyID); 

     storyBodyTextView.setText(Html.fromHtml(storyBody)); 

     if(state != null) { 
      Log.d("pause", "trying to restore textview state.."); 
      storyBodyTextView.onRestoreInstanceState(state); 
     } 

     int scroll = storyBodyScrollView.getScrollY(); 
     Log.i("scroll", Integer.toString(scroll)); 

    } 

    @Override 
    public void onPause() { 

     scrollY = storyBodyScrollView.getScrollY(); 
     Log.i("scroll", Integer.toString(scrollY)); 
     Log.i("insert", Integer.toString(storyID)); 
     DatabaseHelper db = new DatabaseHelper(this); 
     db.setScrollPosition(scrollY, storyID); 
     super.onPause(); 
    } 

} 

我DatabaseHelper的部分:

public class DatabaseHelper extends SQLiteAssetHelper { 

    private static final int DATABASE_VERSION = 1; 

    private static final String DATABASE_NAME = "database9.db"; 
    private static final String BOOKS = "books"; 
    private static final String AUTHORS = "authors"; 

    public DatabaseHelper (Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     setForcedUpgrade(); 
    } 

    public int setScrollPosition(int scrollY, int storyID) { 

     String insertQuery = "UPDATE " + BOOKS + " SET scroll_position = '" + scrollY + "' WHERE id = '" + storyID + "'"; 
     Log.i("insert", insertQuery); 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.execSQL(insertQuery); 

     return 0; 

    } 

    public int getScrollPosition(int storyID) { 

     int scrollPosition = 0; 

     String selectQuery = "SELECT scroll_position FROM " + BOOKS + " WHERE id = '" + storyID + "'"; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       scrollPosition = cursor.getInt(0); 
      } while (cursor.moveToNext()); 
     } 

     return scrollPosition; 

     } 
} 

UPDATE:

我的架構:

CREATE TABLE "books" (
`id` INTEGER NOT NULL, 
`title` TEXT, 
`author_id` INTEGER, 
`collection` TEXT, 
`body` TEXT, 
`scroll_position` INTEGER, 
PRIMARY KEY(`id`)) 
+0

那麼,我以前的評論回答你的問題。 –

沙发
0
0

在您的INSERT命令中,您傳遞的是字符串作爲id,而它期望整數

String insertQuery = "UPDATE " + BOOKS + " SET scroll_position = '" + scrollY + "' WHERE id = '" + storyID + "'"; 

你看? storyID作爲字符串傳遞("' WHERE id = '" + storyID + "'")!
單引號將該id標記爲字符串。

如果您創建一個整數列,它將永遠不會匹配一個字符串。

CREATE TABLE "books" (
`id` INTEGER NOT NULL, 
`title` TEXT, 
`author_id` INTEGER, 
`collection` TEXT, 
`body` TEXT, 
`scroll_position` INTEGER, 
PRIMARY KEY(`id`)) 

id字段被創建爲一個整數(這很好)。
但是你不能在你的命令中傳遞一個字符串(在你的查詢中)。

編輯

您還傳遞scroll_position領域。
這是一個整數。 而這也是行不通的。

+0

謝謝 - 我刪除了單引號,但我遇到同樣的問題 – Sebastian

+0

因此,沒有與傳入的ID匹配。確保傳入的ID存在於表中。請注意,ListView選擇的索引不一定匹配您的表格行ID。 –

+0

雖然我的代碼成功記錄了'scrollY'的輸出,但是當我在數據庫瀏覽器中查看錶時,沒有'scroll_position'的值。 – Sebastian

0
votes
answers
23 views
+10

在數據庫中計數教師

1

我認爲我有正確的想法來解決這個功能,但我不知道爲什麼當我嘗試測試它時出現此錯誤。任何人都可以幫我解決這個問題嗎?在數據庫中計數教師

cur.execute(Q) sqlite3.OperationalError:鄰近 「具有」:語法錯誤

課程表:ID,場,章節,名稱 位置表:ID,

所需的輸出:

>>> courses_how_many_instructors(db) 
[('HLTC16H3F', 2), ('MATA29H3F', 2), ('MATA32H3F', 3), ('MATA67H3F', 2),  
('MGAB01H3F', 3), ('MGAB03H3F', 2), ('MGAD65H3F', 2), ('BIOA01H3F', 3),  
('POLB80H3F', 2), ('STAB22H3F', 2), ('VPMA93H3F', 2), ('CHMA10H3F', 2),  
('CHMB16H3F', 2), ('CSCA08H3F', 2), ('CSCA67H3F', 2)] 

def courses_how_many_instructors(db): 
'''Return the course number and the number of instructors for courses with 
more than one instructor. Note that this means the ID must be 
the same for each instructor.''' 
query = '''SELECT Course, Name FROM Courses WHERE NAME>1 GROUP BY HAVING COUNT(Name)''' 
return run_query(db, query) 
+0

你能分享你的表的定義嗎? – Mureinik

+0

檢查我的編輯。它具有按特定順序列出的表格 – deezy

沙发
0
0

你需要將你的結果由course柱:

SELECT course, COUNT(DISTINCT name) AS num_instructors 
FROM  courses 
GROUP BY name 
HAVING COUNT(DISTINCT name) > 1 
+0

什麼是num_instructors? – deezy

+0

傳達第二列含義的別名 – Mureinik

+0

它應該做什麼? – deezy

0
votes
answers
27 views
+10

SQLite的列錯誤:表XXX沒有名爲YYY

-1

我看着下面,在其他列,並發現匹配我的問題(據我可以告訴)什麼:SQLite的列錯誤:表XXX沒有名爲YYY

android.database.sqlite.SQLiteException: table X has no column named Y: , while compiling: INSERT INTO

Android : Table has no column named "variable name" MySql Database error

Error compiling insert into: No column named ID

Android SQLite issue - table ... has no column named

https://sqlite.org/foreignkeys.html

我收到以下錯誤的SQLite:

SQLiteDatabase: Error inserting zipCode=23456 address2= city=state address1=123 petName=qwerty phoneNumber=null vetName=zaw emailAddress= 
              android.database.sqlite.SQLiteException: table vets has no column named petName (code 1): , while compiling: INSERT INTO vets (zipCode,address2,city,address1,petName,phoneNumber,vetName,emailAddress) VALUES (?,?,?,?,?,?,?,?) 

我有一種感覺,它與在VetTable外鍵做的,但我的研究還沒有與瞭解發生了什麼事情幫助我。

VetTable定義如下:

public class VetTable { 
    public static final String TABLE_VETS = "vets"; 
    public static final String VET_ID = "vetId"; 
    public static final String PET_ID = "petId"; 
    public static final String VET_NAME = "vetName"; 
    public static final String ADDRESS1 = "address1"; 
    public static final String ADDRESS2 = "address2"; 
    public static final String CITY = "city"; 
    public static final String STATE = "state"; 
    public static final String ZIP_CODE = "zipCode"; 
    public static final String PHONE_NUMBER = "phoneNumber"; 
    public static final String EMAIL_ADDRESS = "emailAddress"; 

public static final String SQL_CREATE = 
     "CREATE TABLE " + TABLE_VETS + "(" + 
       VET_ID + " INTEGER PRIMARY KEY UNIQUE, " + 
       PET_ID + " INTEGER, " + 
       VET_NAME + " TEXT, " + 
       ADDRESS1 + " TEXT, " + 
       ADDRESS2 + " TEXT, " + 
       CITY + " TEXT, " + 
       STATE + " TEXT, " + 
       ZIP_CODE + " TEXT, " + 
       PHONE_NUMBER + " TEXT, " + 
       EMAIL_ADDRESS + " TEXT, " + 
       "FOREIGN KEY(" + PET_ID + ") " + 
       "REFERENCES pets(petId));"; 

    public static final String SQL_DELETE = 
      "DROP TABLE" + TABLE_VETS; 
} 

從DBHelper代碼相關的代碼如下:

public void addVetInfo(String name, String address1, String address2, String city, String state, String zip, String phone, String email){ 
    try { 
     db = this.getWritableDatabase(); 
     values.put(VET_NAME, name); 
     values.put(ADDRESS1, address1); 
     values.put(ADDRESS2, address2); 
     values.put(CITY, city); 
     values.put(CITY, state); 
     values.put(ZIP_CODE, zip); 
     values.put(PHONE_NUMBER, phone); 
     values.put(EMAIL_ADDRESS, email); 
     db.insert(TABLE_VETS, null, values); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 
} 

如可以看到的petName不的一部分也不曾經被包括在VetTable ,也不是addVetInfo中參數列表的一部分。那麼,SQLite做的是什麼讓它認爲petName應該是VetTable中的一個列?

+0

有兩個'put(CITY')調用,無論如何,顯示的代碼並不是實際得到執行的代碼 –

+0

CL,你是什麼意思?我沒有發佈什麼代碼? – Jeff

+0

CL,感謝您發現兩個「CITY」電話! – Jeff

沙发
0
0

對於其他人誰是有這個SQLite的錯誤問題,看來,它在我的情況下有重複的是由於列的名稱由CL指出我的帖子。當我糾正並重新編碼時,它工作正常,沒有錯誤。

因此,請確保您的列名稱對於您的插入語句是正確的。

板凳
0
-1

看起來像你的價值觀變量已經有對象內部的價值,看看這個:

public void addVetInfo(String name, String address1, String address2, String city, String state, String zip, String phone, String email){ 
    try { 
     db = this.getWritableDatabase(); 
     //INITIALIZE YOUR VARIABLE VALUES HERE 
     ContentValues values = new ContentValues(); 

    //if(name == "Enter vet name") name = null; 
    values.put(VET_NAME, name); 
    //if(address1 == "Enter address 1" || address1 == " ") address1 = null; 
    values.put(ADDRESS1, address1); 
    //if(address2 == "Enter address 2") address2 = null; 
    values.put(ADDRESS2, address2); 
    //if(city == "Enter city") city = null; 
    values.put(CITY, city); 
    //if(state == "Enter state") state = null; 
    values.put(CITY, state); 
    //if(zip == "Enter zip") zip = null; 
    values.put(ZIP_CODE, zip); 
    //if(phone == "Enter phone number") phone = null; 
    values.put(PHONE_NUMBER, phone); 
    //if(email == "Enter email address") email = null; 
    values.put(EMAIL_ADDRESS, email); 
    db.insert(TABLE_VETS, null, values); 
} catch (SQLException e) { 
    e.printStackTrace(); 
} 
} 
+0

我發現錯誤是由於CL的評論指出我有重複的「CITY」引用導致的。我無法想象爲什麼SQLite會說它與「petName」有什麼關係。 – Jeff

0
votes
answers
18 views
+10

構建SQLite數據庫以分離可讀/寫數據

1

我正在編寫一個應用程序,允許用戶閱讀存儲在SQLite數據庫中的短篇小說。構建SQLite數據庫以分離可讀/寫數據

到目前爲止這麼好。

但是現在我想添加一些涉及寫入數據庫的功能(保存ScrollView的Y位置,以便用戶可以選擇它們離開的位置,爲書籤添加故事等)。

我應該將這些值添加到books表,或者我應該創建一個單獨的表user_settings的列像id(INT),story_id(INT),y_position(INT),bookmarked(布爾)?

注意:我也在考慮未來將故事存儲在非本地數據庫中的可能性。

我的另一個問題是:我是否需要將數據庫移動到某個地方纔能寫入它?我使用的SQLiteAssetHelper和數據庫目前在/assets/databases/database.db。我聽到一些關於/data/data/mypackage文件夾的討論,但我無法在我的項目中看到它。

我的數據庫設置爲當前如下:

authors 
    id 
    name 
    name_alphanumeric 

books 
    id 
    title 
    author_id 
    collection 
    body 

如果它是有用的,這是我DatabaseHelper至今:

public class DatabaseHelper extends SQLiteAssetHelper { 

    private static final int DATABASE_VERSION = 1; 

    private static final String DATABASE_NAME = "database9.db"; 
    private static final String BOOKS = "books"; 
    private static final String AUTHORS = "authors"; 

    public DatabaseHelper (Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     // setForcedUpgrade(); 
    } 

    // Getting all books 
    public ArrayList<Author> getAllAuthors() { 

     ArrayList<Author> authorList = new ArrayList<>(); 

     // Select all query 
     String selectQuery = "SELECT id, name FROM " + AUTHORS + " ORDER BY name_alphabetic"; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       // create new author object 
       Author author = new Author(); 
       // set ID and name of author object 
       author.setID(Integer.parseInt(cursor.getString(0))); 
       author.setName(cursor.getString(1)); 
       // pass author object to authorList array 
       authorList.add(author); 
      } while (cursor.moveToNext()); 
     } 

     // return author list 
     return authorList; 
    } 


    // Getting all stories 
    public List<Book> getAllStories(int authorID) { 

     List<Book> storyList = new ArrayList<>(); 

     // Select all query 
     String selectQuery = "SELECT id, title FROM " + BOOKS + " WHERE author_id = " + authorID; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       Book book = new Book(); 
       book.setStoryID(Integer.parseInt(cursor.getString(0))); 
       book.setTitle(cursor.getString(1)); 
       storyList.add(book); 
      } while (cursor.moveToNext()); 
     } 

     // return contact list 
     return storyList; 
    } 

    // Get all collections 
    public List<Book> getAllCollections(int authorID) { 

     List<Book> collectionsList = new ArrayList<>(); 

     // Select all query 
     String selectQuery = "SELECT DISTINCT collection FROM " + BOOKS + " WHERE author_id = " + authorID; 
     Log.i("stories", selectQuery); 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 

     if (cursor.moveToFirst()) { 
      do { 
       Book book = new Book(); 
       book.setCollection(cursor.getString(0)); 
       // Log.i("stories", cursor.getString(0)); 
       collectionsList.add(book); 
      } while (cursor.moveToNext()); 
     } 

     return collectionsList; 
     // not sure how to log collectionsList here 
    } 

    // Get story 

    public String getStoryBody(int storyID) { 

     // Log.i("stories", Integer.toString(storyID)); 

     String storyBody = ""; 
     // String storyBody(); 

     // Select all query 
     String selectQuery = "SELECT body FROM " + BOOKS + " WHERE id = " + storyID; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       storyBody = cursor.getString(0); 
      } while (cursor.moveToNext()); 
     } 

     return storyBody; 
    } 

    public int setScrollPosition(int scrollY, int storyID) { 

     String insertQuery = "UPDATE " + BOOKS + " SET scroll_position = " + scrollY + " WHERE id = " + storyID; 
     Log.i("insert", insertQuery); 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.execSQL(insertQuery); 

     return 0; 

    } 

    public int getScrollPosition(int storyID) { 

     int scrollPosition = 0; 

     String selectQuery = "SELECT scroll_position FROM " + BOOKS + " WHERE id = " + storyID; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       scrollPosition = cursor.getInt(0); 
      } while (cursor.moveToNext()); 
     } 

     return scrollPosition; 

    } 

} 
沙发
0
0

但現在我想補充一點,涉及寫入功能數據庫 (保存ScrollView的Y位置,以便用戶可以從 中刪除,爲書籤添加故事等)。

我應該將這些值添加到books表,或者我應該創建一個像ID(int)的列 單獨的表user_settings,story_id (INT),y_position(INT),書籤(布爾)?

我想你已經明確表示,他們是USER值,因此它很可能是一個單獨的用戶表將是更好的更易於管理的解決方案。

我的另一個問題是:我需要將數據庫移動到 能寫入它嗎?我正在使用SQLiteAssetHelper,目前數據庫爲 ,位於/assets/databases/database.db。我聽到一些關於 /data/data/mypackage文件夾的討論,但我在我的項目中看不到它。

在所有likeliehood數據庫已被複制從資產文件夾到data/data/yourpackage/databases/dbfilenameSQLiteAssetHelper據我所知這主要就是它的功能。不過,我從來沒有使用過。)這樣的文件夾訪問有限(通常只有應用程序(紮根設備是一個例外)),所以很可能是爲什麼你看不到它。

因此,寫入/更新數據庫的權限方式可能沒有任何要求。

0
votes
answers
21 views
+10

每個線程一個SQLiteConnection?

6

我使用的是來自system.data.sqlite.org的SQLite每個線程一個SQLiteConnection?

我們需要從多個線程(出於各種原因)訪問數據庫。我讀了很多關於sqlite線程安全功能(默認同步訪問模式對我來說很好)。

我不知道是否可以簡單地打開每個線程的連接。是這樣的可能嗎?我真的不關心比賽條件(請求尚未插入的東西)。我只感興趣的是可以使用每個線程一個對象SQLiteConnection來訪問數據。

沙发
0
3

是的。事實上,這是正確的方式,因爲SQLite不是線程安全的(默認情況下,您可以使用某些選項進行線程安全編譯)。而只是爲了確保它的工作原理:在一些小的網站正在使用SQLite的,所以多線程有:)

這裏的更多信息:http://www.sqlite.org/faq.html#q6

板凳
0
4

由於您使用每個線程一個單獨的連接,你應該罰款。

docs

注意SQLiteConnection實例不保證線程安全 。您應該同時避免在幾個 線程中使用相同的 SQLiteConnection。建議每個線程打開一個新的連接 ,並在工作完成時關閉它。

0
votes
answers
20 views
+10

如何讓光標從SQLite數據庫中讀取下一行?

0

我想從我的數據庫從某些領域的報告到PDF。 pdf正在完美生成,但它只是從數據庫中讀取第一個條目而不是所有條目。如何讓光標從SQLite數據庫中讀取下一行?

這是我對PDF的代碼:

public void exportDataBaseIntoPDF() { 
    Document doc = new Document(PageSize.A4); 
    try { 
     path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MSS Jobsheets"; 
     date = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date()); 

     File dir = new File(path); 
     if (!dir.exists()) 
      dir.mkdirs(); 

     Log.d("PDFCreator", "PDF Path: " + path); 

     filePDF = new File(dir, "Report" + "(" + date + ")" + ".pdf"); 
     FileOutputStream fOut = null; 
     try { 
      fOut = new FileOutputStream(filePDF); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
     PdfWriter.getInstance(doc, fOut); 
     doc.open(); 

     DBHelper db = new DBHelper(this); 
     Cursor cursor = db.getDataItem(); 
     int count = cursor.getCount(); 

     cursor.moveToFirst(); 

     for (int j = 0; j < count; j++) { 
      PdfPTable table = new PdfPTable(2); 
      table.addCell(cursor.getString(cursor.getColumnIndex("name"))); 
      table.addCell(cursor.getString(cursor.getColumnIndex("gender"))); 


      cursor.moveToNext(); 

      doc.add(table); 
      doc.close(); 
     } 

    } catch (DocumentException e) { 
     e.printStackTrace(); 
    } 
} 

這是從我的DBHelper類拉低數據:

public Cursor getDataItem() { 
    SQLiteDatabase db = this.getReadableDatabase(); 
    String q = "SELECT * FROM " + PERSON_TABLE_NAME; 
    Cursor mCursor = db.rawQuery(q, null); 

    return mCursor; 
} 
} 

但就像我說的,它只是從數據庫讀取第一行並添加數據但不移動到數據庫中的下一行以將數據添加到PDF中。

有人可以幫我解決這個問題嗎? 在此先感謝!

+0

外面你有數據庫中的多行? –

+0

是的,我確實有。基本上它是一個用戶填寫的表單,然後在一天結束時用戶可以從某些領域獲取報告,然後發送電子郵件。 – Newbie

+0

嘗試關閉doc for side循環。寫這行doc.close();外側爲循環 – Munir

沙发
0
1

實際問題與遊標無關,遊標讀取下一行但您在第一次寫入數據後關閉文檔。嘗試關閉for循環之外的文檔對象。

,就把這行到for loop

doc.close(); 
+0

謝謝!它的工作現在。我無法相信我是如何錯過的!我一直在努力奮鬥這個年齡! – Newbie

+0

@Newbie高興地幫助你..! – Munir

0
votes
answers
23 views
+10

如何在添加數據後刷新片段中的列表視圖?

0

我將數據從選項卡片段插入到sqlite數據庫中。我的問題是一旦數據被插入或從列表中刪除,更新後的列表僅在應用程序重新啓動後纔會顯示。新數據添加到列表後,如何使片段刷新?如何在添加數據後刷新片段中的列表視圖?

任何幫助,這將不勝感激。

public Tab1() { 
    // Required empty public constructor 
} 



// TODO: Rename and change types and number of parameters 
public static Tab1 newInstance(String param1, String param2) { 
    Tab1 fragment = new Tab1(); 
    Bundle args = new Bundle(); 
    args.putString(ARG_PARAM1, param1); 
    args.putString(ARG_PARAM2, param2); 
    fragment.setArguments(args); 

     return fragment; 
} 



@Override 
public void onCreate(Bundle savedInstanceState) { 


    super.onCreate(savedInstanceState); 

    if (getArguments() != null) { 
     mParam1 = getArguments().getString(ARG_PARAM1); 
     mParam2 = getArguments().getString(ARG_PARAM2); 

    } 

} 


//load tasks into the list 
private void loadTaskList() { 

    ArrayList<String> taskList = dbHelper.getTaskList(); 
    if (mAdapter == null) { 
     mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.task_title, taskList); 
     lstTask.setAdapter(mAdapter); 

    } else { 
     mAdapter.clear(); 
     mAdapter.addAll(taskList); 
     mAdapter.notifyDataSetChanged(); 
    } 



} 


    @Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View frag1 = inflater.inflate(R.layout.fragment_tab1, container, false); 

    dbHelper = new DbHelper(getActivity()); 
    lstTask = (ListView)frag1.findViewById(R.id.lstTask); 

    loadTaskList(); 

     return frag1; 

} 
// TODO: Rename method, update argument and hook method into UI event 
public void onButtonPressed(Uri uri) { 
    if (mListener != null) { 
     mListener.onFragmentInteraction(uri); 
    } 
} 

}

沙发
0
0

你每次當你切換標籤的時間刷新選項卡。爲此,您必須創建一個Interface,如下所示。

public interface MainHomeFragmentInterface { 
    void fragmentBecameVisible(); 
} 

調用此InterfaceviewPager

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
      @Override 
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 

      } 

      @Override 
      public void onPageSelected(int position) { 
       MainHomeFragmentInterface fragment = (MainHomeFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, position); 
       if (fragment != null) { 
        fragment.fragmentBecameVisible(); 
       } 
      } 

      @Override 
      public void onPageScrollStateChanged(int state) { 

      } 
     }); 

,並在你的每個tabfragment實現這個Interface

板凳
0
0

爲此,你需要添加下 資源的XML文件> XML> pref_data_sync.xml 其中將包含

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 

    <ListPreference 
     android:defaultValue="180" 
     android:entries="@array/pref_sync_frequency_titles" 
     android:entryValues="@array/pref_sync_frequency_values" 
     android:key="sync_frequency" 
     android:negativeButtonText="@null" 
     android:positiveButtonText="@null" 
     android:title="@string/pref_title_sync_frequency" /> 

    <Preference android:title="@string/pref_title_system_sync_settings"> 
     <intent android:action="android.settings.SYNC_SETTINGS" /> 
    </Preference> 

</PreferenceScreen> 

其中@array文件都包含在string.xml爲 -

<string-array name="pref_sync_frequency_titles"> 
     <item>15 minutes</item> 
     <item>30 minutes</item> 
     <item>1 hour</item> 
     <item>3 hours</item> 
     <item>6 hours</item> 
     <item>Never</item> 
    </string-array> 

    <string-array name="pref_sync_frequency_values"> 
     <item>15</item> 
     <item>30</item> 
     <item>60</item> 
     <item>180</item> 
     <item>360</item> 
     <item>-1</item> 
    </string-array> 

    <string name="pref_title_sync_frequency">Sync frequency</string> 

    <string name="pref_title_system_sync_settings">System sync settings</string> 

我希望這可以幫助你! :)

地板
0
1

您可以使用本地廣播來通知顯示需要刷新的數據的片段。

當您更改數據庫中的數據時,您應該使用LocalBroadcastManager發送廣播,並在顯示數據的片段內部設置BroadcastReceiver

請參閱How to use LocalBroadcastManager?

0
votes
answers
32 views
+10

Python:從每個打開的Google Chrome標籤獲取所有Url

4

我需要從python 3中所有打開的Chrome瀏覽器標籤中獲取所有的URL,而不需要用戶干預。林在Windows上使用Microsoft Visual Studio Python3 10Python:從每個打開的Google Chrome標籤獲取所有Url

我用盡:

直接與開放(路徑當前選項卡)打開它 - 不工作,因爲我沒有permission-我認爲它鎖定,因爲鉻activly寫入它。

Current_Tabs_Source = open(r"C:UsersBeniAppDataLocalGoogleChromeUser 
DataDefaultCurrent Tabs", "r") 
Current_Tabs_Raw = Current_Tabs_Source.read() 
print(Current_Tabs_Raw) #just for checking 

PermissionError:[錯誤13]許可被拒絕通過sglite3

開幕 - 行不通的,因爲其鎖定。我無法在任何地方找到密碼。我試圖打開URL的歷史記錄,但它不起作用。

import sqlite3 
from os import path 

data_path = path.expanduser('~') + r"AppDataLocalGoogleChromeUser 
DataDefault" 
files = listdir(data_path) 
history_db = path.join(data_path, 'history') 

c = sqlite3.connect(history_db) 
cursor = c.cursor() 
select_statement = "SELECT urls.url, urls.visit_count FROM urls, visits 
WHERE urls.id = visits.url;" 
cursor.execute(select_statement) 

results = cursor.fetchall() 

print(results) #just for checking 

sqlite3.OperationalError:數據庫被鎖定

使用硒和第三方Chrome擴展到所有的URL複製到剪貼板 - 不工作,因爲這些擴展僅在活動窗口硒工作。所以Windows中的標籤,我想不要被複制。

我曾考慮過將Chrome擴展每30秒複製一份臨時文件。但是我只知道最小的Javascript,所以這件事讓我很生氣。

那麼有沒有人知道在Python中做到這一點的方法?任何其他解決方案,不勝感激。

+0

我想不出任何可能的方式這可以在Python來完成。我甚至不知道你如何試圖這樣使用SQLite,數據庫語言...您最好的選擇確實是更像JavaScript的前端。 – Mangohero1

+1

這將是有益的,如果你可以分享你一直工作的代碼,直到現在,所以我們可以更好地瞭解你的方法 –

+1

@HamSam我上傳了一些代碼,所以你可以看到即時嘗試 –

沙发
0
0

如果要訪問數據庫,應關閉所有瀏覽器。

Source

0
votes
answers
20 views
+10

如何在一個片段內的recylerview列表中顯示SQLite數據庫數據?

0

我是一個業餘的android開發人員,我想從數據庫中獲取用戶輸入的項目,然後將其顯示在一個片段中的recyclerview列表(不是ListView)中。如何在一個片段內的recylerview列表中顯示SQLite數據庫數據?

到目前爲止,我已經創建了將數據保存到其中的SQLite數據庫,我只想知道我可以在recyclerview中顯示所有這些信息。下面顯示的Java代碼顯示了我想要做的,但是在ListView中而不是在回收器視圖中。

DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper { 
    private static final String TAG = "DatabaseHelper"; 

    public static final String DATABASE_NAME = "budget10.db"; 
    public static final String TABLE_NAME = "expense_table"; 
    public static final String TABLE_NAME2 = "income_table"; 
    public static final String COL_1 = "_id"; 
    public static final String COL_2 = "_id"; 
    public static final String EXPENSE_AMOUNT = "EXPENSE_AMOUNT"; 
    public static final String EXPENSE_DATE = "DATE"; 
    public static final String EXPENSE_NOTES = "NOTES"; 
    public static final String INCOME_AMOUNT = "INCOME_AMOUNT"; 
    public static final String INCOME_DATE = "DATE"; 
    public static final String INCOME_NOTES = "NOTES"; 
    public static final String INCOME_CATEGORY = "INCOME_CATEGORY"; 
    public static final String EXPENSE_CATEGORY = "EXPENSE_CATEGORY"; 
    public static final String EXPENSE_ACCOUNT = "EXPENSE_ACCOUNT"; 
    public static final String INCOME_ACCOUNT = "INCOME_ACCOUNT"; 

    public DatabaseHelper(Context context) { 
     super(context, DATABASE_NAME, null, 3); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
     db.execSQL("create table " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, EXPENSE_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, EXPENSE_CATEGORY TEXT, EXPENSE_ACCOUNT TEXT)"); 
     db.execSQL("create table " + TABLE_NAME2 + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,INCOME_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, INCOME_CATEGORY TEXT, INCOME_ACCOUNT TEXT)"); 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2); 
     onCreate(db); 
    } 

    public boolean insertexpenseData(Double amount_expense, String date_expense, String notes_expense, String category_expense, String expense_account) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues contentValues = new ContentValues(); 
     contentValues.put(EXPENSE_AMOUNT, amount_expense); 
     contentValues.put(EXPENSE_DATE, date_expense); 
     contentValues.put(EXPENSE_NOTES, notes_expense); 
     contentValues.put(EXPENSE_CATEGORY, category_expense); 
     contentValues.put(EXPENSE_ACCOUNT, expense_account); 
     long result = db.insert(TABLE_NAME, null, contentValues); 
     if (result == -1) 
      return false; 
     else 
      return true; 
    } 

    public boolean insertincomeData(Double amount_income, String date_income, String notes_income, String category_income, String income_account) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues contentValues = new ContentValues(); 
     contentValues.put(INCOME_AMOUNT, amount_income); 
     contentValues.put(INCOME_DATE, date_income); 
     contentValues.put(INCOME_NOTES, notes_income); 
     contentValues.put(INCOME_CATEGORY, category_income); 
     contentValues.put(INCOME_ACCOUNT, income_account); 
     long result = db.insert(TABLE_NAME2, null, contentValues); 
     if (result == -1) 
      return false; 
     else 
      return true; 
    } 

    public Cursor getexpenseData() { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor res = db.rawQuery("select * from " + TABLE_NAME, null); 
     return res; 
    } 

    public Cursor getincomeData() { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor res = db.rawQuery("select * from " + TABLE_NAME2, null); 
     return res; 
    } 



    public boolean updateexpenseData(String id, String amount, String date, String notes, String catagory_income) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues contentValues = new ContentValues(); 
     contentValues.put(COL_1, id); 
     contentValues.put(EXPENSE_AMOUNT, amount); 
     contentValues.put(EXPENSE_DATE, date); 
     contentValues.put(EXPENSE_NOTES, notes); 
     contentValues.put(EXPENSE_CATEGORY, catagory_income); 
     db.update(TABLE_NAME, contentValues, "_id = ?", new String[]{id}); 
     return true; 
    } 

    public boolean updateincomeData(String id, String amount, String date, String notes, String catagory_income) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues contentValues = new ContentValues(); 
     contentValues.put(COL_2, id); 
     contentValues.put(INCOME_AMOUNT, amount); 
     contentValues.put(INCOME_DATE, date); 
     contentValues.put(INCOME_NOTES, notes); 
     contentValues.put(INCOME_CATEGORY, catagory_income); 
     db.update(TABLE_NAME2, contentValues, "_id = ?", new String[]{id}); 
     return true; 
    } 

    public Integer deleteexpenseData(String _id) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     return db.delete(TABLE_NAME, "_id = ?", new String[]{_id}); 
    } 

    public Integer deleteincomeData(String _id) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     return db.delete(TABLE_NAME2, "_id = ?", new String[]{_id}); 
    } 

    public double getNetBudget() { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) - (SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table) FROM income_table"; 
     Cursor cursor = db.rawQuery(selectQuery, null); 
     double netBudget = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned 
     if (cursor.moveToFirst()) { 
      netBudget = cursor.getDouble(0); 
     } 
     cursor.close(); 
     return netBudget; 
    } 

    public double getTotalExpense() { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     String selectQuery = "SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table"; 
     Cursor cursor = db.rawQuery(selectQuery, null); 
     double netExpense = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned 
     if (cursor.moveToFirst()) { 
      netExpense = cursor.getDouble(0); 
     } 
     cursor.close(); 
     return netExpense; 
    } 

    public double getTotalIncome() { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) FROM income_table"; 
     Cursor cursor = db.rawQuery(selectQuery, null); 
     double netIncome = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned 
     if (cursor.moveToFirst()) { 
      netIncome = cursor.getDouble(0); 
     } 
     cursor.close(); 
     return netIncome; 
    } 

    public void deleteAllIncome() { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.delete(TABLE_NAME2, null, null); 
     db.execSQL("delete from " + TABLE_NAME2); 
     db.close(); 
    } 

    public void deleteAllExpense() { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.delete(TABLE_NAME, null, null); 
     db.execSQL("delete from " + TABLE_NAME); 
     db.close(); 
    } 

} 

片段的Lis??tView,我想變成一個recyclerview

public class tab2income extends Fragment { 

    private static final String TAG = "tab2income"; 
    DatabaseHelper mDatabaseHelper; 
    private ListView mListView; 
    View rootView; 
    Cursor incomedata; 
    SimpleCursorAdapter sca; 
    DecimalFormat formatter = new DecimalFormat("0.00"); 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     rootView = inflater.inflate(R.layout.tab2income, container, false); 
     return rootView; 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     mListView = (ListView) rootView.findViewById(R.id.listViewincome); 
     mListView.setEmptyView(rootView.findViewById(R.id.empty)); 
     mDatabaseHelper = new DatabaseHelper(getActivity()); 

     populateListView(); 
    } 

    private void populateListView() { 
     Log.d(TAG, "populateListView: Displaying data in the ListView."); 
     incomedata = mDatabaseHelper.getincomeData(); 
     sca = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, incomedata, new String[]{DatabaseHelper.INCOME_AMOUNT}, new int[]{android.R.id.text1}, 0); 
     mListView.setAdapter(sca); 

     mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
       int csrpos = incomedata.getPosition(); 
       incomedata.moveToPosition(i); 
       displayNoteDate(
         incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)), 
         incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)), 
         incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)), 
         l, 
         incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT))); 
       incomedata.moveToPosition(csrpos); 
      } 
     }); 
    } 


    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     incomedata.close(); 
    } 

    public void displayNoteDate(String noteContent, String dateValue,String category, final long noteID,String account) { 
     MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity()) 
       .title("Income Information") 
       .content("Date: "+ dateValue+ 
         "
Category: "+category+ 
         "
Account: "+account+ 
         "
Note: "+noteContent) 
       .positiveText("close") 
       .negativeText("delete") 
       .onPositive(new MaterialDialog.SingleButtonCallback() { 
        @Override 
        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { 
        } 
       }) 
       .onNegative(new MaterialDialog.SingleButtonCallback() { 
        @Override 
        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { 
         mDatabaseHelper.deleteincomeData(Long.toString(noteID)); 
         incomedata = mDatabaseHelper.getincomeData(); 
         sca.swapCursor(incomedata); 
        } 
       }); 
     builder.show(); 
    } 
} 

編輯

這就是我與迄今所做代碼在Sauro的答案中v巴什和我有recyclerview在我的XML文件,並沒有任何反應的項目被點擊時:

片段

public class tab2income extends Fragment implements ItemClickListener { 

    private static final String TAG = "tab2income"; 
    DatabaseHelper mDatabaseHelper; 
    private RecyclerView mListView; 
    View rootView; 
    Cursor incomedata; 
    SimpleCursorAdapter sca; 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     rootView = inflater.inflate(R.layout.tab2income, container, false); 
     return rootView; 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     mListView = rootView.findViewById(R.id.ListViewincome); 
     RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); 
     mListView.setLayoutManager(layoutManager); 
     mDatabaseHelper = new DatabaseHelper(getActivity()); 

     populateListView(); 
    } 

    private void populateListView() { 
     Log.d(TAG, "populateListView: Displaying data in the ListView."); 
     ArrayList<String> arrayList = new ArrayList<>(); 
     MyAdapter myAdapter = new MyAdapter(arrayList); 
     mListView.setAdapter(myAdapter); 

     incomedata = mDatabaseHelper.getincomeData(); 
     if(incomedata.moveToFirst()){ 
      do { 
       arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT))); 
      } while (incomedata.moveToNext()); 
     } 
     myAdapter.notifyDataSetChanged(); 
    } 


    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     incomedata.close(); 
    } 


    @Override 
    public void onClick(View view, int i) { 
     int csrpos = incomedata.getPosition(); 
     incomedata.moveToPosition(i); 
     displayNoteDate(
       incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)), 
       incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)), 
       incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)), 
       incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT))); 
     incomedata.moveToPosition(csrpos); 
    } 

    public void displayNoteDate(String noteContent, String dateValue,String category,String account) { 
     MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity()) 
       .title("Income Information") 
       .content("Date: "+ dateValue+ 
         "
Category: "+category+ 
         "
Account: "+account+ 
         "
Note: "+noteContent) 
       .positiveText("close") 
       .negativeText("delete") 
       .onPositive(new MaterialDialog.SingleButtonCallback() { 
        @Override 
        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { 
        } 
       }) 
       .onNegative(new MaterialDialog.SingleButtonCallback() { 
        @Override 
        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { 
        } 
       }); 
     builder.show(); 
    } 

} 

適配器

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { 
    private final ArrayList<String> dataSet; 
    private ItemClickListener clickListener; 

    public MyAdapter(ArrayList<String> myDataset) { 
     dataSet = myDataset; 
    } 

    @Override 
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     //layout of the list item 
     View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false); 
     return new ViewHolder(view); 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) { 
     holder.mTextView.setText(dataSet.get(position)); 
    } 

    @Override 
    public int getItemCount() { 
     return dataSet.size(); 
    } 

    public void setClickListener(ItemClickListener itemClickListener) { 
     this.clickListener = itemClickListener; 
    } 

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { 
     final TextView mTextView; 

     ViewHolder(View v) { 
      super(v); 
      //textview for showing results 
      mTextView = v.findViewById(android.R.id.text1); 
      v.setOnClickListener(this); 
     } 

     //for click 
     @Override 
     public void onClick(View view) { 
      if (clickListener != null) clickListener.onClick(view, getAdapterPosition()); 

     } 
    } 
} 
+0

我建議您使用新的Android架構組件。這是很容易的,並且需要更少的代碼。 https://developer.android.com/topic/libraries/architecture/index.html –

沙发
0
0

對於RecyclerView你需要創建您自己的定製適配器。

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { 
    private final ArrayList<String> dataSet; 
    private ItemClickListener clickListener; 

    public MyAdapter(ArrayList<String> myDataset) { 
     dataSet = myDataset; 
    } 

    @Override 
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     //layout of the list item 
     View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false); 
     return new ViewHolder(view); 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) { 
     holder.mTextView.setText(dataSet.get(position)); 
    } 

    @Override 
    public int getItemCount() { 
     return dataSet.size(); 
    } 

    public void setClickListener(ItemClickListener itemClickListener) { 
     this.clickListener = itemClickListener; 
    } 

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { 
     final TextView mTextView; 

     ViewHolder(View v) { 
      super(v); 
      //textview for showing results 
      mTextView = v.findViewById(android.R.id.text1); 
      v.setOnClickListener(this); 
     } 

     //for click 
     @Override 
     public void onClick(View view) { 
      if (clickListener != null) clickListener.onClick(view, getAdapterPosition()); 
     } 
    } 
} 

然後,我只是重寫populateListView()方法

??

您還需要爲每個項目單擊一個接口。

public interface ItemClickListener { 
    void onClick (View view, int position); 
} 

並在你的Fragment中實現這個接口。

public class tab2income extends Fragment implements ItemClickListener{ 

    //All of your codes 

    @Override 
    public void onClick (View view, int i) { 
     int csrpos = incomedata.getPosition(); 
      incomedata.moveToPosition(i); 
      displayNoteDate(
        incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)), 
        incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)), 
        incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)), 
        l, 
        incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT))); 
      incomedata.moveToPosition(csrpos); 
    } 
} 
+0

我只是想問我該如何在片段中使用它? –

+0

怎麼樣的筆記ID,這是行不通的,而且約束佈局cardview也會引發錯誤 –

+0

此外,我嘗試修復異常,然後運行應用程序,但片段不顯示recyclerview –