why function are not getting executed in sequence? - java

Here is the problem...I have three different functions namely syncFirebaseContacts(); getAllContacts(); and compareContactUpdateList();. These function's execution order is very important because first function's output becomes input of another. As I have said I have placed these three function in my onCreate() method in sequence as described.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new AdoreDataSource(this);
datasource.open();
syncFirebaseContacts();
getAllContacts();
compareContactUpdateList();
.......
But while debugging I found out that although pointer points syncFirebaseContacts() first but the code of getAllContact() is executed first and then compareContactUpdateList() is executed and after that syncFirebaseContacts() code is executed.
private void getAllContacts() {
String contactNumber;
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//All Mapping Stuff to be done here..
contactNumber = contactNumber.replaceAll("\\s+","");
contactNumber = contactNumber.trim();
lst2.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext());
}
}
private void syncFirebaseContacts() {
Firebase userLocationRef = new Firebase(Constants.FIREBASE_URL_USERS);
userLocationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dsp : dataSnapshot.getChildren()){
datasource.createContact(String.valueOf(dsp.getKey()));
lst1.add(String.valueOf(dsp.getKey()));
Log.e("Hello", String.valueOf(dsp.getKey()));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("Could not process", "Sorry");
}
});
}
private void compareContactsUpdateList() {
ArrayList<String> commonOfAll = new ArrayList<String>(lst1);
commonOfAll.retainAll(lst2);
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
final ArrayList<ContactsList> contacts = new ArrayList<ContactsList>();
//List<SyncContacts> syncContacts = datasource.getAllContacts();
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
String nameOfContact = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumber = contactNumber.replaceAll("\\s+","");
contactNumber = contactNumber.trim();
Log.d("Name ", nameOfContact + contactNumber);
for(int j =0; j < commonOfAll.size(); j++){
if(contactNumber.equals(commonOfAll)){
Log.d("Name ", nameOfContact);
contacts.add(new ContactsList(contactNumber, nameOfContact, R.mipmap.ic_launcher));
}
}
break;
}
pCur.close();
}
} while (cursor.moveToNext());
}
final ContactsAdapterTwo contactsAdapterTwo = new ContactsAdapterTwo(this, contacts);
final GridView gridView = (GridView) findViewById(R.id.grid);
gridView.post(new Runnable() {
public void run() {
gridView.setAdapter(contactsAdapterTwo);
}
});
}
As my problem is that I want to compare two lists which is done in compareContactsUpdateList() by the line
ArrayList<String> commonOfAll = new ArrayList<String>(lst1);
commonOfAll.retainAll(lst2); as I found out that lst1 is always empty because syncFirebaseContacts() 's code is excuted at last
My applogies if my question length is too long or if my problem is trivial. But it is a big problem for me coz I am new to coding :-) please help me....Anyways Thanx in advance...

Related

how to fix sqliteException in android java

I have trying to insert values into database as well as in content provider but getting null sqlite exception.Before using content provider class my data are added to database without any problem.after trying content provider im getting exception. Also I doesn't know whether values are inserted for content provider.....
And in SpecificActivity class I need to use drawable which is returned by LoadImageAsyncTask class but Im getting null value there...
Help me to solve those issues..
public class FeedReaderContract {
public static class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_CONTENT = "content";
public static final String COLUMN_NAME_IMAGE = "image";
public static final String COLUMN_NAME_CHANNEL = "channel";
}
}
public class FeedReaderDbHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
Context context;
public Context getContext() {
return context;
}
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY, " +
FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + " TEXT, " +
FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT + " TEXT, " +
FeedReaderContract.FeedEntry.COLUMN_NAME_CHANNEL + " TEXT, " +
FeedReaderContract.FeedEntry.COLUMN_NAME_IMAGE + " TEXT); ";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
NewsFeedProvider.db = db;
db.execSQL(SQL_CREATE_ENTRIES);
Log.e("sql db", "created");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME);
onCreate(db);
}
public void getData(long id) {
try {
Log.e("entered", "getdata");
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(FeedReaderContract.FeedEntry.TABLE_NAME, new String[] {
FeedReaderContract.FeedEntry._ID, FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, FeedReaderContract.FeedEntry.COLUMN_NAME_CHANNEL, FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, FeedReaderContract.FeedEntry.COLUMN_NAME_IMAGE
}, FeedReaderContract.FeedEntry._ID + "=?", new String[] {
String.valueOf(id)
}, null, null, null, null);
ArrayList < NewsReport > newsReports = new ArrayList < > ();
List itemIds = new ArrayList < > ();
while (cursor.moveToNext()) {
newsReports.add(new NewsReport(cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE)),
cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_NAME_CHANNEL)),
cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT)),
cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_NAME_IMAGE))));
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID));
itemIds.add(itemId);
Log.e("id", "" + itemId);
}
cursor.close();
Log.e("newsreportsize", "dbhelper" + newsReports.size());
if (newsReports.size() != 0) {
for (int i = 0; i < newsReports.size(); i++) {
Log.e("news pic", "" + newsReports.get(i).getPic());
Log.e("news title", "" + newsReports.get(i).getTitle());
Log.e("news content", "" + newsReports.get(i).getContent());
Log.e("news chanel", "" + newsReports.get(i).getNewsChannel());
}
}
} catch (Exception ex) {
Log.e("exception req data", "" + ex);
}
}
}
public class LoadImageAsyncTask extends AsyncTask < String, Void, Drawable > {
private Drawable drawable;
String imageUrl;
private Drawable image;
#Override
protected Drawable doInBackground(String...strings) {
try {
InputStream is = (InputStream) new URL(imageUrl).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
Log.e("drwable", "" + d);
} catch (Exception e) {
Log.e("Specific Activity", "Converting drawable" + e);
}
return drawable;
}
#Override
protected void onPostExecute(Drawable drawableImage) {
super.onPostExecute(drawableImage);
setImage(drawableImage);
}
public void setImage(Drawable drawable) {
new SpecificNewsReportActivity().drawable = drawable;
Log.e("set image", "" + drawable);
this.drawable = drawable;
}
public Drawable getImage() {
Log.e("get image", "" + drawable);
return drawable;
}
}
public class NewsFeedProvider extends ContentProvider {
static final String PROVIDER_NAME = "com.example.newsreport";
static final String URL = "content://" + PROVIDER_NAME + "/newsfeed";
static final Uri CONTENT_URL = Uri.parse(URL);
static final int uriCode = 1;
static String newsTitle;
static String newsContent;
static String newsImage;
static String newsChannel;
static final UriMatcher uriMatcher;
private FeedReaderDbHelper dbHelper;
private static HashMap < String, String > values;
public static SQLiteDatabase db;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "newsfeed", uriCode);
}
#Override
public boolean onCreate() {
dbHelper = new FeedReaderDbHelper(getContext());
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(FeedReaderContract.FeedEntry.TABLE_NAME);
switch (uriMatcher.match(uri)) {
case uriCode:
queryBuilder.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
}
//Cursor cursor=queryBuilder.query(dbHelper.getReadableDatabase(),projection,selection,selectionArgs,null,null,sortOrder);
Cursor cursor = dbHelper.getReadableDatabase().query(FeedReaderContract.FeedEntry.TABLE_NAME, projection, FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + "= ?", selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case uriCode:
return "vnd.android.cursor.dir/newsfeed";
default:
throw new IllegalArgumentException("Unsupported URI" + uri);
}
}
#Override
public Uri insert(Uri uri, ContentValues contentValues) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long rowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME, null, contentValues);
if (rowId > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URL, rowId);
getContext().getContentResolver().notifyChange(_uri, null);
Log.e("insert", "feedreader" + contentValues);
return _uri;
} else {
Toast.makeText(getContext(), "Row insert failed", Toast.LENGTH_SHORT).show();
return null;
}
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int rowsDeleted = 0;
SQLiteDatabase db = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)) {
case uriCode:
rowsDeleted = db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
int rowsUpdated = 0;
SQLiteDatabase db = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)) {
case uriCode:
rowsUpdated = db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
}
public class NewsReportActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks < ArrayList < NewsReport >> {
ProgressBar progressBar;
FeedReaderDbHelper dbHelper;
SQLiteDatabase db;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view);
dbHelper = new FeedReaderDbHelper(this);
db = dbHelper.getWritableDatabase();
Log.e("application", "" + dbHelper);
Intent intent = getIntent();
if (intent.hasExtra("exception")) {
TextView connectionTextView = (TextView) findViewById(R.id.no_connection_text_view);
connectionTextView.setText("There is no internet connection!!!");
} else {
Log.e("no exception", "entered else");
}
getSupportLoaderManager().initLoader(0, null, this);
}
#NonNull
#Override
public Loader < ArrayList < NewsReport >> onCreateLoader(int id, #Nullable Bundle args) {
NewsReportLoader newsReportLoader = new NewsReportLoader(this);
newsReportLoader.forceLoad();
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
return newsReportLoader;
}
#Override
public void onLoadFinished(#NonNull Loader < ArrayList < NewsReport >> loader, ArrayList < NewsReport > data) {
try {
Log.e("data", "" + data.size());
NewsReportAdapter adapter = new NewsReportAdapter(this, data);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
progressBar.setVisibility(View.INVISIBLE);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
new LinearLayoutManager(this).getOrientation());
recyclerView.addItemDecoration(mDividerItemDecoration);
if (dbHelper != null) {
Log.e("dbhelper", "notnull");
db = dbHelper.getWritableDatabase();
if (db != null) {
Log.e("db", "notnull");
for (int i = 0; i < data.size(); i++) {
ContentValues values = new ContentValues();
NewsReport newsReport = data.get(i);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, newsReport.getTitle());
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, newsReport.getContent());
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CHANNEL, newsReport.getNewsChannel());
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_IMAGE, newsReport.getPic());
values.put(NewsFeedProvider.newsTitle, newsReport.getTitle());
values.put(NewsFeedProvider.newsContent, newsReport.getContent());
values.put(NewsFeedProvider.newsChannel, newsReport.getNewsChannel());
values.put(NewsFeedProvider.newsImage, newsReport.getPic());
try {
Uri uri = getApplicationContext().getContentResolver().insert(NewsFeedProvider.CONTENT_URL, values);
} catch (Exception ex) {
Log.e("exception in resolver" + getContentResolver(), "" + ex);
}
long newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME, null, values);
Log.e("new row id", "" + newRowId);
dbHelper.getData(newRowId);
}
} else
Log.e("db", "null");
} else {
Log.e("dbhelper", "null");
}
// db.execSQL("delete from "+ FeedReaderContract.FeedEntry.TABLE_NAME);
} catch (Exception ex) {
Log.e("newsactivity", "" + FeedReaderContract.FeedEntry.TABLE_NAME.length());
Log.e("onloadfinished", "" + ex);
Log.e("datahelper", "" + dbHelper.getReadableDatabase().rawQuery("SELECT * FROM " + FeedReaderContract.FeedEntry.TABLE_NAME, null));
}
}
#Override
public void onLoaderReset(#NonNull Loader < ArrayList < NewsReport >> loader) {
}
}
public class SpecificNewsReportActivity extends AppCompatActivity {
private TextView contentTextView, titleTextView;
public ImageView imageView;
private Intent intent;
public Drawable drawable;
private String imageUrl;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_specific_news_report);
ActionBar actionBar = this.getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
intent = getIntent();
LoadImageAsyncTask task = new LoadImageAsyncTask();
AsyncTask < String, Void, Drawable > d = task.execute();
try {
drawable = d.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
imageUrl = getIntent().getStringExtra("image");
Log.e("drawable specific", "" + drawable);
drawable = new LoadImageAsyncTask().getImage();
contentTextView = (TextView) findViewById(R.id.specific_news_report_content_text_view);
titleTextView = (TextView) findViewById(R.id.specific_news_report_title_text_view);
imageView = (ImageView) findViewById(R.id.specific_news_report_image_view);
contentTextView.setText(intent.getStringExtra("content"));
titleTextView.setText(intent.getStringExtra("title"));
try {
if (drawable != null) {
imageView.setImageDrawable(drawable);
} else {
Log.e("returned drawable", "null");
}
} catch (Exception ex) {
Log.e("enna exception", "" + ex);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
Intent intent = NavUtils.getParentActivityIntent(this);
NavUtils.navigateUpTo(this, intent);
}
return super.onOptionsItemSelected(item);
}
}
stacktrace
2019-07-29 13:57:20.172 24098-24098/com.example.newsreport E/SQLiteLog: (1) near "null": syntax error
2019-07-29 13:57:20.177 24098-24098/com.example.newsreport E/SQLiteDatabase: Error inserting channel=News18.com null=https://images.news18.com/ibnlive/uploads/2019/07/yediyurappa-1.jpg image=https://images.news18.com/ibnlive/uploads/2019/07/yediyurappa-1.jpg title=Karnataka Assembly Trust Vote LIVE: Yediyurappa Wins Floor Test, Speaker Ramesh Kumar Resigns - News18 content=Eleven Congress MLAs and three JDS lawmakers faced the axe from the Speaker in addition to the three disqualified earlier, bringing down the majority mark to 104, one less than the current strength of 105 of the BJP, which also enjoys the support of an Indepe… [+3489 chars]
android.database.sqlite.SQLiteException: near "null": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO entry(channel,null,image,title,content) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:903)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:514)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1562)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at com.example.newsreport.NewsFeedProvider.insert(NewsFeedProvider.java:78)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:265)
at android.content.ContentResolver.insert(ContentResolver.java:1587)
at com.example.newsreport.NewsReportActivity.onLoadFinished(NewsReportActivity.java:96)
at com.example.newsreport.NewsReportActivity.onLoadFinished(NewsReportActivity.java:29)
at androidx.loader.app.LoaderManagerImpl$LoaderObserver.onChanged(LoaderManagerImpl.java:250)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:131)
at androidx.lifecycle.LiveData.setValue(LiveData.java:289)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:33)
at androidx.loader.app.LoaderManagerImpl$LoaderInfo.setValue(LoaderManagerImpl.java:189)
at androidx.loader.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManagerImpl.java:174)
at androidx.loader.content.Loader.deliverResult(Loader.java:132)
at androidx.loader.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:258)
at androidx.loader.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:83)
at androidx.loader.content.ModernAsyncTask.finish(ModernAsyncTask.java:490)
at androidx.loader.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:507)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-07-29 13:57:20.218 24098-24098/com.example.newsreport E/SQLiteLog: (1) near "null": syntax error
2019-07-29 13:57:20.220 24098-24098/com.example.newsreport E/SQLiteDatabase: Error inserting channel=News18.com null=https://images.news18.com/ibnlive/uploads/2019/07/yediyurappa-1.jpg image=https://images.news18.com/ibnlive/uploads/2019/07/yediyurappa-1.jpg title=Karnataka Assembly Trust Vote LIVE: Yediyurappa Wins Floor Test, Speaker Ramesh Kumar Resigns - News18 content=Eleven Congress MLAs and three JDS lawmakers faced the axe from the Speaker in addition to the three disqualified earlier, bringing down the majority mark to 104, one less than the current strength of 105 of the BJP, which also enjoys the support of an Indepe… [+3489 chars]
android.database.sqlite.SQLiteException: near "null": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO entry(channel,null,image,title,content) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:903)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:514)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1562)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at com.example.newsreport.NewsReportActivity.onLoadFinished(NewsReportActivity.java:102)
at com.example.newsreport.NewsReportActivity.onLoadFinished(NewsReportActivity.java:29)
at androidx.loader.app.LoaderManagerImpl$LoaderObserver.onChanged(LoaderManagerImpl.java:250)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
I need to use drawable which is returned from loadimageasynctask
I need to store all data in database as well as for content provider
In the table there are 4 columns and the primary key.
When you insert a new row you supply values for the ContentValues object but you do it twice for each column:
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, newsReport.getTitle());
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, newsReport.getContent());
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CHANNEL, newsReport.getNewsChannel());
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_IMAGE, newsReport.getPic());
values.put(NewsFeedProvider.newsTitle, newsReport.getTitle());
values.put(NewsFeedProvider.newsContent, newsReport.getContent());
values.put(NewsFeedProvider.newsChannel, newsReport.getNewsChannel());
values.put(NewsFeedProvider.newsImage, newsReport.getPic());
Why?
I suspect that one of:
NewsFeedProvider.newsTitle
NewsFeedProvider.newsContent
NewsFeedProvider.newsChannel
NewsFeedProvider.newsImage
returns null.
So delete these lines:
values.put(NewsFeedProvider.newsTitle, newsReport.getTitle());
values.put(NewsFeedProvider.newsContent, newsReport.getContent());
values.put(NewsFeedProvider.newsChannel, newsReport.getNewsChannel());
values.put(NewsFeedProvider.newsImage, newsReport.getPic());
They are not needed.
The values for the columns are set by the previous 4 lines.

Migrating to CursorLoader & LoaderManager for AutoCompleteTextView with SQLiteDatabase

I have an AutoCompleteTextView, which shows dropdown list of suggestions taken from a SQLiteDatabase query. At the moment it uses SimpleCursorAdapter, however there are several problems with it (I have a separate question about the issue here: SimpleCursorAdapter issue - "java.lang.IllegalStateException: trying to requery an already closed cursor").
Nevertheless, I was advised to look in the direction of CursorLoader and LoaderManager, and I've tried it, yet couldn't make it work. I'd be grateful if someone would guide/recommend/show the right way of migrating my code below to CursorLoader/LoaderManager concept. Any kind of help very appreciated!
mAdapter = new SimpleCursorAdapter(this,
R.layout.dropdown_text,
null,
new String[]{CITY_COUNTRY_NAME},
new int[]{R.id.text}, 0);
mAutoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
cityCountryName = cursor.getString(cursor.getColumnIndexOrThrow(CITY_COUNTRY_NAME));
mAutoCompleteTextView.setText(cityCountryName);
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{cityCountryName});
}
});
mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence sequence) {
String constraint = sequence.toString();
String queryString = "SELECT " + ID + ", " + CITY_ID + ", " + CITY_COUNTRY_NAME + " FROM " + TABLE_1;
constraint = constraint.trim() + "%";
queryString += " WHERE " + CITY_COUNTRY_NAME + " LIKE ?";
String params[] = {constraint};
try {
Cursor cursor = database.rawQuery(queryString, params);
if (cursor != null) {
startManagingCursor(cursor);
cursor.moveToFirst();
return cursor;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
});
mAutoCompleteTextView.setAdapter(mAdapter);
Here is the whole project for the reference (you can make a pull request there, if you wish): Open Weather App
Unfortunately, here on SO nobody came up with a solution, yet a colleague (he doesn't have an SO account) made a pull request with the migration fixes. It works perfectly, and I decided to post the correct answer here as well.
If you're interested in how these improvements look inside the actual code, you're welcome to visit the original open source project page on GitHub: Open Weather App
This is the new adapter:
mAdapter = new SimpleCursorAdapter(this,
R.layout.dropdown_text,
null,
new String[]{CITY_COUNTRY_NAME},
new int[]{R.id.text},0);
mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
if (constraint != null) {
if (constraint.length() >= 3 && !TextUtils.isEmpty(constraint)) {
Bundle bundle = new Bundle();
String query = charArrayUpperCaser(constraint);
bundle.putString(CITY_ARGS, query);
getLoaderManager().restartLoader(0, bundle, MainActivity.this).forceLoad();
}
}
return null;
}
});
This is the onCreateLoader() callback:
#Override
public android.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
String s = args.getString(CITY_ARGS);
WeatherCursorLoader loader = null;
if (s != null && !TextUtils.isEmpty(s)) {
loader = new WeatherCursorLoader(this, database, s);
}
return loader;
}
Custom CursorLoader itself:
private static class WeatherCursorLoader extends CursorLoader {
private SQLiteDatabase mSQLiteDatabase;
private String mQuery;
WeatherCursorLoader(Context context, SQLiteDatabase cDatabase, String s) {
super(context);
mSQLiteDatabase = cDatabase;
mQuery = s + "%";
Log.d(TAG, "WeatherCursorLoader: " + mQuery);
}
#Override
public Cursor loadInBackground() {
return mSQLiteDatabase.query(TABLE_1, mProjection,
CITY_COUNTRY_NAME + " like ?", new String[] {mQuery},
null, null, null, "50");
}
}

Saving elements in SQLite Android

I want to save DatabaseTableDay to my SQLite in anndroid applicatin but something gones wrong.
My DatabaseDAODay is:
public class DatabaseDAODay {
public static final String TAG = "DaysDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DatabaseHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = { DatabaseHelper.COLUMN_DAY_ID,
DatabaseHelper.COLUMN_DAY_NAME, DatabaseHelper.COLUMN_DAY_WEIGHT};
public DatabaseDAODay(Context context) {
this.mContext = context;
mDbHelper = new DatabaseHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public DatabaseTableDay createDay(String name, float weight, Long id) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_DAY_NAME, name);
values.put(DatabaseHelper.COLUMN_DAY_WEIGHT, weight);
long insertId = id;
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_DAYS, mAllColumns,
DatabaseHelper.COLUMN_DAY_ID + " = " + insertId, null, null,
null, null);
DatabaseTableDay newDay = new DatabaseTableDay();
if(cursor != null && cursor.moveToFirst()){
newDay = cursorToDay(cursor);
cursor.close();
Toast.makeText(mContext,"im here",Toast.LENGTH_LONG).show();
}
return newDay;
}
public void deleteDay(DatabaseTableDay databaseTableDay) {
long id = databaseTableDay.getId();
// delete all employees of this company
DatabaseDAOActivity databaseDAOActivity = new DatabaseDAOActivity(mContext);
List<DatabaseTableActivity> databaseTableActivities = databaseDAOActivity.getActivitiesOfDay(id);
if (databaseTableActivities != null && !databaseTableActivities.isEmpty()) {
for (DatabaseTableActivity e : databaseTableActivities) {
databaseDAOActivity.deleteActivity(e);
}
}
System.out.println("the deleted day has the id: " + id);
mDatabase.delete(DatabaseHelper.TABLE_DAYS, DatabaseHelper.COLUMN_DAY_ID
+ " = " + id, null);
}
public List<DatabaseTableDay> getAllDays() {
List<DatabaseTableDay> listDays = new ArrayList<DatabaseTableDay>();
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_DAYS, mAllColumns,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
DatabaseTableDay day = cursorToDay(cursor);
listDays.add(day);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listDays;
}
public DatabaseTableDay getDayById(long id) {
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_DAYS, mAllColumns,
DatabaseHelper.COLUMN_DAY_ID + " = ?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
DatabaseTableDay databaseTableDay = cursorToDay(cursor);
return databaseTableDay;
}
protected DatabaseTableDay cursorToDay(Cursor cursor) {
DatabaseTableDay databaseTableDay = new DatabaseTableDay();
databaseTableDay.setId(cursor.getLong(0));
databaseTableDay.setName(cursor.getString(1));
databaseTableDay.setWeight(cursor.getLong(2));
return databaseTableDay;
}
}
and I try to save it by:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseTableDay databaseTableDay = databaseDAODay.createDay(
editText.getText().toString(), 100f, new Long(myId));
List<DatabaseTableDay> list = databaseDAODay.getAllDays();
}
});
but list is empty anyway.
Probably the problem is createDay() method in DatabaseDAODay because if condition is always null and application doesn' run cursorToDay() method.
I had problem without condition and if there was only cursot.moveToFirst() and then cursorToDay() there was NullPoinerException - because coursor was null. I followed this and put condition !=null but actually nothing happens and List is always empty...
How should I solve my problem?
You are right about the problem being createDay(): instead of inserting a new day by using insert() you try to read from the database by using query()
Change your method like this:
public DatabaseTableDay createDay(String name, float weight, Long id) {
DatabaseTableDay dayToReturn;
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_DAY_NAME, name);
values.put(DatabaseHelper.COLUMN_DAY_WEIGHT, weight);
values.put(DatabaseHelper.COLUMN_DAY_ID, id);
long resID = mDatabase.insert(DatabaseHelper.TABLE_DAYS, null, values);
if (resID == -1)
{
// something went wrong, do error handling here
dayToReturn = null;
}
else
{
// no error: resID is "the row ID of the newly inserted row"
// you only need this info if you are using autoincrement
// not if you set the ID yourself
// all right, this will work -
// but somehow it hurts a little to retrieve an entry I just added.
// I'd like much more to simply use a constructor with all the values
// and create a new DatabaseTableDay instance
dayToReturn = getDayById(id);
}
return dayToReturn;
}
See also this link to documentation for SQLiteDatabase insert()

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);

how to upload and retrieve image using sql in eclipse

I want to have an option for user to upload two images and retrieve image after saved on database, i am new to android programming, I am trying this since four days, googled alot, but could not find out exact solution.
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME
+ " (name,number,skypeId,address) values (?,?,?,?)";
public DataManipulator(Context context) {
DataManipulator.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulator.context);
DataManipulator.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulator.db.compileStatement(INSERT);
}
public long insert(String name, String number, String skypeId,
String address) {
this.insertStmt.bindString(1, name);
this.insertStmt.bindString(2, number);
this.insertStmt.bindString(3, skypeId);
this.insertStmt.bindString(4, address);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id", "name",
"number", "skypeId", "address" }, null, null, null, null,
"name asc");
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public void delete(int rowId) {
db.delete(TABLE_NAME, null, null);
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "
+ TABLE_NAME
+ " (id INTEGER PRIMARY KEY, name TEXT, number TEXT, skypeId TEXT, address TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
my SaveData.java file
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save);
View add = findViewById(R.id.Button01add);
add.setOnClickListener(this);
View home = findViewById(R.id.Button01home);
home.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.Button01home:
Intent i = new Intent(this, DatabaseSample.class);
startActivity(i);
break;
case R.id.Button01add:
View editText1 = (EditText) findViewById(R.id.name);
View editText2 = (EditText) findViewById(R.id.number);
View editText3 = (EditText) findViewById(R.id.skypeId);
View editText4 = (EditText) findViewById(R.id.address);
String myEditText1 = ((TextView) editText1).getText().toString();` `
String myEditText2 = ((TextView) editText2).getText().toString();
String myEditText3 = ((TextView) editText3).getText().toString();
String myEditText4 = ((TextView) editText4).getText().toString();
this.dh = new DataManipulator(this);
this.dh.insert(myEditText1, myEditText2, myEditText3, myEditText4);
showDialog(DIALOG_ID);
break;
}
}
protected final Dialog onCreateDialog(final int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Information saved successfully ! Add Another Info?")
.setCancelable(false)
.setPositiveButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
SaveData.this.finish();
}
})
.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
dialog = alert;
break;
default:
}
return dialog;
}
}
and CheckData.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = name[1] + " - " + name[2] + " - " + name[3] + " - " + name[4];
stg1[x] = stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stg1);
this.setListAdapter(adapter);
selection = (TextView) findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(stg1[position]);
}
}
For saving image in database table you need to convert it to byte array and then you can put it in a contentValue. You can make a method for saving image as shown below-
protected long saveBitmap(SQLiteDatabase database, Bitmap bmp)
{
int size = bmp.getRowBytes() * bmp.getHeight();
ByteBuffer b = ByteBuffer.allocate(size); bmp.copyPixelsToBuffer(b);
byte[] bytes = new byte[size];
b.get(bytes, 0, bytes.length);
ContentValues cv=new ContentValues();
cv.put(CHUNK, bytes);
this.id= database.insert(TABLE, null, cv);
}
For fetching back that record you can do it like this-
byte[] bb = cursor.getBlob(cursor.getColumnIndex(/*Your column index for saving image*/));

Categories