从SQL数据库调用数据到ListView时出错

时间:2013-05-14 20:05:07

标签: android sqlite

我一直试图在我的项目中找到错误,但我仍然没有运气。由于我是编程新手,我无法指出这个错误。我在主项目的对话框中有一个列表视图,这里正在尝试将数据从MySQL数据库浏览器调用到列表视图。我为这段代码制作了一个新项目,因为我不想用这段代码弄乱我的主项目。

 package com.pdb.projectdb;

 import java.util.ArrayList; 

 import android.app.ListActivity;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.AdapterView.OnItemClickListener;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.Toast;

  public class Main1Activity extends ListActivity {

  private static final String DB_NAME = "yourdb.sqlite3";

  //A good practice is to define database field names as constants
  private static final String TABLE_NAME = "friends";
  private static final String FRIEND_ID = "_id";
  private static final String FRIEND_NAME = "name";

 private SQLiteDatabase database;
 private ListView listView;
 private ArrayList friends;

 @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main1);

    //Our key helper
    ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
    database = dbOpenHelper.openDataBase();
    //That’s it, the database is open!
    fillFreinds();
      setUpList();
  }

  private void setUpList() {
  //We use a standard adapter and an element layout for brevity’s sake
  setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,   
 friends));
 listView = getListView();

 //Let’s set a message shown upon tapping an item
    listView.setOnItemClickListener(new OnItemClickListener() {
 public void onItemClick(AdapterView parent, View view,
 int position,long id) {
 Toast.makeText(getApplicationContext(),
 ((TextView) view).getText() +
      " could be Softeq's friend",
      Toast.LENGTH_SHORT).show();
 }
 }
 }

 //Extracting elements from the database
  private void fillFreinds() {
 friends = new ArrayList<String>();
 Cursor friendCursor = database.query(TABLE_NAME, new String[] {FRIEND_ID,
        FRIEND_NAME}, null, null, null, null, FRIEND_NAME);
 friendCursor.moveToFirst();
 if(!friendCursor.isAfterLast()) {
  do {
 String name = friendCursor.getString(1);
 friends.add(name);
 } while (friendCursor.moveToNext());
  }
friendCursor.close();
 }
  }

XML.file

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context=".Main1Activity" >

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="114dp"
    android:src="@drawable/ic_launcher" />

   </RelativeLayout>

DBHelper

     package com.pdb.projectdb;

     import java.io.FileOutputStream;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.OutputStream;

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

     public class ExternalDbOpenHelper extends SQLiteOpenHelper {

    //Path to the device folder with databases
    public static String DB_PATH;

    //Database file name
    public static String DB_NAME;
    public SQLiteDatabase database;
     public final Context context;

    public SQLiteDatabase getDb() {
    return database;
    }

     public ExternalDbOpenHelper(Context context, String databaseName) {
     super(context, databaseName, null, 1);
     this.context = context;
     //Write a full path to the databases of your application
     String packageName = context.getPackageName();
     DB_PATH = String.format("/data/data/newDB/databases/", packageName);
     DB_NAME = databaseName;
     openDataBase();
     }

    //This piece of code will create a database if it’s not yet created
    public void createDataBase() {
    boolean dbExist = checkDataBase();
     if (!dbExist) {
     this.getReadableDatabase();
     try {
     copyDataBase();
    } catch (IOException e) {
    Log.e(this.getClass().toString(), "Copying error");
    throw new Error("Error copying database!");
     }
    } else {
      Log.i(this.getClass().toString(), "Database already exists");
    }
     }

     //Performing a database existence check
     private boolean checkDataBase() {
     SQLiteDatabase checkDb = null;
     try {
     String path = DB_PATH + DB_NAME;
     checkDb = SQLiteDatabase.openDatabase(path, null,
     SQLiteDatabase.OPEN_READONLY);
     } catch (SQLException e) {
     Log.e(this.getClass().toString(), "Error while checking db");
     }
     //Android doesn’t like resource leaks, everything should 
    // be closed
     if (checkDb != null) {
     checkDb.close();
       }
         return checkDb != null;
      }

    //Method for copying the database
    private void copyDataBase() throws IOException {
    //Open a stream for reading from our ready-made database
    //The stream source is located in the assets
    InputStream externalDbStream = context.getAssets().open(DB_NAME);

    //Path to the created empty database on your Android device
    String outFileName = DB_PATH + DB_NAME;

    //Now create a stream for writing the database byte by byte
     OutputStream localDbStream = new FileOutputStream(outFileName);

    //Copying the database
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = externalDbStream.read(buffer)) > 0) {
     localDbStream.write(buffer, 0, bytesRead);
     }
    //Don’t forget to close the streams
       localDbStream.close();
    externalDbStream.close();
     }

     public SQLiteDatabase openDataBase() throws SQLException {
     String path = DB_PATH + DB_NAME;
     if (database == null) {
     createDataBase();
     database = SQLiteDatabase.openDatabase(path, null,
     SQLiteDatabase.OPEN_READWRITE);
     }
      return database;
     }

     @Override
     public synchronized void close() {
     if (database != null) {
     database.close();
       }
     super.close();
       }
     @Override
     public void onCreate(SQLiteDatabase db) {}
     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
     }

项目视图http://img441.imageshack.us/img441/1936/projectg.jpg

P.s我的朋友告诉我不要在这里浪费问题因为你可以被禁止请告诉我,如果我没有格式化我的问题

谢谢

http://img594.imageshack.us/img594/3965/fixq.jpg

1 个答案:

答案 0 :(得分:0)

替换为此,我正确地为您格式化

import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main1Activity extends ListActivity {

    private static final String DB_NAME = "yourdb.sqlite3";

    // A good practice is to define database field names as constants
    private static final String TABLE_NAME = "friends";
    private static final String FRIEND_ID = "_id";
    private static final String FRIEND_NAME = "name";

    private SQLiteDatabase database;
    private ListView listView;
    private ArrayList friends;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);

        // Our key helper
        ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this,
                DB_NAME);
        database = dbOpenHelper.openDataBase();
        // That’s it, the database is open!
        fillFreinds();
        setUpList();
    }

    private void setUpList() {
        // We use a standard adapter and an element layout for brevity’s sake
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, friends));
        listView = getListView();

        // Let’s set a message shown upon tapping an item
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View view,
                    int position, long id) {
                Toast.makeText(
                        getApplicationContext(),
                        ((TextView) view).getText()
                                + " could be Softeq's friend",
                        Toast.LENGTH_SHORT).show();
            }

        });

    }

    // Extracting elements from the database
    private void fillFreinds() {
        friends = new ArrayList<String>();
        Cursor friendCursor = database.query(TABLE_NAME, new String[] {
                FRIEND_ID, FRIEND_NAME }, null, null, null, null, FRIEND_NAME);
        friendCursor.moveToFirst();
        if (!friendCursor.isAfterLast()) {
            do {
                String name = friendCursor.getString(1);
                friends.add(name);
            } while (friendCursor.moveToNext());
        }
        friendCursor.close();
    }
}