마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

데이터베이스 로그캣 오류발생

0 추천
public class SecondActivity extends Activity {

    public static final String TAG = "SecondActivity";

    DataListView listView;
    IconTextListAdapter adapter;
    InputMethodManager imm;
    String strSearch2;
    String strSearchQuery;

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

        Intent intent = getIntent();
//        strSearch2 = intent.getStringExtra("strSearch");

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        adapter = new IconTextListAdapter(this);

        listView = new DataListView(this);

        LinearLayout linLayout = (LinearLayout) findViewById(R.id.LayoutDicList);
        linLayout.addView(listView);

        strSearch2 = "로";
        strSearchQuery = strSearch2.concat("%");

        DatabaseHelper.openDatabase(DatabaseHelper.wordDatabaseFile);
        Cursor cursor = DatabaseHelper.queryMasterTable(strSearchQuery);

        AddCursorData(cursor);

        listView.setAdapter(adapter);

        listView.setOnDataSelectionListener( new OnDataSelectionListener () {

            public void onDataSelected(AdapterView parent, View v, int position, long id) {

                IconTextItem selectItem = (IconTextItem)adapter.getItem(position);

                Bundle bundle = new Bundle();
                bundle.putString("data0", selectItem.getData(0));
                bundle.putString("data1", selectItem.getData(1));

                Intent intent = new Intent( getApplicationContext(), DetailActivity.class );
                intent.putExtras(bundle);
                startActivity ( intent );
        }
        });
}

    protected void onDestroy() {
        super.onDestroy();

        DatabaseHelper.closeDatabase();
    }

     public void AddCursorData ( Cursor outCursor ) {

        int recordCount = outCursor.getCount();
        println("cursor count : " + recordCount + "\n");

        adapter.clear();

        int clasFromCol = outCursor.getColumnIndex("CLASFROM");
        int clasSoutCol = outCursor.getColumnIndex("CLASSOUT");

        Resources res = getResources();

         for (int i = 0; i < recordCount; i++) {
            outCursor.moveToNext();
            String clasFrom = outCursor.getString(clasFromCol);
            String clasSout = outCursor.getString(clasSoutCol);

            adapter.addItem(new IconTextItem(res.getDrawable(R.drawable.capsule1),clasSout,clasFrom));
        }

        outCursor.close();
    }

    public void println(String msg) {
        Log.d(TAG, msg);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

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

        return super.onOptionsItemSelected(item);
    }
}

쿼리마스터테이블(데이터 베이스 헬퍼)

public static SQLiteDatabase db;
public static String wordDatabaseFile = "/sdcard/wordinfo.db";

public static Cursor queryMasterTable(String strSearchWord ) {
        String aSQL = "select WORDFROM, WORDNAME, CLASFROM, CLASSOUT "
                + " from MASTER"
                + " where CLASSOUT like ?";

        String[] args = {strSearchWord};

        Cursor outCursor = db.rawQuery(aSQL, args);

        return (outCursor);
}
사전 프로그램을 만드는데 맨 처음 화면에 검색창을 놓고 검색 버튼을 눌렀을때 다음 액티비티에 리스트 형식으로 db내의 데이터가 표현되는 것인데요. 주석처리를 해서 알아본 결과         
Cursor cursor = DatabaseHelper.queryMasterTable(strSearchQuery);
가 있는 줄에서 앱을 실행하고 검색버튼을 누르면 오류메시지가 뜨네요.
일단은 주석으로 검색단어 "로"를 설정했습니다.
 
     Caused by: java.lang.NullPointerException
            at com.firstproject.codename.northdictionary.DatabaseHelper.queryMasterTable(DatabaseHelper.java:78)
            at com.firstproject.codename.northdictionary.SecondActivity.onCreate(SecondActivity.java:51)

 

익명사용자 님이 2015년 2월 23일 질문

2개의 답변

0 추천

SQLiteDatabase db;

정의만 해놓고 실제 값을 가져오지않고 바로 사용하니

NullPointerException 이 뜨는겁니다.

db = ............. 이게 필요하지요

nicehee (73,100 포인트) 님이 2015년 2월 23일 답변
0 추천
public class DatabaseHelper {

    public static final String TAG = "DatabaseHelper";
    public static SQLiteDatabase db;
    public static String wordDatabaseFile = "/sdcard/wordinfo.db";

    public DatabaseHelper(){}

    public static void openDatabase(String databaseFile){

        println("creating or opening database [" + wordDatabaseFile + "].");

        try{
            db = SQLiteDatabase.openDatabase(
                    databaseFile,null,SQLiteDatabase.OPEN_READWRITE);

        } catch (SQLiteException ex) {
    }
}

public static void  closeDatabase(){
    try {
        db.close();
    } catch (Exception ext) {
        ext.printStackTrace();
        println("Exception in closing database : " + ext.toString());
    }
}
    private static void createMasterTable() {
        try {
            db.execSQL("drop table if exists MASTER");
            db.execSQL("create table MASTER("
                    + " WORDFROM text, "
                    + " WORDNAME text, "
                    + " CLASFROM text, "
                    + " CLASSOUT text)" );

        } catch (SQLiteException ex) {
        }

    }

    public static boolean insertMasterData(String aLine) {
        String[] tokens = aLine.split("\\|");
        if (tokens != null && tokens.length > 3) {
            println("length of tokens : " + tokens.length);
            db.execSQL( "insert into MASTER(WORDFROM, WORDNAME, CLASFROM, CLASSOUT) values (" +
                    "'" + tokens[0] + "'," +
                    "'" + tokens[1] + "'," +
                    "'" + tokens[2] + "'," +
                    "'" + tokens[3] + "')");
            return true;
        } else {
            println("the input line is invalid.");
        }

        return false;
    }

    public static Cursor queryMasterTable(String strSearchWord) {

        String aSQL = "select WORDFROM, WORDNAME, CLASFROM, CLASSOUT "
                + " from MASTER"
                + " where CLASSOUT like ?";

        String[] args = {strSearchWord};

        Cursor outCursor = db.rawQuery(aSQL, args);

        return (outCursor);
    }

    public static Cursor queryDetailsTable(String strDrugCode) {
        String aSQL = "select WORDNAME, CLASSNAME, DETAILS "
                + " from DETAILS"
                + " where WORDNAME = ?";

        String[] args = {strDrugCode};

        Cursor outCursor = db.rawQuery(aSQL, args);

        return (outCursor);

    }

    public static void println(String msg) {
        Log.d(TAG, msg);}

opendatabase를 사용할 때 있습니다.

익명사용자 님이 2015년 2월 23일 답변
...