1

我已经创建了 sdcard 并在其中保存了数据库文件 UPData.db。在这个数据库中,我创建了一个表名 Customer,但没有得到结果。正在显示 DBList 中的 NullPointerException。请帮助我按照相同的结构执行此操作?

activity_up.xml

<LinearLayout 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"
    tools:context=".UP"
    android:orientation="vertical">
    <LinearLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="UserName" />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="UserName" 
        android:id="@+id/un"/>
    </LinearLayout>
    <LinearLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PassWord" />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="PassWord"
        android:id="@+id/pw" />
    </LinearLayout>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Submit"
        android:id="@+id/submit"/>

</LinearLayout>

res/layout/list.xml

<LinearLayout 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"
    tools:context=".UP"
   >
   <ListView 
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:id="@+id/listview"></ListView>

</LinearLayout>

viewholder.xml

<LinearLayout 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"
    tools:context=".UP"
   android:orientation="vertical">
   <TextView 
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:id="@+id/tvid"/>
   <TextView 
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:id="@+id/tvname"/>
   <TextView 
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:id="@+id/tvaddress"/>
   <TextView 
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:id="@+id/tvphone"/>

</LinearLayout>


**manifest.xml**

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.up"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" 
        android:name="Main">
        <activity
            android:name="com.example.up.UP"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="ShowList"></activity>
    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>


**UP.java**

package com.example.up;
public class UP extends Activity {
    EditText un,pw;
    Button submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_up);
        un=(EditText)findViewById(R.id.un);
        pw=(EditText)findViewById(R.id.pw);
        submit=(Button)findViewById(R.id.submit);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String user=un.getText().toString();
                String pwd=pw.getText().toString();
                System.out.println("user--"+user +"&&"+"Password is--"+pwd);
                Intent showlist=new Intent(UP.this,ShowList.class);
                startActivity(showlist);

            }
        });
    }


}

**ShowList.java**

package com.example.up;
public class ShowList extends Activity {
    ListView list;
    ArrayList<ListData> alist;
    ArrayList<ListData> achildlist;
    ArrayAdapter<String> adapter;
    int id=-1;
    Cursor cur=null;
    ListData listdata;
    DBHelper help;
    DBList dblist;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        list=(ListView)findViewById(R.id.listview);

        loadData();

    }
    public void loadData(){
        try{
            alist=new ArrayList<ShowList.ListData>();
            dblist=new DBList(this);
            cur=dblist.getListData(this);

            if(cur!=null){
                if(cur.moveToFirst()){
                    do{
                        listdata=new ListData();
                        listdata.setCustomerId(cur.getInt(cur.getColumnIndex("customerId")));
                        listdata.setCustomerName(cur.getString(cur.getColumnIndex("customerName")));
                        listdata.setCustomerName(cur.getString(cur.getColumnIndex("customerAddress")));
                        listdata.setCustomerId(cur.getInt(cur.getColumnIndex("phone")));

                        String id=Integer.toString(cur.getInt(cur.getColumnIndex("customerId")));
                        System.out.println(id);

                        alist.add(listdata);
                    }while(cur.moveToNext());
                }
                cur.close();
            }
            list.setAdapter(new ListDataAdapter(this,alist));
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    class ListDataAdapter extends BaseAdapter{

        Context con;
        ListDataAdapter(Context c,ArrayList<ListData> listadapter){
            this.con=c;
            achildlist=listadapter;
        }

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

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

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

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            ViewHolder obj=null;
            try{
                if(arg1==null){
            obj=new ViewHolder();
            LayoutInflater vi=(LayoutInflater)getSystemService(Context.LOCATION_SERVICE);
            arg1=vi.inflate(R.layout.viewholder, null);
            obj.tvid=(TextView)arg1.findViewById(R.id.tvid);
            obj.tvname=(TextView)arg1.findViewById(R.id.tvname);
            obj.tvaddress=(TextView)arg1.findViewById(R.id.tvaddress);
            obj.tvphone=(TextView)arg1.findViewById(R.id.tvphone);
            arg1.setTag(obj);
                }else{
                    obj=(ViewHolder)arg1.getTag();
                }
                if(obj!=null){
                    ListData listdata=achildlist.get(arg0);
                    obj.tvid.setText(listdata.getCustomerId());
                    obj.tvname.setText(listdata.getCustomerName());
                    obj.tvaddress.setText(listdata.getCustomerAddress());
                    obj.tvphone.setText(listdata.getPhone());
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return arg1;

        }

    }
    class ViewHolder {
        TextView tvid;
        TextView tvname;
        TextView tvaddress;
        TextView tvphone;
    }
    class ListData{
         int customerId;
         String customerName;
         String customerAddress;
         int phone;

         public int getCustomerId() {
            return customerId;
        }
        public void setCustomerId(int customerId) {
            this.customerId = customerId;
        }
        public String getCustomerName() {
            return customerName;
        }
        public void setCustomerName(String customerName) {
            this.customerName = customerName;
        }
        public String getCustomerAddress() {
            return customerAddress;
        }
        public void setCustomerAddress(String customerAddress) {
            this.customerAddress = customerAddress;
        }
        public int getPhone() {
            return phone;
        }
        public void setPhone(int phone) {
            this.phone = phone;
        }

    }

}

**Main.java**

package com.example.up;    
public class Main extends Application {

        public DBHelper adapter;

}

**DBHelper.java**

package com.example.up; 
public class DBHelper{
    public static final int version = 1;
    public  String DBName = "/sdcard/UPData.db";
    private SQLiteDatabase dbSqlite;
    private Context c;
    public SQHelper openhelper;

    //public static final String PATH_APPLICATION = "/Android/Data/com.example.up/files/";
    //public static final String FOLDER_LOGS = "Logs/";
    //public static final String LOG_FILE_NAME = "ErrorLog.txt";


    public DBHelper(Context context){
        c=context;
        openhelper=new SQHelper(c, DBName, null, version);
    }


    public class SQHelper extends SQLiteOpenHelper{

        public SQHelper(Context context, String name,
                CursorFactory factory, int version) {
            super(context, name, factory, version);
            // TODO Auto-generated constructor stub

        }

        @Override
        public void onCreate(SQLiteDatabase db) {

             try{
                 System.out.println("inside oncreate of dbhelper+++++++++");
                 File sdcard = Environment.getExternalStorageDirectory();
                   File f = new File(sdcard,"UPData.db");
                   if(!f.exists()){
                       f.createNewFile();
                   }

                   BufferedReader buf = new BufferedReader(new FileReader(f));
                   String readString = new String(); 
                   while((readString = buf.readLine())!= null){

                      Log.d("oncreate of DBHelper in UP..........", readString);
                   }
                } catch (FileNotFoundException e) {
                   e.printStackTrace();
                } catch (IOException e){
                   e.printStackTrace();
                }
            // TODO Auto-generated method stub
            /*try {


                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                    String strDirPath = Environment.getExternalStorageDirectory().getPath() + PATH_APPLICATION + FOLDER_LOGS;
                    File dirLog = new File(strDirPath);
                    if (!dirLog.isDirectory() || !dirLog.exists()) {
                        dirLog.mkdirs();
                    }
                    //String strLogFile = "Logs_" + CommonMethods.getCurrentDateTime(Values.DATE_FORMAT) + ".txt";
                    String strLogFile = LOG_FILE_NAME;
                    File fileLog = new File(dirLog, strLogFile);
                    if (!fileLog.exists()) {
                        fileLog.createNewFile();
                    }

                    FileWriter fileWrite = new FileWriter(fileLog, true);

                    BufferedWriter bufWriter = new BufferedWriter(fileWrite);

                    //String strLog = CommonMethods.getCurrentDateTime(Values.DATE_TIME_2_FORMAT) + " ERROR : " + strModule + "\t" + strLogData + " ; " + "\r\n";
                    //bufWriter.write(strLog);
                    bufWriter.close();
                    fileWrite.close();

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }*/

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

        }

    }   
    public void close() {
        try {
            dbSqlite.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void open() throws SQLiteException {
        try {

            dbSqlite = openhelper.getWritableDatabase();

        } catch (SQLiteException e) {
            dbSqlite = openhelper.getReadableDatabase();
            e.printStackTrace();
        }
    }

    public Cursor getRecordsWithRawQuery(String strSql, String[] sArrSelectionArgs) {
        Cursor cursor = null;
        try {

            cursor = dbSqlite.rawQuery(strSql, sArrSelectionArgs);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
        return cursor;
    }

    public void executeNonQuery(String strQuery) {
        try {
            dbSqlite.execSQL(strQuery);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}

//这个java类(DBList)我得到空指针异常。我应该在哪一部分编写代码以从 sdcard 读取表。或者这是否需要!

DBList.java

package com.example.up; 
public class DBList {

    private  int customerId;
    private  String customerName;
    private  String customerAddress;
    private  int phone;

     Context context;
     Main maincall;
    SQLiteDatabase db;





     public DBList(Context con){
        this.context=con;
        maincall=(Main)context.getApplicationContext();
     }

    public  Cursor getListData(Context context){
        Cursor cur=null;
        try{

            //String query="Select customerId,customerName,customerAddress,phone from Customer where customerId="+id;
            String query="Select customerId,customerName,customerAddress,phone from Customer";
            Main maincall=(Main)context.getApplicationContext();
            cur=maincall.adapter.getRecordsWithRawQuery(query, null);

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

            return cur; 
    }
    public void insert(){
        try{
            String query="Insert into Customer(customerId,customerName,customerAddress,phone) Values" +"("+customerId+","+customerName+","+customerAddress+","+phone+")";
            maincall.adapter.executeNonQuery(query);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public  int getCustomerId() {
        return customerId;
    }

    public  void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }
    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
    public String getCustomerAddress() {
        return customerAddress;
    }
    public void setCustomerAddress(String customerAddress) {
        this.customerAddress = customerAddress;
    }
    public int getPhone() {
        return phone;
    }
    public void setPhone(int phone) {
        this.phone = phone;
    }

}
4

1 回答 1

3

最好使用资产文件夹中的数据库...检查此答案这可能会对您有所帮助..将数据库文件从 /assets 复制到文件资源管理器中的 /data/data 文件夹 - Android

于 2013-08-30T07:35:43.127 回答