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);
Related
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.
I apologize for conversation.
I am using Google Translator.
I am writing an application that displays text messages with specific numbers.
The numbers stored in the application's user.
*** My problem is that my app does not work on Android 4.4 and above.
Basically what I Should do ? thanks.
My step-by-step program :
Incoming sms:
public class IncomingSms extends BroadcastReceiver {
SmsManager smsManager = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentmessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentmessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentmessage.getDisplayMessageBody();
Log.i("payam", "senderNum=" + senderNum + " | msg=" + message);
DBAdapter db = new DBAdapter(context);
db.open();
List<sh_number> blocknumbers = db.getAllNUMBERItem();
db.close();
for (sh_number thisblocknumber : blocknumbers) {
if (senderNum.equals(thisblocknumber.getnumber())) {
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}
/*if(senderNum.equals("5554")){
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}else {
Toast.makeText(context, "senderNum="+senderNum+" | msg="+message,Toast.LENGTH_LONG).show();
}*/
}
}
}
}
NumberListAdapter :
public class NumberListAdapter extends ArrayAdapter<sh_number> {
List<sh_number> AllNumbers;
Context c;
public NumberListAdapter(Context c, List<sh_number> numbrs){
super(c, android.R.id.content, numbrs);
AllNumbers = numbrs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_number, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getname());
txt = (TextView)convertView.findViewById(R.id.Itm_number);
txt.setText(AllNumbers.get(position).getnumber());
return convertView;
}
MassageListAdapter :
public class MsgListAdapter extends ArrayAdapter<sh_msg> {
List<sh_msg> AllNumbers;
Context c;
public MsgListAdapter(Context c, List<sh_msg> msgs){
super(c, android.R.id.content, msgs);
AllNumbers = msgs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_msg, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getnumber());
txt = (TextView)convertView.findViewById(R.id.Itm_msg);
txt.setText(AllNumbers.get(position).getText());
txt = (TextView)convertView.findViewById(R.id.Itm_date);
txt.setText(AllNumbers.get(position).getDate());
return convertView;
}
Database :
public class DBAdapter {
public static final String DATABASE_NAME = "smsblkrdb";
static final int DATABASE_VERSION = 1;
static final String CREATE_MSGTABLE = "CREATE TABLE msgsTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" numberid integer(128),\n" +
"\"text\" text(128),\n" +
" date text(128)\n" +
");";
public static final String DATABASE_MSGTABLE = "msgsTable";
public static final String KEY_ID = "id";
public static final String KEY_NUMBERID = "numberid";
public static final String KEY_TEXT = "text";
public static final String KEY_DATE = "date";
static final String CREATE_NUMBERSTABLE = "CREATE TABLE numbersTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" name text(128),\n" +
" number text(128)\n" +
");";
public static final String DATABASE_NUMBERSTABLE = "numbersTable";
public static final String KEY_NAME = "name";
public static final String KEY_NUMBER = "number";
public static final String TAG = "EsfanduneLrn";
DatabaseHelper DBHelper;
final Context context;
SQLiteDatabase db;
String yek_Msgnam[] = {
KEY_ID, KEY_NUMBERID, KEY_TEXT, KEY_DATE
};
String yek_Numbernam[] = {
KEY_ID, KEY_NAME, KEY_NUMBER
};
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_MSGTABLE);
db.execSQL(CREATE_NUMBERSTABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_MSGTABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NUMBERSTABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close() {
DBHelper.close();
}
//---insert a contact into the database---
public long insertSH_MSG(sh_msg thisMsg) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisMsg.getId()));
initialValues.put(KEY_NUMBERID, thisMsg.getnumber());
initialValues.put(KEY_TEXT, thisMsg.getText());
initialValues.put(KEY_DATE, thisMsg.getDate());
return db.insert(DATABASE_MSGTABLE, null, initialValues);
}
public long insertSH_NUMBER(sh_number thisNumbr) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisNumbr.getId()));
initialValues.put(KEY_NUMBER, thisNumbr.getnumber());
initialValues.put(KEY_NAME, thisNumbr.getname());
return db.insert(DATABASE_NUMBERSTABLE, null, initialValues);
}
//---retrieves all the contacts---
public List<sh_msg> getAllMSGItem() {
Cursor cursor = db.query(DATABASE_MSGTABLE, yek_Msgnam, null, null, null, null, null);
List<sh_msg> nams = cursorToList_SHMSG(cursor);
cursor.close();
return nams;
}
private List<sh_msg> cursorToList_SHMSG(Cursor cursor) {
List<sh_msg> nams = new ArrayList<sh_msg>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_msg nam = new sh_msg();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setDate(cursor.getString(cursor.getColumnIndex(KEY_DATE)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBERID)));
nam.setText(cursor.getString(cursor.getColumnIndex(KEY_TEXT)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public List<sh_number> getAllNUMBERItem() {
Cursor cursor = db.query(DATABASE_NUMBERSTABLE, yek_Numbernam, null, null, null, null, null);
List<sh_number> nams = cursorToList_SHNUMBER(cursor);
cursor.close();
return nams;
}
private List<sh_number> cursorToList_SHNUMBER(Cursor cursor) {
List<sh_number> nams = new ArrayList<sh_number>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_number nam = new sh_number();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setname(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBER)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public void removeNumber(int numberId) {
db.delete(DATABASE_NUMBERSTABLE, KEY_ID +" == "+numberId,null);
}
I've got two activities. One is updating value in database from edittext and in the second activity i want put this value from database into textview. At the first time when i update value everything goes well but at the second time textview cant be updated and i see in the Textview value "0". When i gave breakpoints i see that my cursor didnt want to take value second time. Any suggestion what should i do ? It's problem with lifecycle of activity or what? There is my code. Any example or suggestion will be very helpful for me.
public class DzienPierwszy extends AppCompatActivity {
Button button;
OpenHelper1 mDb;
TextView pp1,pp2,pp3,s1,s2,s3,p1,p2,p3,pn,sr,pt,nd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.dzien_treningu);
p1 = (TextView) findViewById(R.id.p1);
p2 = (TextView) findViewById(R.id.p2);
p3 = (TextView) findViewById(R.id.p3);
s1 = (TextView) findViewById(R.id.s1);
s2 = (TextView) findViewById(R.id.s2);
s3 = (TextView) findViewById(R.id.s3);
pp1 = (TextView) findViewById(R.id.pp1);
pp2 = (TextView) findViewById(R.id.pp2);
pp3 = (TextView) findViewById(R.id.pp3);
pn = (TextView) findViewById(R.id.pn);
sr = (TextView) findViewById(R.id.sr);
pt = (TextView) findViewById(R.id.pt);
nd = (TextView) findViewById(R.id.nd);
Intent i = getIntent();
final String product = i.getStringExtra("cwiczenie ");
int lol1=0;
mDb = new OpenHelper1(this);
mDb.open();
// fetch data about 1 row in database table
Cursor test = mDb.fetchOneCwiczenie(product);
mDb.close();
if( test != null && test.moveToFirst() ){
//get value from column
lol1 = test.getInt(test.getColumnIndex("score"));
test.close();
}
p1.setText(String.valueOf(Math.round(lol1*0.55)));
p2.setText(String.valueOf(Math.round(lol1*0.79)));
p3.setText(String.valueOf(Math.round(lol1*0.67)));
s1.setText(String.valueOf(Math.round(lol1*0.67)));
s2.setText(String.valueOf(Math.round(lol1*0.91)));
s3.setText(String.valueOf(Math.round(lol1*0.79)));
pp1.setText(String.valueOf(Math.round(lol1*0.79)));
pp2.setText(String.valueOf(Math.round(lol1*1.03)));
pp3.setText(String.valueOf(Math.round(lol1*0.91)));
}
public void open(View view) {
Intent intent = new Intent(getApplicationContext(),TestActivity.class);
startActivity(intent);
}
}
public class OpenHelper1{
private static final String TAG = "TreningDbAdapter";
public DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final ContentResolver resolver =null;
private final Context mCtx;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "menadzerCwiczen1";
public static final String TABLE_CWICZENIA = "cwiczenia";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KIND = "kind";
public static final String KEY_URL = "url";
public static final String KEY_SCORE = "score";
public static final String KEY_SERIES = "series";
static final String PROVIDER_NAME = "com.example.jacek.gympartner.SQLite";
static final String URL = "content://" + PROVIDER_NAME + "/cwiczenia";
static final Uri CONTENT_URI = Uri.parse(URL);
private static HashMap<String, String> CWICZENIA_PROJECTION_MAP;
static final int CWICZENIA = 1;
static final int CWICZENIE_ID = 2;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenie", CWICZENIA);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenia/#", CWICZENIE_ID);
}
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + TABLE_CWICZENIA + " (" +
KEY_ID + " integer PRIMARY KEY autoincrement," +
KEY_NAME + " TEXT," +
KEY_KIND + " TEXT," +
KEY_URL + " TEXT," +
KEY_SCORE + " TEXT," +
KEY_SERIES + " integer" +
");";
/*
#Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
mDb = dbHelper.getWritableDatabase();
return (mDb == null)? false:true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
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;
}
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki','Klatka piersiowa','https://www.youtube.com/watch?v=bwnidT3CB_Q',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki na poręczach','Triceps','https://www.youtube.com/watch?v=Cufsu3IHhCo',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Odwrotne wiosłowanie','Plecy','https://www.youtube.com/watch?v=8qCn76yKhro',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Spięcia brzucha leżąc','Górna część mięśni brzucha','https://www.youtube.com/watch?v=VVcm4LdmIwM',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Unoszenie kolan','Dolna część mięśni brzucha','https://www.youtube.com/watch?v=Htx9Z8ZkiCg',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Skręty tułowia','Mięśnie skośne brzucha','https://www.youtube.com/watch?v=i7smKA3mgBU',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Przysiady','Uda','https://www.youtube.com/watch?v=NEduXlZ8zSk&t',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Wspięcia na palce','Mięśnie łydek','https://www.youtube.com/watch?v=Wri0VppFWCY',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Podciąganie na drążku','Mięśnie łydek','https://www.youtube.com/watch?v=7hM1iriAxx8',0,3)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CWICZENIA);
onCreate(db);
}
}
public OpenHelper1(Context ctx) {
this.mCtx = ctx;
}
public OpenHelper1 open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public OpenHelper1 read() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getReadableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCwiczenie(String name,
String kind,
String url,
int score,
int series) {
mDbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_KIND, kind);
initialValues.put(KEY_URL, url);
initialValues.put(KEY_SCORE, score);
initialValues.put(KEY_SERIES, series);
return mDb.insert(TABLE_CWICZENIA, null, initialValues);
}
public void deleteCwiczenie(String name) {
mDb.execSQL("DELETE FROM " + TABLE_CWICZENIA + " WHERE " + KEY_NAME + "=\"" + name + "\";" );
}
public void updateScore1(Uri uri,String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public void updateScore(String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public boolean deleteAllCwiczenia() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_CWICZENIA, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCwiczeniaByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllcwiczenia() {
Cursor mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchOneCwiczenie(String name) {
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if(c != null) {
c.moveToFirst();
}
return c;
}
public Cursor fetchOneCwiczenie1(Uri uri,String name) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_CWICZENIA);
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if (c != null) {
// c.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI);
}
return c;
}
public void insertSomeCwiczenia() {
createCwiczenie("Pompki","Klatka piersiowa","https://www.youtube.com/watch?v=bwnidT3CB_Q",20,3);
createCwiczenie("Pompki na poręczach","Triceps","https://www.youtube.com/watch?v=Cufsu3IHhCo",0,3);
createCwiczenie("Odwrotne wiosłowanie","Plecy","https://www.youtube.com/watch?v=8qCn76yKhro",0,3);
createCwiczenie("Spięcia brzucha leżąc","Górna część mięśni brzucha","https://www.youtube.com/watch?v=VVcm4LdmIwM",0,3);
createCwiczenie("Unoszenie kolan","Dolna część mięśni brzucha","https://www.youtube.com/watch?v=Htx9Z8ZkiCg",0,3);
createCwiczenie("Skręty tułowia","Mięśnie skośne brzucha","https://www.youtube.com/watch?v=i7smKA3mgBU",0,3);
createCwiczenie("Przysiady","Uda","https://www.youtube.com/watch?v=NEduXlZ8zSk&t",0,3);
createCwiczenie("Wspięcia na palce","Mięśnie łydek","https://www.youtube.com/watch?v=Wri0VppFWCY",0,3);
createCwiczenie("Podciąganie na drążku","Mięśnie łydek","https://www.youtube.com/watch?v=7hM1iriAxx8",0,3);
}
}
public class TestActivity extends AppCompatActivity {
TextView textView;
EditText editText;
Button button,button1;
OpenHelper1 mDb;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test_layout);
textView = (TextView) findViewById(R.id.polecenie);
editText = (EditText) findViewById(R.id.wartosc);
button = (Button) findViewById(R.id.treningactivity);
button1 = (Button) findViewById(R.id.zapisz);
//button2 = (Button) findViewById(R.id.button);
mDb = new OpenHelper1(this);
Intent i = getIntent();
// getting attached intent data
final String product = i.getStringExtra("cwiczenie ");
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int wynik = Integer.parseInt(editText.getText().toString());
mDb.open();
mDb.updateScore(product,wynik);
mDb.close();
}
});
/*
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDb.open();
Cursor t = mDb.fetchOneCwiczenie(product);
int c = t.getInt(t.getColumnIndex("score"));
String k = Integer.toString(c);
textView1.setText(k);
mDb.close();
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext().getApplicationContext(), DzienPierwszy.class);
i.putExtra("cwiczenie ", product);
startActivity(i);
}
});
}
}
There are more than couple of things that you need to do -
In your content provider, you need to attach a notification Uri before the Cursor is being returned to client (in this case your Activity). The code would look something like this (Here the Authority URI need to be changed as per your provider) -
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(),ContactsContract.AUTHORITY_URI);
}
return c;
Every time there is a update in data, the following line needs to be called -
getContext().getContentResolver().notifyChange(ContactsContract.AUTHORITY_URI, null,
syncToNetwork);
Basically what point 1 & 2 does is that it notifies the underlying data layer that there is currently a client with an active cursor and needs to be notified if there is a change in the underlying data. If you are using any of the inbuilt data providers in Android like ContactsProvider/SmsProvider to read contacts/SMS data, point 1 &2 would have been taken care.
ContactsProvider
And on your activity code you need to do something like
cursor.registerContentObserver(mChangeObserver). If you instead use a Cursor adapter which wraps around your cursor, then this would have been taken care. Have a look at the Cursor Adapter source code -
CursorAdapter Sample
I am trying to create diary where the user saves some text and an image.
I have managed to save the text (title and body) however i am a beginner so i am unsure how to save the image ,can someone help? this is my code, i have created notes where i tried to get the image in the code but i dont know how to make it work
ActivityDiaryEdit.java:
public class ActivityDiaryEdit extends Activity {
private static final int RESULT_LOAD_IMAGE =1;
private EditText mTitleText;
private EditText mBodyText;
private ImageView mImage; //image
private Long mRowId;
private DiaryDbAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new DiaryDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.diary_edit);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mImage = (ImageView) findViewById(R.id.imageView1); //image
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(DiaryDbAdapter.KEY_TITLE);
String body = extras.getString(DiaryDbAdapter.KEY_BODY);
mRowId = extras.getLong(DiaryDbAdapter.KEY_ROWID);
if (title != null) {
mTitleText.setText(title);
}
if (body != null) {
mBodyText.setText(body);
}
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
Bitmap image =((BitmapDrawable)mImage.getDrawable()).getBitmap(); //image
if (mRowId != null) {
mDbHelper.updateDiary(mRowId, title, body , image); //add image?
} else
mDbHelper.createDiary(title, body , image);
Intent mIntent = new Intent();
setResult(RESULT_OK, mIntent);
finish();
}
});
}
public void onClick(View v){
switch(v.getId()) {
case R.id.imageView1: //when the imageup is clicked the following will happen
Intent galleryIntent = new Intent (Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,RESULT_LOAD_IMAGE);
break;
case R.id.confirm:
Bitmap image =((BitmapDrawable)mImage.getDrawable()).getBitmap(); //holds the image
break;
}
}
#Override
protected void onActivityResult(int requestCode , int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data !=null){
Bitmap bmp =(Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(bmp);
mImage.requestFocus();
ByteArrayOutputStream boas = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, boas);
byte [] b =boas.toByteArray();
String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray= Base64.decode(encodedImageString, Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
Uri selectedImage =data.getData();
mImage.setImageURI(selectedImage);
}
}
private class UploadImage extends AsyncTask<Void,Void ,Void >{
Bitmap image;
String name;
public UploadImage(Bitmap image,String name){
this.image = image;
this.name = name;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT); //encoding the image-String representation of the image
ArrayList<NameValuePair>dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("image", encodedImage));
dataToSend.add(new BasicNameValuePair("name",name));
return null;
}
}
DiaryDbAdapter.java:
class DiaryDbAdapter {
public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_ROWID = "_id";
public static final String KEY_CREATED = "created";
public static final String KEY_IMAGE = "image"; //image
private static final String TABLE_CONTACTS = "contacts";
private static final String TAG = "DiaryDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE = "create table diary (_id integer primary key autoincrement, "
+ "title text not null, body text not null, created text not null);";
private static final String DATABASE_NAME = "database";
private static final String DATABASE_TABLE = "diary";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS diary");
onCreate(db);
}
}
public DiaryDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public DiaryDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void closeclose() {
mDbHelper.close();
}
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
} //for image
public long createDiary(String title, String body , Bitmap image) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
// initialValues.put(KEY_IMAGE, image); //how to put image?
Calendar calendar = Calendar.getInstance();
String created = calendar.get(Calendar.YEAR) + ""
+ calendar.get(Calendar.MONTH) + ""
+ calendar.get(Calendar.DAY_OF_MONTH) + ""
+ calendar.get(Calendar.HOUR_OF_DAY) + ""
+ calendar.get(Calendar.MINUTE) + "";
initialValues.put(KEY_CREATED, created);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteDiary(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor getAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_CREATED ,KEY_IMAGE}, null, null, null, null, null);
}
public Cursor getDiary(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_CREATED , KEY_IMAGE }, KEY_ROWID + "=" + rowId, null, null,
null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateDiary(long rowId, String title, String body , Bitmap image) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
//args.put(KEY_IMAGE, image); //how to put image?
Calendar calendar = Calendar.getInstance();
String created = calendar.get(Calendar.YEAR) + ""
+ calendar.get(Calendar.MONTH) + ""
+ calendar.get(Calendar.DAY_OF_MONTH) + ""
+ calendar.get(Calendar.HOUR_OF_DAY) + ""
+ calendar.get(Calendar.MINUTE) + "";
args.put(KEY_CREATED, created);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
MainActivity.java:
public class MainActivity extends ListActivity {
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private DiaryDbAdapter mDbHelper;
private Cursor mDiaryCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diary_list);
mDbHelper = new DiaryDbAdapter(this);
mDbHelper.open();
renderListView();
}
private void renderListView() {
mDiaryCursor = mDbHelper.getAllNotes();
startManagingCursor(mDiaryCursor);
String[] from = new String[] { DiaryDbAdapter.KEY_TITLE,
DiaryDbAdapter.KEY_CREATED , }; //DiaryAdapter KEY_IMAGE ??
int[] to = new int[] { R.id.text1, R.id.created , R.id.imageView1 };
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.diary_now, mDiaryCursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case INSERT_ID:
createDiary();
return true;
case DELETE_ID:
mDbHelper.deleteDiary(getListView().getSelectedItemId());
renderListView();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createDiary() {
Intent i = new Intent(this, ActivityDiaryEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) { // from activity edit and diaryDb
super.onListItemClick(l, v, position, id);
Cursor c = mDiaryCursor;
c.moveToPosition(position);
Intent i = new Intent(this, ActivityDiaryEdit.class);
i.putExtra(DiaryDbAdapter.KEY_ROWID, id);
i.putExtra(DiaryDbAdapter.KEY_TITLE, c.getString(c
.getColumnIndexOrThrow(DiaryDbAdapter.KEY_TITLE)));
i.putExtra(DiaryDbAdapter.KEY_BODY, c.getString(c
.getColumnIndexOrThrow(DiaryDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
// i.putExtra(DiaryAdapter.KEY_IMAGE, c.getString(c
// .getColumnIndexOrThrow(DiaryAdapter.KEY_IMAGE))); image??
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
renderListView();
}
}
To store images inside Sqlite use Blob(Binary large object)
Retrieve bytes array from a bitmap compressed as PNG:
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, stream);
return stream.toByteArray();
}
On SqlStatement use bindBlob to insert an image. More info about this
For retrieval use cursor.getBlob(index) and decode blob to Bitmap:
public static Bitmap getImage(byte[] image)
{
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
If would recommend saving images as files instead of using Sqlite for that. Android developers has nice article about it.
I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview.
Now I want to delete values by position (for example, if i click listview's 4th item i would to delete full this items)
This is my code:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
My Adapter Code:
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and my Main Java code:
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
int a;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
a = Integer.parseInt(holder.counter.getText().toString());
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
dbHelper.close();
cAdapter.notifyDataSetChanged();
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
cAdapter.notifyDataSetChanged();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
I found one example about how to delete title but it's not working.
How could I delete user by position in listview 'onclick' listener?
Any help would be great, thanks
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
You'll need to use the table name here, if all else is correct.