我尝试在Android上学习SQLite
。这是我的第一个SQL应用程序。所以我找不到这些错误的原因。
这是MainActivity.java :
public class MainActivity extends AppCompatActivity {
ListView listView;
final ArrayList<String> artNameList =new ArrayList<String>();
static ArrayList<Bitmap> artImageList = new ArrayList<Bitmap>();
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater =getMenuInflater();
menuInflater.inflate(R.menu.add_art,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.add_art){
Intent intent = new Intent(getApplicationContext(),Main2Activity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.listView);
ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,artNameList);
listView.setAdapter(arrayAdapter);
String Url ="content://com.example.duygu.newartbook.ArtContentProvider";
Uri artUri =Uri.parse(Url);
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(artUri,null,null,null,"name");
if(cursor !=null ){
while (cursor.moveToNext()){
artNameList.add(cursor.getString(cursor.getColumnIndex(ArtContentProvider.NAME)));
byte[] bytes = cursor.getBlob(cursor.getColumnIndex(ArtContentProvider.IMAGE));
Bitmap image = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
artImageList.add(image);
arrayAdapter.notifyDataSetChanged();
}
}
}
}
这是ArtContentProvider.java
public class ArtContentProvider extends ContentProvider {
//****************************************************CONTENT PROVIDER**************************************************************
static final String PROVIDER_NAME ="com.example.duygu.newartbook.ArtContentProvider";
static final String URL ="content://"+PROVIDER_NAME+"/arts";
static final Uri CONTENT_URI =Uri.parse(URL); //Url'nin uri'ye çevirilmesi.
static final String NAME="name";
static final String IMAGE="image";
static final int ARTS=1;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME,"arts",ARTS);
}
private static HashMap<String,String> ART_PROJECTION_MAP;
//******************************DATABASE********************************************************************
private SQLiteDatabase sqLiteDatabase;
static final String DATABASE_NAME ="Arts";
static final String ARTS_TABLE_NAME="arts";
static final int DATABASE_VERSION=1;
static final String CREATE_DATABASE_TABLE="CREATE TABLE "+
ARTS_TABLE_NAME+"(name TEXT NOT NULL, "+
"image BLOB NOT NULL);"; // Başka bir yerde kullanmak istediğimiz için bu şekilde tanımlıyoruz.
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DATABASE_TABLE); //tablomuzu açarak başlıyoruz.
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) { // herhangi bir upgrade durumunda tablo silinip yenisi oluşturuluyor.
db.execSQL("DROP TABLE IF EXISTS " + ARTS_TABLE_NAME);
onCreate(db);
}
}
//******************************DATABASE********************************************************************
@Override
public boolean onCreate() {
Context context= getContext();
DatabaseHelper databaseHelper =new DatabaseHelper(context); // helper çağrıldı
sqLiteDatabase=databaseHelper.getWritableDatabase(); //yazılabilir olması için
return (sqLiteDatabase != null); //sqlitedatabase boş değilse true döner. Boolena çevirmiş olduk.
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projections, @Nullable String selection, @Nullable String[] strings1, @Nullable String sortOrder) {
SQLiteQueryBuilder sqLiteQueryBuilder = new SQLiteQueryBuilder();
sqLiteQueryBuilder.setTables(ARTS_TABLE_NAME);
switch (uriMatcher.match(uri)){
case ARTS:
sqLiteQueryBuilder.setProjectionMap(ART_PROJECTION_MAP);
break;
default:
}
if(sortOrder == null || sortOrder.matches("")){
sortOrder=NAME; //isme göre diz
}
Cursor cursor =sqLiteQueryBuilder.query(sqLiteDatabase,projections,selection,strings1,null,null,sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),uri); // uri da bir değişiklik olursa takip etmek için kullandığımız yöntem.
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
long rowID= sqLiteDatabase.insert(ARTS_TABLE_NAME,"",contentValues);
if (rowID>0){
Uri newUri= ContentUris.withAppendedId(CONTENT_URI,rowID);
getContext().getContentResolver().notifyChange(newUri,null);
return newUri;
}
throw new SQLException("Failed");
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
return 0;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
return 0;
}
}
这是我的错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.duygu.newartbook, PID: 26354
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.duygu.newartbook/com.example.duygu.newartbook.MainActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.access$900(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at android.database.CursorWrapper.getString(CursorWrapper.java:137)
at com.example.duygu.newartbook.MainActivity.onCreate(MainActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6272)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)