Cannot resolve ContentProvider outside the application - java

I'm trying to share basic data between 2 applications using SharedPreferences.
I've created a Class that extends ContentProvider:
package com.chou.playground;
///imports...
public class SharedIdProvider extends ContentProvider {
static final String PROVIDER_NAME = BuildConfig.APPLICATION_ID + ".provider";
static final String URL = "content://" + PROVIDER_NAME + "/__hd";
static final int uriCode = 1;
static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "/__hd", uriCode);
uriMatcher.addURI(PROVIDER_NAME, "/__hd/*", uriCode);
}
private transient static SharedPreferences prefs;
private transient static String hardwareId;
#Override
public String getType(#NotNull Uri uri) {
if (uriMatcher.match(uri) == uriCode) {
return PROVIDER_NAME + "/__hd";
}
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
#Override
public boolean onCreate() {
Context context = getContext();
if (context != null) {
prefs = context.getSharedPreferences("rsa_application_key_prefs", 0);
hardwareId = getHardwareId(context);
context.getContentResolver().notifyChange(Uri.parse(URL), null);
return true;
}
return true;
}
public static void update(Context context, String value){
hardwareId = value;
storeHardwareID(context.getApplicationContext(), value);
}
static synchronized String getHardwareId(Context context) {
String hardwareId = null;
if (null != context) {
hardwareId = getStoredHardwareId(context.getApplicationContext());
if (TextUtils.isEmpty(hardwareId)) {
hardwareId = generateHardwareId();
storeHardwareID(context.getApplicationContext(), hardwareId);
}
}
return hardwareId;
}
private static void storeHardwareID(Context context, String hardwareId) {
if (prefs == null) {
Log.e("SdkPreferences", "unexpected error in storeHardwareID, can't get shared preferences");
} else {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("com.aes.api.hardware_id", hardwareId);
editor.putBoolean("com.aes.api.can_be_sync", true);
editor.apply();
}
}
private static String getStoredHardwareId(Context context) {
if (prefs == null) {
Log.e("SdkPreferences", "unexpected error in getStoredHardwareId, can't get shared preferences");
return "INVALID";
} else {
return prefs.getString("com.aes.api.hardware_id", null);
}
}
private static String generateHardwareId() {
return UUID.randomUUID().toString();
}
#Override
public Cursor query(#NotNull Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Context context = getContext();
MatrixCursor cursor = new MatrixCursor(new String[] { "__hd" });
cursor.addRow(new Object[]{ getCachedOrLoadHardwareId( context ) });
return cursor;
}
public static boolean canBeSynchronized() {
return prefs.getBoolean("com.aes.api.can_be_sync", false);
}
private String getCachedOrLoadHardwareId(Context context) {
if(hardwareId == null){
hardwareId = getHardwareId(context);
}
return hardwareId;
}
#Override
public Uri insert(#NotNull Uri uri, ContentValues values) {
return null;
}
#Override
public int update(#NotNull Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;
}
#Override
public int delete(#NotNull Uri uri, String selection, String[] selectionArgs) {
return 0;
}
}
also added the class reference in the AndroidManifest.xml:
<provider
android:authorities="${applicationId}.provider"
android:enabled="true"
android:exported="true"
android:grantUriPermissions="true"
android:name="com.chou.playground.SharedIdProvider">
</provider>
then in my MainActivity I'm trying to get the data:
private void trySyncWith() {
Uri kUri = Uri.parse("content://" + "com.chou.app1.provider" + "/__hd");
Context context = getBaseContext();
if (context != null) {
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver != null) {
final Cursor cursor = contentResolver.query(kUri, null, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToNext();
String hardwareId = cursor.getString(0);
if (hardwareId != null) {
SharedIdProvider.update(context, hardwareId);
}
cursor.close();
}
}
}
}
everythings works fine when the app is the same, but when I change the applicationId in my gradle.build file in com.chou.app2, com.chou.app2 cannot find the first content provider, the log says:
Failed to find provider info for com.chou.app1.provider
The strange thing it's that when I run from terminal:
adb shell content query --uri content://com.chou.app1.provider/__hd
then everything starts working properly even from the second app.
Someone can help me?

Related

Couldn't read row 0, col -1 from CursorWindow. error

I want to make simple recyclerview from external database but the app crashes. This is in the logcat:
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
DatabaseAccess class:
public class DatabaseAccess {
private SQLiteDatabase database;
private SQLiteOpenHelper openHelper;
private static DatabaseAccess instance;
private DatabaseAccess (Context context) {
this.openHelper = new MyDatabase(context);
}
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
public void open() {
this.database = this.openHelper.getWritableDatabase();
}
public void close() {
if (this.database!= null) {
this.database.close();
}
}
public ArrayList<CAR> getAllCars() {
ArrayList<CAR> cars = new ArrayList<>();
Cursor cursor = database.rawQuery(" SELECT * FROM " + MyDatabase.CAR_TB_NAME, null);
if (cursor != null && cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(MyDatabase.CAR_CLN_ID));
String model = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_MODEL));
String color = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_COLOR));
double dpl = cursor.getDouble(cursor.getColumnIndex(MyDatabase.CAR_CLN_DPL));
CAR c = new CAR(id,model,color,dpl);
cars.add(c);
}
while (cursor.moveToNext());
cursor.close();
}
return cars;
}
}
the error disappeared when I corrected that part of code
int id = cursor.getInt(cursor.getColumnIndex(MyDatabase.CAR_CLN_ID));
String model = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_MODEL));
String color = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_COLOR));
double dpl = cursor.getDouble(cursor.getColumnIndex(MyDatabase.CAR_CLN_DPL));
to
int id = cursor.getInt(0);
String model = cursor.getString(1);
String color = cursor.getString(2);
double dpl = cursor.getdouble(3);

Missing file path

I would like to send the image and text that I received from the user to the server but I have problems.
void sendData(final String username) {
String url = "http://hesabdarbartar.ir/api/update";
final SharedPreferences preferences = getApplicationContext().getSharedPreferences("data_user", Context.MODE_PRIVATE);
AndroidNetworking.upload(url)
.addMultipartFile(Key.IMAGE, new File(path))
.addMultipartParameter(Key.NAME, username)
.addHeaders(Key.TOKEN, preferences.getString("api_token", ""))
.build()
.getAsObject(User.class, new ParsedRequestListener<User>() {
#Override
public void onResponse(User response) {
try {
preferences.edit().putString("name", response.getName()).apply();
preferences.edit().putString("pic", response.getPic()).apply();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "خطا در ارتباط با سرور!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError) {
Log.i("ererer", "" + String.valueOf(anError));
}
});
}
void askReadPermission() {
Dexter.withActivity(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
pickImage();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response != null && response.isPermanentlyDenied()) {
Snackbar.make(btn_confirm, "برای انتخاب فایل دسترسی ضروری است!", Snackbar.LENGTH_LONG).setAction("اجازه دادن!", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.fromParts("package", getApplicationContext().getPackageName(), null));
startActivity(i);
}
}).show();
} else {
Snackbar.make(btn_confirm, "برای انتخاب فایل دسترسی ضروری است!", Snackbar.LENGTH_LONG).show();
}
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
}
private void pickImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data.getData() != null) {
path = data.getData().getPath();
btn_confirm.setEnabled(true);
img_prof.setImageURI(data.getData());
}
}
}
Here's a snapshot of the program's problems
What you receive in onActivityResult() is an Uri of the image, not its real path. You should convert it to the real path, then you can use it in new File(path). There is a converter:
public class RealPathUtil {
public static String getRealPath(Context context, Uri fileUri) {
String realPath;
// SDK < API11
if (Build.VERSION.SDK_INT < 11) {
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(context, fileUri);
}
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19) {
realPath = RealPathUtil.getRealPathFromURI_API11to18(context, fileUri);
}
// SDK > 19 (Android 4.4) and up
else {
realPath = RealPathUtil.getRealPathFromURI_API19(context, fileUri);
}
return realPath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
String result = null;
CursorLoader cursorLoader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = 0;
String result = "";
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
return result;
}
return result;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #author paulburke
*/
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}

Adding Data to SQLiteDatabase

I have a SQLite DB file in assets which is then imported in the application.
The select query works fine and shows the results but at the same time if I try to insert data into the table it does not work. I get no error so that I can identify the problem.
DatabaseHelper class: addProject() method is to insert data.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DB_VERSION=1;
private static String DB_PATH="";
private static final String DB_NAME="AndroidProject.sqlite";
//Projects Table attrib
String TABLE_PROJECT="Project";
String KEY_PROJECT_ID = "_id";
String KEY_PROJECT_NAME = "project_name";
String KEY_PROJECT_DESC = "project_desc";
String KEY_PROJECT_TYPE = "project_type";
String KEY_PROJECT_START_DATE = "start_date";
String KEY_PROJECT_END_DATE = "end_date";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (Build.VERSION.SDK_INT>=15){
DB_PATH=context.getApplicationInfo().dataDir + "/databases/";
}
else {
DB_PATH= Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/databases/";
}
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void checkAndCopyDatabase(){
boolean doExists=checkDatabase();
if (doExists){
Log.d("TAG", "Database alredy exists");
}
else{
this.getReadableDatabase();
}
try {
copyDatabase();
} catch (IOException e) {
e.printStackTrace();
Log.d("TAG", "Error Copying DATABASE");
}
}
public boolean checkDatabase(){
SQLiteDatabase checkDB=null;
try {
String myPath=DB_PATH+DB_NAME;
checkDB=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
}catch (SQLiteException e){
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public void copyDatabase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase(){
String myPath = DB_PATH + DB_NAME;
myDatabase=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close(){
if (myDatabase != null){
myDatabase.close();
}
super.close();
}
public Cursor QueryData(String query){
return myDatabase.rawQuery(query,null);
}
public void addProject(SqlProjects blog){
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PROJECT_NAME, blog.get_project_name());
values.put(KEY_PROJECT_DESC, blog.get_project_desc());
values.put(KEY_PROJECT_TYPE, blog.get_project_type());
values.put(KEY_PROJECT_START_DATE, blog.get_project_start_date());
values.put(KEY_PROJECT_END_DATE, blog.get_project_end_date());
try {
Log.d("TAG", "Adding data");
myDatabase.insertOrThrow(TABLE_PROJECT, null, values);
} catch (SQLiteException e) {
e.printStackTrace();
}
myDatabase.close();
}
}
SqlProjects class Constructor, getters and setters
public class SqlProjects {
private DatabaseHelper helper;
int _id;
String _project_name, _project_desc,_project_type;
String _project_start_date,_project_end_date;
public SqlProjects() {
}
public SqlProjects(String _project_name, String _project_desc, String _project_type, String _project_start_date, String _project_end_date) {
this._project_name = _project_name;
this._project_desc = _project_desc;
this._project_type = _project_type;
this._project_start_date = _project_start_date;
this._project_end_date = _project_end_date;
}
public SqlProjects(int _id, String _project_name, String _project_desc, String _project_type, String _project_start_date, String _project_end_date) {
this._id = _id;
this._project_name = _project_name;
this._project_desc = _project_desc;
this._project_type = _project_type;
this._project_start_date = _project_start_date;
this._project_end_date = _project_end_date;
}
public int get_project_id() {
return _id;
}
public void set_project_id(int _project_id) {
this._id = _project_id;
}
public String get_project_name() {
return _project_name;
}
public void set_project_name(String _project_name) {
this._project_name = _project_name;
}
public String get_project_desc() {
return _project_desc;
}
public void set_project_desc(String _project_desc) {
this._project_desc = _project_desc;
}
public String get_project_type() {
return _project_type;
}
public void set_project_type(String _project_type) {
this._project_type = _project_type;
}
public String get_project_start_date() {
return _project_start_date;
}
public void set_project_start_date(String _project_start_date) {
this._project_start_date = _project_start_date;
}
public String get_project_end_date() {
return _project_end_date;
}
public void set_project_end_date(String _project_end_date) {
this._project_end_date = _project_end_date;
}
}
Main Class
final DatabaseHelper db = new DatabaseHelper(Add_Project.this);
btnAddProjects.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!(TextUtils.isEmpty(editName.getText().toString())) && !(TextUtils.isEmpty(editDesc.getText().toString())) && !(tvStartDate.getText().equals("")) && !(tvEndDate.getText().equals(""))) {
db.addProject(new SqlProjects(editName.getText().toString(), editDesc.getText().toString(), editType.getSelectedItem().toString(), tvStartDate.getText().toString(), tvEndDate.getText().toString()));
editName.setText("");
editDesc.setText("");
tvStartDate.setText("");
tvEndDate.setText("");
Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
});
I think you have forgot to open the database before insert operation.
btnAddProjects.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!(TextUtils.isEmpty(editName.getText().toString())) && !(TextUtils.isEmpty(editDesc.getText().toString())) && !(tvStartDate.getText().equals("")) && !(tvEndDate.getText().equals(""))) {
//open db before any operation
db.openDatabase();
db.addProject(new SqlProjects(editName.getText().toString(), editDesc.getText().toString(), editType.getSelectedItem().toString(), tvStartDate.getText().toString(), tvEndDate.getText().toString()));
editName.setText("");
editDesc.setText("");
tvStartDate.setText("");
tvEndDate.setText("");
Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
});
Seems like the issue anyways check it out!

how to display images from sqlite through drawable

I want to display images from column 'images' in 'penyakit' table from sqlite database. That image display through TabGambar.java.
My friend told me than I can put address of image in database and save that image in drawable. But I don't understand how it works. I have tried to use string uri drawable but it can only display one image for all.
Previously, I had been looking for references on google and find so many tutorials. But I still don't get which part should I add or change. Can somebody help my problem?
This is my works.
TabGambar.java
public class TabGambar extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.tabgambar, container, false);
configureTextView(view);
return view;
}
private void configureTextView(View view) {
// TODO Auto-generated method stub
TextView namapenyakit = (TextView) view.findViewById(R.id.namapenyakit);
ImageView gambarpenyakit = (ImageView) view.findViewById(R.id.gambarpenyakit);
Bundle b = getActivity().getIntent().getExtras();
if (b != null)
{
namapenyakit.setText(b.getString("nama_penyakit"));
String uri = "#drawable/ayam1";
int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
gambarpenyakit.setImageDrawable(res);
}
}
}
DBAdapter.java
public class DBAdapter extends SQLiteAssetHelper {
//nama database, versi, dan nama tabel yang akan dibuat.
private static final String DATABASE_NAME = "pakarayam";
private static final int DATABASE_VERSION = 1;
private static final String tabel_gejala = "gejala";
public static final String kd_gejala = "kode_gejala";
public static final String nm_gejala = "nama_gejala";
private static final String tabel_penyakit = "penyakit";
public static final String kd_penyakit = "kode_penyakit";
public static final String nm_penyakit = "nama_penyakit";
public static final String deskripsi = "deskripsi";
public static final String solusi = "solusi";
public static final String gambar = "gambar";
private static final String tabel_rule = "rule";
public static final String kd_rule = "kode_rule";
public static final String ko_gejala = "kode_gejala";
public static final String ko_penyakit = "kode_penyakit";
public static final String nilai_mb = "nilai_mb";
public static final String nilai_md = "nilai_md";
private static DBAdapter dbInstance;
private static SQLiteDatabase db;
private DBAdapter(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBAdapter getInstance(Context context)
{
if (dbInstance == null)
{
dbInstance = new DBAdapter(context);
db = dbInstance.getWritableDatabase();
}
return dbInstance;
}
#Override
public synchronized void close()
{
super.close();
if (dbInstance != null)
{
dbInstance.close();
}
}
public ArrayList<Gejala> getAllGejala()
{
ArrayList<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {kd_gejala, nm_gejala
}, null, null, null, null, nm_gejala);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
gejala.setKode_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(kd_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Gejala> Search(String Nama_gejala)
{
List<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {
kd_gejala,
nm_gejala },
nm_gejala + " like ?", new String[] {"%"+ Nama_gejala +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Penyakit> getAllPenyakit()
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {kd_penyakit, nm_penyakit, deskripsi, solusi, gambar
}, null, null, null, null, nm_penyakit);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public List<Penyakit> Searching (String Nama_penyakit)
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {
kd_penyakit,
nm_penyakit,
deskripsi,
solusi,
gambar},
nm_penyakit + " like ?", new String[] {"%"+ Nama_penyakit +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public double getMB(/*int kode_rule,*/ String kode_gejala)
{
/*
Cursor cursor = db.query(tabel_rule, new String[]
{kd_rule, ko_gejala, ko_penyakit, nilai_mb, nilai_md
}, ko_gejala + " like ?", new String[] {"%"+ kode_gejala +"%"},
null, null, null, null);
double mb = 0;
cursor.moveToFirst();
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
} while (cursor.moveToNext());
}
*/
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double mb = 0;
if(cursor != null){
cursor.moveToFirst();
while(!cursor.isAfterLast()){
mb = cursor.getDouble(3);
}
}
return mb;
}
public double getMD(/*int kode_rule,*/ String kode_gejala)
{
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double md = 0;
// cursor.moveToFirst();
// md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
/*
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
} while (cursor.moveToNext());
}
*/
if(cursor != null){
cursor.moveToFirst();
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
System.out.print(nilai_md);
}
return md;
}
}
I'm not sure of the exact details here but basically, if you want to store images in your database you must store the information as a 'blob' of bytes.
You'll need to convert between bytes and Bitmap when you read from the DB and Bitmap and bytes when you want to write to the DB.
A URI is usually used for a file coming from your device storage or somewhere on a server/website etc.
If this is what you're looking for and you'd like more detailed help just let me know and I can provide more info.

android.content.res.Resources$NotFoundException: Resource ID #0x88a6fd

I'm beginner and I'm trying to to load contact from database by clicking a button in a fragment, and then save outgoing call also in database?
ContactsFragemt.java
public class ContactsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>
{
SimpleCursorAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.contact, container, false);
final Button Button = (Button) view.findViewById(R.id.load_button);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(getActivity());
//*************************** method for population main contacts listView *********************************//
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String image_uri = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
int position = 0;
int exist = 0;
boolean imageComp, nameComp;
String[] contactsData = sqlDataBaseHelper.getContacts(position);
while (exist == 0 && (contactsData[0] != (null) || contactsData[1] != (null) || contactsData[2] != (null))) // we are checking that if it is reached at the end or not
{
if (contactsData[1] != null) {
if (contactsData[1].equals(phNumber)) // will make update if we got matched with phone number and if any of ther other parameter is changed
{
if (contactsData[2] == null) {
// pic is null saved in data base and
if (image_uri != null) {
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
// then update new pic here
}
} else // but if their is pic
if (!contactsData[2].equals(image_uri)) { // and he/she update pic with a brand new picture then
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
}
if (contactsData[0] == null) {
// name is null saved in data base and
if (contactName != null) {
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
// then update new name here
}
} else // if name was saved previously in based
if (!contactsData[0].equals(contactName)) { //but the guy changed his name so
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
}
exist = 1;
}
}
position++;
contactsData = sqlDataBaseHelper.getContacts(position);
}
if (exist == 0) // means if number is not in the list then make update
{
long id = sqlDataBaseHelper.insertData1(contactName, phNumber, image_uri);
if (id < 0) {
Toast.makeText(getActivity(), "Data1 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Data1 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
}
String[] fromFieldNames = sqlDataBaseHelper.fromFieldName1();
int[] toViewIDs = sqlDataBaseHelper.toIds1();
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.list_items_view,
null,
fromFieldNames,
toViewIDs,0);
ListView mainList = (ListView) view.findViewById(R.id.main_list_view);
mainList.setAdapter(adapter);
getLoaderManager().initLoader(0, null, ContactsFragment.this);
}
});
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = ContentProvider.CONTENT_URI;
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader loader) {
adapter.swapCursor(null);
}
}
SimpleCursorAdapter.java
public class SimpleCursorAdapter extends android.widget.SimpleCursorAdapter {
Context mcontext;
String[] values;
Cursor cursor;
int[] to;
public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.values = from;
this.to = to;
this.cursor = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(list_items_view, parent, false);
final ImageButton call = (ImageButton) view.findViewById(R.id.call);
ImageButton sms = (ImageButton) view.findViewById(R.id.sms);
final TextView contact_no = (TextView) view.findViewById(R.id.contact_no);
final TextView contactName = (TextView) view.findViewById(R.id.contact_name);
ImageView contactImage = (ImageView) view.findViewById(R.id.contact_image);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(mcontext);
//********************************** method for calling from app****************************/
call.setOnClickListener(new View.OnClickListener() { //when phone button is clicked
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(String.valueOf("tel:" + contact_no.getText().toString())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//*/
if (ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mcontext.startActivity(callIntent);//*/
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) { // for 12 hours format
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
Cursor c = mcontext.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
if (c.moveToNext() == true) {
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/outgoing_call.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
c.close();
}
});
//********************************** method for sending message from app****************************//
sms.setOnClickListener(new View.OnClickListener() { //when sms button is clicked
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + contact_no.getText().toString()));
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(smsIntent);
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) {
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
String duration = "000 000 000";
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/message_sent.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
});
//************************** Reading contact from SQLDataBase for each item*************************************//
String[] contactsData = sqlDataBaseHelper.getContacts(position);
if (contactsData[0] != (null)) {
contactName.setText(contactsData[0]);
contact_no.setText(contactsData[1]);
if (contactsData[2] == (null)) {
contactImage.setImageResource(R.drawable.w4j8n);
} else {
contactImage.setImageURI(Uri.parse(contactsData[2]));
}
}//*/
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
}
}
ContentProvider.java
public class ContentProvider extends android.content.ContentProvider {
public static final String PROVIDER_NAME = "com.example.asim.simpleviewpager"; //.contentprovider
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/ContactsDataBase");
private static final int CONTENTPROVIDERS = 1;
private static final UriMatcher uriMatcher ;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "ContactsDataBase", CONTENTPROVIDERS);
}
SQLDataBaseAdapter sqlDataBaseAdapter;
#Override
public boolean onCreate() {
sqlDataBaseAdapter = new SQLDataBaseAdapter(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if (uriMatcher.match(uri) == CONTENTPROVIDERS) {
return sqlDataBaseAdapter.getAllContacts();
} else {
return null;
}
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
SQLDataBaseAdapter.java
public class SQLDataBaseAdapter {
SQLDataBaseHelper sqlDataBaseHelper;
public SQLDataBaseAdapter(Context context){
sqlDataBaseHelper = new SQLDataBaseHelper(context);
}
public long insertData1(String contactName, String contactNo, String pic){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.NO, contactNo);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE1_NAME,null,contentValues);
return id;
}
public long insertData2(String contactName, String duration, String time, String date, String pic ){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.DURATION, duration);
contentValues.put(SQLDataBaseHelper.TIME, time);
contentValues.put(SQLDataBaseHelper.DATE, date);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE2_NAME,null,contentValues);
return id;
}
public String[] getContacts(int position) {
String[] contactsData = new String[3];
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
String[] columns = {SQLDataBaseHelper.UID, SQLDataBaseHelper.NAME, SQLDataBaseHelper.PICTURE, SQLDataBaseHelper.NO};
Cursor cursor = db.query(SQLDataBaseHelper.TABLE1_NAME, columns, null, null, null, null, null);
cursor.moveToPosition(position);
int pos = cursor.getPosition();
int cnt = cursor.getCount();
int checkElement = cnt-pos;
if (checkElement > 0)
{
cursor.moveToPosition(position);
int nameColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NAME);
String name = cursor.getString(nameColumnIndex);
int noColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NO);
String contactNo = cursor.getString(noColumnIndex);
int picColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.PICTURE);
String picture = cursor.getString(picColumnIndex);
contactsData[0] = name;
contactsData[1] = contactNo;
contactsData[2] = picture;
} else
{
contactsData[0] = null;
contactsData[1] = null;
contactsData[2] = null;
}
cursor.close();
db.close();
return contactsData;
}
public void updateTable1 (String oldName, String newName, String oldPhoneNo, String NewPhoneNumber, String oldPic, String newPic) {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
if (oldName != newName) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, newName);
String[] whereArgs = {oldName};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NAME+" =? ",whereArgs);
}
if(oldPhoneNo!=NewPhoneNumber){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NO, NewPhoneNumber);
String[] whereArgs = {oldPhoneNo};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NO+" =? ",whereArgs);
}
if(oldPic!=newPic){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.PICTURE, NewPhoneNumber);
String[] whereArgs = {oldPic};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.PICTURE+" =? ",whereArgs);
}
}
public void deleteRowTable1()
{
}
public void updateTable2 ()
{
}
public void deleteRowTable2()
{
}
/////////////////////////////////////////////////////////////////////
public Cursor getAllContacts(){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return db.query(SQLDataBaseHelper.TABLE1_NAME, new String[] {
SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE},
null, null, null, null,
SQLDataBaseHelper.NAME + " asc ");
}
public SQLDataBaseAdapter open() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return this;
}
public Cursor getAllRows1() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
Cursor cursor = db.query(true, SQLDataBaseHelper.TABLE1_NAME, SQLDataBaseHelper.ALL_KEYS1, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public String[] fromFieldName1(){///
String[] fields = new String[] {SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE};
return fields;
}
public int[] toIds1(){
int[] toViewIds = new int[]{R.id.contact_name,R.id.contact_no,R.id.contact_image};
return toViewIds;
}
static class SQLDataBaseHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "ContactsDataBase";
private static final String TABLE1_NAME = "CALLS_TABLE1";
private static final String TABLE2_NAME = "LOGS_TABLE";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String NO = "ContactNo";
private static final String DURATION = "Duration";
private static final String PICTURE = "Picture";
private static final String DATE = "Date";
private static final String TIME = "Time";
private static final String[] ALL_KEYS1 = new String[] {UID,NAME, NO, PICTURE};
private static final String CREATE_TABLE1 = "CREATE TABLE "+TABLE1_NAME+" (" +UID+
" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+NO+" VARCHAR(255), "
+PICTURE+" VARCHAR(255));";
private static final String CREATE_TABLE2 = "CREATE TABLE "+TABLE2_NAME+" ("
+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+DURATION+" VARCHAR(255), "
+PICTURE+" VARCHAR(255), " +DATE+ " VARCHAR(255), "+TIME+ " VARCHAR(255));";
private static final String DROP_TABLE1 = "DROP TABLE IF EXIST"+ TABLE1_NAME ;
private static final String DROP_TABLE2 = "DROP TABLE IF EXIST"+ TABLE2_NAME ;
private Context context;
public SQLDataBaseHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE1);
Toast.makeText(context,"onCreate1 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
try {
db.execSQL(CREATE_TABLE2);
Toast.makeText(context,"onCreate2 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE1);
Toast.makeText(context,"onUpgrade1 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
try {
db.execSQL(DROP_TABLE2);
Toast.makeText(context,"onUpgrade2 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
}
}
}
and these are the errors
01-30 04:03:23.804 2702-2702/com.example.asim.simpleviewpager E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: Resource ID #0x88a6fd
at android.content.res.Resources.getValue(Resources.java:1049)
at android.content.res.Resources.getDrawable(Resources.java:664)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:175)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:168)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:51)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:72)
at android.support.v4.widget.SimpleCursorAdapter.setViewImage(SimpleCursorAdapter.java:195)
at android.support.v4.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:143)
In SimpleCursorAdapter.java, you have a method bindView() which overrides the same method from its parent class, but you don't put any code in that method. Deleting the method should fix the error. But if you plan to override how binding works in that method, you may want to put some code in there starting with something like
super.bindView(view, context, cursor);

Categories