2012-10-16 6 views
0

sqlite 용 데이터베이스를 만든 샘플 응용 프로그램을 만들고 있는데 테이블에 값을 삽입했습니다. 그러나 select 쿼리를 사용할 때 nullpointer 예외가 발생합니다.Sqlite select 문이 작동하지 않습니다.

public class MainActivity extends Activity { 

    Button insert; 
    Button show; 
    EditText name; 
    EditText mobile; 
    SQLiteDatabase db; 
    String name_str; 
    String mob_str; 

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


     name = (EditText)findViewById(R.id.name_editText); 


     insert = (Button) findViewById(R.id.insert_button); 

     insert.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       //Toast.makeText(getApplicationContext(), "Onclick works", Toast.LENGTH_LONG).show(); 



       name_str=name.getText().toString(); 
       Toast.makeText(getApplicationContext(), name_str, Toast.LENGTH_LONG).show(); 

       // create or open database file 
       db = openOrCreateDatabase("Test.db" , SQLiteDatabase.CREATE_IF_NECESSARY, 
                         null); 
       db.setVersion(1); 
       // db.setLocale(Locale.getDefault()); 
       db.setLockingEnabled(true); 

       //System.out.println("Database Created"); 

      // creating table in database 
       db.execSQL("CREATE TABLE IF NOT EXISTS "+"contacts"+" " + 
           "(id INTEGER PRIMARY KEY AUTOINCREMENT," + 
           " name varchar, " + 
           " mobile varchar); "); 

       db.execSQL("INSERT INTO contacts(name, mobile)VALUES ('Swift','9830098300');"); 

       db.execSQL("drop table contacts"); 


       //Database Exists check 
       File database=getApplicationContext().getDatabasePath("Test.db"); 

       if (!database.exists()) { 
        // Database does not exist so copy it from assets here 
        Log.i("Database", "Not Found"); 
       } else { 
        Log.i("Database", "Found"); 
       } 






      } 



     }); 
     show = (Button) findViewById(R.id.show_button); 

     show.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
//    //Toast.makeText(getApplicationContext(), "Onclick works", Toast.LENGTH_LONG).show(); 
       Cursor c =db.rawQuery("SELECT COUNT() FROM sqlite_master WHERE name ='contacts';",null); 
       if (c != null) { 
        if (c.moveToFirst()) { 
          do { 
     String firstName = c.getString(c.getColumnIndex("name")); 

          }while (c.moveToNext()); 
        } 
       } 

      } 
     }); 

    } 





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





} 

이는 main.xml에 있습니다 : :

이 내 클래스입니다

<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" > 

    <TextView 
     android:id="@+id/name_textView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginTop="60dp" 
     android:text="Name:" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

    <EditText 
     android:id="@+id/name_editText" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/name_textView" 
     android:layout_alignBottom="@+id/name_textView" 
     android:layout_marginLeft="14dp" 
     android:layout_toRightOf="@+id/name_textView" 
     android:ems="10" > 

     <requestFocus /> 
    </EditText> 

    <TextView 
     android:id="@+id/mobile_textView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_below="@+id/name_editText" 
     android:layout_marginTop="53dp" 
     android:text="Mobile: " 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

    <EditText 
     android:id="@+id/mobile_editText" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/mobile_textView" 
     android:layout_alignBottom="@+id/mobile_textView" 
     android:layout_alignLeft="@+id/name_editText" 
     android:ems="10" 
     android:inputType="phone" /> 

    <Button 
     android:id="@+id/insert_button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/mobile_editText" 
     android:layout_centerVertical="true" 
     android:text="Insert" /> 

    <Button 
     android:id="@+id/show_button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/insert_button" 
     android:layout_alignBottom="@+id/insert_button" 
     android:layout_alignRight="@+id/mobile_editText" 
     android:text="Show" /> 

</RelativeLayout> 

로그 캣 :

10-16 17:16:28.938: D/AndroidRuntime(413): Shutting down VM 
10-16 17:16:28.938: W/dalvikvm(413): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 
10-16 17:16:28.958: E/AndroidRuntime(413): FATAL EXCEPTION: main 
10-16 17:16:28.958: E/AndroidRuntime(413): java.lang.NullPointerException 
10-16 17:16:28.958: E/AndroidRuntime(413): at com.cyberswift.database.example.MainActivity$2.onClick(MainActivity.java:97) 
10-16 17:16:28.958: E/AndroidRuntime(413): at android.view.View.performClick(View.java:2408) 
10-16 17:16:28.958: E/AndroidRuntime(413): at android.view.View$PerformClick.run(View.java:8816) 
10-16 17:16:28.958: E/AndroidRuntime(413): at android.os.Handler.handleCallback(Handler.java:587) 
10-16 17:16:28.958: E/AndroidRuntime(413): at android.os.Handler.dispatchMessage(Handler.java:92) 
10-16 17:16:28.958: E/AndroidRuntime(413): at android.os.Looper.loop(Looper.java:123) 
10-16 17:16:28.958: E/AndroidRuntime(413): at android.app.ActivityThread.main(ActivityThread.java:4627) 
10-16 17:16:28.958: E/AndroidRuntime(413): at java.lang.reflect.Method.invokeNative(Native Method) 
10-16 17:16:28.958: E/AndroidRuntime(413): at java.lang.reflect.Method.invoke(Method.java:521) 
10-16 17:16:28.958: E/AndroidRuntime(413): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
10-16 17:16:28.958: E/AndroidRuntime(413): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
10-16 17:16:28.958: E/AndroidRuntime(413): at dalvik.system.NativeStart.main(Native Method) 
10-16 17:16:30.998: I/Process(413): Sending signal. PID: 413 SIG: 9 

는 정확히 내가 잘못 가고 ..... ..........

+0

logcat 데이터. – Prachi

+0

데이터 발생을 계산하는 것입니다. – kittu88

+0

null 인 경우 뭔가가 NULL입니다 !! –

답변

1

당신은 (String firstName = c.getString(c.getColumnIndex("name"));) 커서를 반복 할 때 찾을 수 없으므로 쿼리에서 name 열을 참조하십시오. 또한

, 당신은 당신이 계산 열을 지정하거나 SQL 쿼리에있는 모든 계산해야합니다

db.rawQuery("SELECT name, COUNT(*) AS "+ "\""+ "count"+ "\""+ " FROM sqlite_master WHERE name ='contacts'",null); 

이 그럼 당신은 String firstName = c.getString(c.getColumnIndex("name"));을 사용할 수 있습니다 모하메드는 'didn를 말한다으로 count는 필요한 값을

+0

커서 값을 확인하기위한 if 조건이 유지됩니까? – kittu88

+0

예, 모든 코드는 db.rawQuery 부분을 제외하고 동일합니다. –

+0

여전히 동일한 예외가 발생합니다. – kittu88

0

이있을 것이다 쿼리에서 이름 열을 선택하십시오. 내가 아는 한

, 행을 계산 안드로이드에서 당신은 당신이 원하는대로 열을 선택한 다음 계산으로 cursor.size()를 받아야합니다. (권장)을

당신이 커서에서 데이터를 얻고 싶다면, 먼저 당신에게 에서 cursor.size()> 0이 (c! = null)인지 확인해야합니다. 데이터베이스에서 데이터를 가져 오는 예제 :

if (cursor != null && cursor.size() > 0) 
{ 
// get count 
int count = cursor.size(); 

// to get data 
cursor.moveToFirst(); 
while(!cursor.isAfterLast()) 
{ 
// do get data from cursor 
} 
} 
관련 문제