在Android工作室中使用SQLitedatabase getWritableDatabase()时,Java IO Exception Broken Pipe

时间:2015-01-21 12:15:51

标签: android android-sqlite broken-pipe getwritabledatabase

当我使用getWritableDatabase()或getReadableDatabase()函数时,ADB日志会显示此错误。

ddmlib: Broken pipe
java.io.IOException: Broken pipe
    at sun.nio.ch.FileDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:29)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:69)
    at sun.nio.ch.IOUtil.write(IOUtil.java:40)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:336)
    at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
    at com.android.ddmlib.Client.sendAndConsume(Client.java:675)
    at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:342)
    at com.android.ddmlib.Client.requestAllocationStatus(Client.java:521)
    at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:847)
    at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:815)
    at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:633)
    at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:46)
    at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:592)

我正在创建一个Android应用程序,并添加了SQLiteDatabase作为我的数据库,我实现了如下的基本数据库代码。

package intracode.org.ksuapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jongwookim on 1/20/15.
 */
public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String

    DATABASE_NAME = "applicantDB",
    TABLE_APPLICANT = "applicants",
    KEY_ID = "id",
    KEY_NAME = "name;",
    KEY_PHONE = "phone",
    KEY_EMAIL = "email",
    KEY_SID = "sid",
    KEY_IMAGEURI = "imageUri";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("Joey", "Database handler");
        db.execSQL("CREATE TABLE " + TABLE_APPLICANT + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                                                             KEY_NAME + " TEXT, " +
                                                             KEY_PHONE + " TEXT, " +
                                                             KEY_EMAIL + " TEXT, " +
                                                             KEY_SID +  " TEXT, " +
                                                             KEY_IMAGEURI + " TEXT)");
        Log.d("Joey", "Table created");

    }

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

        onCreate(db);
    }

    public void createApplicant(Applicant _applicant) {
        Log.d("Joey", "In create applicant");
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_NAME, _applicant.getName());
        values.put(KEY_PHONE, _applicant.getPhone());
        values.put(KEY_EMAIL, _applicant.getEmail());
        values.put(KEY_SID, _applicant.getSID());
        values.put(KEY_IMAGEURI, _applicant.getimageUri().toString());
//
        db.insert(TABLE_APPLICANT, null, values);
        db.close();

    }

    public Applicant getApplicant(int id) {
        SQLiteDatabase db = getReadableDatabase();
//
//        Cursor cursor1 = db.query(TABLE_APPLICANT, new String[] {KEY_ID, KEY_NAME, KEY_PHONE, KEY_SID, KEY_IMAGEURI},
//                KEY_ID + "=?", new String[] {String.valueOf(id)}, null, null, null, null);

        Cursor cursor = db.query(TABLE_APPLICANT, new String[] {KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL ,KEY_SID, KEY_IMAGEURI},
                                 KEY_ID + "=?", new String[] {String.valueOf(id)}, null, null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }

        Applicant applicant = new Applicant(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
                                            cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));

        db.close();
        cursor.close();
        return applicant;
    }

    public void deleteApplicant(Applicant applicant) {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(TABLE_APPLICANT, KEY_ID + "=?", new String[] {String.valueOf(applicant.getId())});
        db.close();
    }

    public int getApplicantCount() {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_APPLICANT, null );

        int count = cursor.getCount();

        db.close();
        cursor.close();

        return count;
    }

    public int updateApplicant(Applicant _applicant) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(KEY_NAME, _applicant.getName());
        values.put(KEY_PHONE, _applicant.getPhone());
        values.put(KEY_EMAIL, _applicant.getEmail());
        values.put(KEY_SID, _applicant.getSID());
        values.put(KEY_IMAGEURI, _applicant.getimageUri().toString());

        return db.update(TABLE_APPLICANT, values, KEY_ID + "=?", new String[] {String.valueOf(_applicant.getId())});
    }

    public List<Applicant> getAllApplicant() {

        List<Applicant> applicants = new ArrayList<Applicant>();
//        SQLiteDatabase db = getWritableDatabase();
//        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_APPLICANT, null);

//        if (cursor.moveToFirst()) {
//            do {
//                Applicant applicant = new Applicant(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
//                        cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
//                applicants.add(applicant);
//            } while (cursor.moveToNext());
//        }

        return applicants;
    }
}

这是我的申请人类

package intracode.org.ksuapplication;

import android.net.Uri;

/**
 * Created by jongwookim on 1/17/15.
 */
public class Applicant {

    private String _name, _phone, _email, _sid;
    private Uri _imageUri;
    private int _id;

    public Applicant(int id, String name, String phone, String email, String sid, Uri imageUri){
        _id = id;
        _name = name;
        _phone = phone;
        _email = email;
        _sid = sid;
        _imageUri = imageUri;
    }

    public int getId() {
        return _id;
    }

    public String getName() {
        return _name;
    }

    public String getPhone() {
        return _phone;
    }

    public String getEmail() {
        return _email;
    }

    public String getSID() {
        return _sid;
    }

    public Uri getimageUri() {
        return _imageUri;
    }
}

和MainActivity

package intracode.org.ksuapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    EditText a_Name, a_Email, a_Phone, a_sid;
    ImageView applicant_imageView;
    List<Applicant> applicants = new ArrayList<Applicant>();
    ListView applicantListView;
    Uri imageUri = null;
//    Uri imageUri = Uri.parse("android.resource://intracode.org.ksuapplicant/drawable/no_user.png");
    DatabaseHandler dbHandler;
    int index = 0;

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



        a_Name = (EditText) findViewById(R.id.applicantName);
        a_Email = (EditText) findViewById(R.id.applicantEmail);
        a_Phone = (EditText) findViewById(R.id.applicantPhone);
        a_sid = (EditText) findViewById(R.id.applicantSID);

        applicantListView = (ListView) findViewById(R.id.listView);

        applicant_imageView = (ImageView) findViewById(R.id.applicantImage);

        dbHandler = new DatabaseHandler(getApplicationContext());

        TabHost tab = (TabHost) findViewById(R.id.tab);

        tab.setup();

        TabHost.TabSpec tabSpec = tab.newTabSpec("staffApplication");
        tabSpec.setContent(R.id.staffApplication);
        tabSpec.setIndicator("staffApplication");
        tab.addTab(tabSpec);

        tabSpec = tab.newTabSpec("list");
        tabSpec.setContent(R.id.ApplicantList);
        tabSpec.setIndicator("list");
        tab.addTab(tabSpec);

        final Button applyButton = (Button) findViewById(R.id.applyButton);
        applyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Joey", "Button");
                Applicant applicant = new Applicant(dbHandler.getApplicantCount(), String.valueOf(a_Name.getText()),
                        String.valueOf(a_Phone.getText()), String.valueOf(a_Email.getText()), String.valueOf(a_sid.getText()), imageUri );
                dbHandler.createApplicant(applicant);
                applicants.add(applicant);

                Toast.makeText(getApplicationContext(), "You, " + a_Name.getText().toString()  +
                        ", successfully applied to KSU", Toast.LENGTH_SHORT).show();

                populateList();

            }
        });

        a_Name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                applyButton.setEnabled(!a_Name.getText().toString().trim().isEmpty());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        applicant_imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select your photo"), 1);
            }
        });

//        Log.d("Joey", "here");

//        List<Applicant> addableApplicants = dbHandler.getAllApplicant();

//        int applicantCount = dbHandler.getApplicantCount();

//        for (int i = 0;i < applicantCount;i++) {
//            applicants.add(addableApplicants.get(i));
//        }
//
//        if (!applicants.isEmpty()) {
//            populateList();
//        }
    }

    public void onActivityResult(int reqCode, int resCode, Intent data) {
        if (resCode == RESULT_OK) {
            if (reqCode == 1) {
                imageUri = data.getData();
                applicant_imageView.setImageURI(data.getData());
            }
        }
    }

    private void populateList() {
        ArrayAdapter<Applicant> adapter = new ApplicantListAdapter();
        applicantListView.setAdapter(adapter);
    }


    private class ApplicantListAdapter extends ArrayAdapter<Applicant> {
        public ApplicantListAdapter() {
            super (MainActivity.this, R.layout.list_applicant, applicants  );
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.list_applicant, parent, false);
            }

            Applicant currentApplicant = applicants.get(position);

            TextView name = (TextView) view.findViewById(R.id.applicant_Name);
            TextView phone = (TextView) view.findViewById(R.id.applicant_Phone);
            TextView email = (TextView) view.findViewById(R.id.applicant_Email);
            TextView sid = (TextView) view.findViewById(R.id.applicant_StudentID);
            ImageView ivApplicantImage = (ImageView) view.findViewById(R.id.applicantImage_inListView);


            name.setText(currentApplicant.getName());
            phone.setText(currentApplicant.getPhone());
            email.setText(currentApplicant.getEmail());
            sid.setText(currentApplicant.getSID());
            ivApplicantImage.setImageURI(currentApplicant.getimageUri());

            return view;
        }
    }

    @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_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

我不知道为什么我得到错误。 这是因为getWritableDatabase()?还是其他一些问题?

我尝试调试,似乎Table不是在DatabaseHandler类中创建onCreate功能。我在CREATE TABLE之前和之后放了日志。 第二个日志不会出现在日志窗口中。

github链接在这里。

https://github.com/joeykiwi/KSUApplication

请帮助我,这是我下周的工作申请所必需的。

1 个答案:

答案 0 :(得分:0)

;中的KEY_NAME位置错误,导致语法错误。

您发布的堆栈跟踪不是来自设备。看一下设备logcat,发现像这样的运行时问题。