数据库不是在Android中使用Sqlite数据库创建的

时间:2013-06-25 06:12:36

标签: android android-listview android-sqlite

我已经制作了一个简单的Android数据库演示程序用于学习目的我已经重新链接如下: enter link description here

我已经一步一步地走了,但数据库没有在我的程序中创建,我的代码如下:

contactlistAdapter.java

package com.example.dblistview;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ContactListAdapter extends BaseAdapter {
    Context context;
    ArrayList<ContactListItems> contactList;
    public ContactListAdapter(Context context, ArrayList<ContactListItems> list) {

        this.context = context;
        contactList = list;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
    return contactList.size();
    }

    @Override
    public Object getItem(int pos) {
        // TODO Auto-generated method stub
        return contactList.get(pos);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         ContactListItems contactListItems = contactList.get(position);

            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.raw, null);

            }
            TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno);
            tvSlNo.setText(contactListItems.getSlno());
            TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
            tvName.setText(contactListItems.getName());
            TextView tvPhone = (TextView) convertView.findViewById(R.id.tv_phone);
            tvPhone.setText(contactListItems.getPhone());

            return convertView;

    }

}

contactListItems.java

package com.example.dblistview;

public class ContactListItems {
     String slno;
     String name;
     String phone;

     public String getSlno() {
      return slno;
     }

     public void setSlno(String slno) {
      this.slno = slno;
     }

     public String getName() {
      return name;
     }

     public void setName(String name) {
      this.name = name;
     }

     public String getPhone() {
      return phone;
     }

     public void setPhone(String phone) {
      this.phone = phone;
     }

    }

main.java

package com.example.dblistview;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
sqlHandler sqlHandler;
ListView lv;
Button submit;
EditText nm,fn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=(ListView)findViewById(R.id.lv_custom_list);
        nm=(EditText)findViewById(R.id.et_name);
        fn=(EditText)findViewById(R.id.et_phone);
        submit=(Button)findViewById(R.id.btn_submit);

        sqlHandler =new sqlHandler();
        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            String name=nm.getText().toString();
            String fon=fn.getText().toString();
             String query = "INSERT INTO PHONE_CONTACTS(name,phone) values ('"
                      + name + "','" + fon + "')";
            sqlHandler.executeQuery(query);

            }
        });

    }
        private void showList() {

          ArrayList<ContactListItems> contactList = new ArrayList<ContactListItems>();
          contactList.clear();
          String query = "SELECT * FROM PHONE_CONTACTS ";
          Cursor c1 = sqlHandler.selectQuery(query);
          if (c1 != null && c1.getCount() != 0) {
           if (c1.moveToFirst()) {
            do {
             ContactListItems contactListItems = new ContactListItems();

             contactListItems.setSlno(c1.getString(c1
               .getColumnIndex("slno")));
             contactListItems.setName(c1.getString(c1
               .getColumnIndex("name")));
             contactListItems.setPhone(c1.getString(c1
               .getColumnIndex("phone")));
             contactList.add(contactListItems);

            } while (c1.moveToNext());
           }
          }
          c1.close();

          ContactListAdapter contactListAdapter = new ContactListAdapter(
            MainActivity.this, contactList);
          lv.setAdapter(contactListAdapter);

         }
}

sqlDbhelper.java

package com.example.dblistview;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SqlDbhelper extends SQLiteOpenHelper {
    public static final String DATABASE_TABLE = "PHONE_CONTACTS";

    public static final String COLUMN1 = "slno";
    public static final String COLUMN2 = "name";
    public static final String COLUMN3 = "phone";

             private static final String SCRIPT_CREATE_DATABASE = "create table "
                       + DATABASE_TABLE + " (" + COLUMN1
                       + " integer primary key autoincrement, " + COLUMN2
                       + " text not null, " + COLUMN3 + " text not null);";

    public SqlDbhelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(SCRIPT_CREATE_DATABASE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("drop table if exists" + DATABASE_TABLE);
        onCreate(db);
    }

}

sqlhandler.java

package com.example.dblistview;
import com.example.dblistview.SqlDbhelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


public class sqlHandler {public static final String DATABASE_NAME = "MY_DATABASE";
public static final int DATABASE_VERSION = 1;
Context context;
SQLiteDatabase sqlDatabase;
SqlDbhelper dbHelper;

public void SqlHandler(Context context) {

 dbHelper = new SqlDbhelper(context, DATABASE_NAME, null,
   DATABASE_VERSION);
 sqlDatabase = dbHelper.getWritableDatabase();
}

public void executeQuery(String query) {
 try {

  if (sqlDatabase.isOpen()) {
   sqlDatabase.close();
  }

  sqlDatabase = dbHelper.getWritableDatabase();
  sqlDatabase.execSQL(query);

 } catch (Exception e) {

  System.out.println("DATABASE ERROR " + e);
 }

}

public Cursor selectQuery(String query) {
 Cursor c1 = null;
 try {

  if (sqlDatabase.isOpen()) {
   sqlDatabase.close();

  }
  sqlDatabase = dbHelper.getWritableDatabase();
  c1 = sqlDatabase.rawQuery(query, null);

 } catch (Exception e) {

  System.out.println("DATABASE ERROR " + e);


 }
 return c1;

}

}

2 个答案:

答案 0 :(得分:1)

Try this DatabaseUtil class to create :

public class DatabaseUtil 
{
    private static final String DATABASE_NAME = "database_name";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "table_name";
     private static final String ROW_ID = "_id";
    private static final String PARAM1 = "param1";
    private static final String PARAM2 = "param2";
    private static final String CREATE_TABLE = "create table " + TABLE_NAME + " (" + ROW_ID + " integer primary key autoincrement, "`enter code here`
            + param1+" text not null, " + param2+ " text not null);";
private final Context context;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) 
        {super(context, DATABASE_NAME, null, DATABASE_VERSION);}

        @Override
        public void onCreate(SQLiteDatabase db) 
        {db.execSQL(CREATE_TABLE);}

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        {}
    }

    public DatabaseUtil(Context c)
    {this.context = c;}

    public DatabaseUtil open() throws SQLException
    {
        mDbHelper = new DatabaseHelper(context);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close()
    {mDbHelper.close();}

    public long add(String strparam1,String strparam2)
    {
        ContentValues cv = new ContentValues();
        cv.put(PARAM1 ,strparam1);
        cv.put(PARAM2 ,strparam2);

        return mDb.insert(TABLE_NAME, null, cv);
    }

    public Cursor fetchAll()
    {return mDb.query(TABLE_NAME,new String[] {ROW_ID, PARAM1, PARAM2},null,null,null,null,null);}

    public boolean deleteTitle(String strparam1) 
    {return mDb.delete(TABLE_NAME,PARAM1 + "='" + strparam1+"'", null)>0;}
}

Then to create and add the values,
DatabaseUtil util = new DatabaseUtil(this);
util.open();
util.add(param1, param2);
util.close();

This will be simpler insert for you. 

答案 1 :(得分:0)

我猜DATABASE_NAME应该是“database_name.db”。这意味着您必须添加扩展名,因为这是文件名。

希望这会对你有所帮助。