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.
Related
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
Thanks in advance for helping me out. This is my first time working on SQLite Database as well as creating an app.
Problem: When I click save"ImageButton" on the AddEntry.xml for some reason its not displaying on my listview which is located in my Fragment Home.xml. I found fragments to be a tad difficult since you have to change the code around in order for it to work. so please excuse if my code is all over the place.
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener
{
EditText DescriptionET,CalorieET;
ImageButton Savebtn, Cancelbtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry,
container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
descriptionET.setText("");
EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
calorieET.setText("");
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER =
"section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private View v;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home,
container, false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain)getActivity()).loadSelection(1);
}
});
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView)
getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
listview = (ListView) getActivity().findViewById(R.id.listViewDB);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber -
FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new
SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
closeDataBase();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
// Constants & Data
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[]
{KEY_ROWID, KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Thanks again for helping me out. I've been stressing for the last couple of days trying to figure it out.
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);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
i have two classes which i am trying to pass my values in other class for insertion in db, through getters and setters i made but i get the the exception and my application crashes as soon as i click the Save button ..please somebody take a look on it its been three days i cant seem to solve it Thanks
here are my both classes:
/**
* Created by Sanya on 11/22/2015.
*/
public class User_overlay_save extends Activity implements View.OnClickListener
{
private static int RESULT_LOAD_IMAGE = 1;
private static int RESULT_LOAD_VIDEO = 2;
private int position = 0;
private SQLiteDatabase db; DatabaseHelper helper;
File myapp;
private MediaController mediaControls;
Button save_button;
ImageButton vid_button,img_button;
EditText name_overlay;
TextView real_Imgpath, real_Vidpath;
protected void onCreate(Bundle savedInstanceState){
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_overlay_save);
save_button=(Button)findViewById(R.id.save_Ouser);
img_button=(ImageButton)findViewById(R.id.img_button);
vid_button=(ImageButton)findViewById(R.id.vid_button);
real_Imgpath =(TextView)findViewById(R.id.real_Imgpath);
real_Vidpath =(TextView)findViewById(R.id.real_Vidpath);
name_overlay=(EditText)findViewById(R.id.name_overlay);
save_button.setOnClickListener(this);
img_button.setOnClickListener(this);
vid_button.setOnClickListener(this);
name_overlay.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.save_Ouser:
{
boolean result= helper.Insert();
if(result==true)
{
Toast.makeText(getApplicationContext(), "saved..in DB..!!!",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "ERROR--the path could not b saved..!!",
Toast.LENGTH_LONG).show();
}
}
break;
case R.id.img_button:
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
case R.id.vid_button:
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_VIDEO);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String realPath;
//FOR IMAGE PATH SAVING
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
String selectedImagePath;
Uri selectedImageUri = data.getData();
//MEDIA GALLERY
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
Log.i("Image-->File Path-->", " " + selectedImagePath);
setImgTextViews(Build.VERSION.SDK_INT, selectedImagePath);
SET_saveImg(selectedImagePath);
}
else if(Build.VERSION.SDK_INT < 19)
{
realPath = this.getRealPathFromURI_FromAPI11_18(this, data.getData());
setImgTextViews(Build.VERSION.SDK_INT, realPath);
}
//----------->>>>>>>>>>>---------->>>>FOR VIDEO PATH SAVING------>>>>>>------------>>>>>>>>>>>-------->>>>>>>>>---------->>>>
if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK && null != data)
{
//FOR VIDEO PATH SAVING
String selectedVidPath;
Uri selectedVidUri = data.getData();
//VIDEO____PLAY___LIST
selectedVidPath = ImageFilePath.getPath(getApplicationContext(), selectedVidUri);
Log.i("VIDEO-->File Path-->", "" + selectedVidPath);
setVIDTextViews(Build.VERSION.SDK_INT, selectedVidPath);
SET_saveVid(selectedVidPath);
}
}
public String getRealPathFromURI_FromAPI11_18(Context context, Uri contentUri)
{
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
protected void setImgTextViews(int sdk,String realPath){
this.real_Imgpath.setText
("CURRENT VERSION--SDK-->"+sdk+"Real Path: "+realPath);
}
protected void setVIDTextViews(int sdk,String realPath)
{
this.real_Vidpath.setText
("CURRENT VERSION--SDK-->"+sdk+"Real Path: "+realPath);
}
//---->>------>>>------->>>>SETTERS--FOR IMAGE-->SET_saveImg(selectedImagePath) For &VIDEO -->>SET_saveVid(selectedVidPath)--->>AND--->>GETTERS FOR IMAGE AND VIDEO--------->>>>>
String realPath; String vidPath;
public String GET_saveImg()//IS CALLED FROM DATABASE_HELPER CLASS TO PROVIDE THE SETTER VALUES
{
return realPath;
}
protected void SET_saveImg(String realPath)
{
this.realPath=realPath;
}
protected String GET_saveVid()
{
return vidPath;
}
protected void SET_saveVid(String vidPath)
{
this.vidPath= vidPath;
}}
---------------------<<<<<<------------>>>>>>>>>>>>--------- DATABASEHELPER_class
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db; User_overlay_save obj ;
// Database Name
public static String DATABASE_NAME = "MY_database.sql";
// Current version of database
private static final int DATABASE_VERSION = 1;
// Name of table
private static final String TABLE_Images = "images";
// All Keys used in table
static final String KEY_ID = "id";
static final String KEY_IMAGE = "image";
static final String KEY_FILE = "file";
public static String TAG = "tag";
private static final String CREATE_TABLE_Images = "CREATE TABLE "
+ TABLE_Images + "(" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_IMAGE + "TEXT" + KEY_FILE + " TEXT );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/*This method is called by system if the database is accessed but not yet created*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_Images); // create Image table
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_Images);
// drop table if exists
onCreate(db);
}
public boolean Insert()
{ boolean success = false;
String imgpath = obj.GET_saveImg();
String vidPath = obj.GET_saveVid();
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE, imgpath);
values.put(KEY_FILE, vidPath);
db.insert(TABLE_Images, null, values);
success=true;
db.close();
if(success) {
return true;
}
else
{
return false;
}
}
}
Your DatabaseHelper object helper is null. Because you have just declare it, not define anywhere.
put helper = new DatabaseHelper(any arguments if there it is);
inside onCreate before setting onClickListener on save button.
protected void onCreate(Bundle savedInstanceState){
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_overlay_save);
...........................
helper = new DatabaseHelper();
save_button.setOnClickListener(this);
..................
}
Im having trouble getting individual items to delete in a database my application is using. I know the method gets called, but nothing in my list is ever removed. Im not getting any errors which is making it tough to track down. Assistance would be awesome.
public class MainActivity extends Activity{
//Global Variables
ListView lv;
Intent addM, viewM;
public DBAdapter movieDatabase;
String tempTitle, tempYear;
int request_Code = 1;
int request_code2 = 2;
SimpleCursorAdapter dataAdapter;
Cursor cursor;
Button addButton;
long testID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creates the database
movieDatabase = new DBAdapter(this);
movieDatabase.open();
//movieDatabase.deleteAllMovies();
//creates the intents to start the sub activities
addM = new Intent(this, AddMovie.class);
viewM = new Intent(this, MovieView.class);
}
//handles the return of the activity addMovie
public void onActivityResult(int requestCode, int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
switch(requestCode)
{
case 1:
dbAddMovie(data.getStringExtra("title"),
data.getStringExtra("year"));
break;
case 2:
testID = data.getLongExtra("rowid", -1);
dMovie(testID);
break;
}
}
}
//adds item to the movie list
public void dbAddMovie(String mT, String mY)
{
movieDatabase.open();
movieDatabase.insertMovie(mT, mY);
Toast.makeText(this, "Movie: " + mT + " added to database",
Toast.LENGTH_SHORT).show();
}
//deletes an entry into the database
public void dMovie(long rowid)
{
//Toast.makeText(this, "Deleting: " + rowid,
Toast.LENGTH_SHORT).show();
movieDatabase.deleteMovie(rowid);
movieDatabase.getAllMovies();
}
//displays the database as a list
public void displayListView()
{
addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
cursor = movieDatabase.getAllMovies();
//columns to use
String[] columns = new String[]
{
movieDatabase.KEY_TITLE,
};
//xml data to bind the data to
int[] to = new int[]
{
R.id.column2,
};
//adapter to display the database as a list
dataAdapter = new SimpleCursorAdapter(this,
R.layout.complexrow, cursor, columns, to, 0);
//gets the List view resource
lv = (ListView) findViewById(R.id.movielist);
//sets the list view to use the adapter
lv.setAdapter(dataAdapter);
//handles the list click events
lv.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View
v, int position,
long id) {
Cursor cursor = (Cursor)
parent.getItemAtPosition(position);
Bundle mDet = new Bundle();
mDet.putString("title",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_TITLE)));
mDet.putString("year",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_YEAR)));
mDet.putInt("rId", position);
viewM.putExtras(mDet);
startActivityForResult(viewM, 2);
}
});
//dataAdapter.notifyDataSetChanged();
}
public void onResume()
{
super.onResume();
displayListView();
}
}
and my coresponding dbadapter class
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_YEAR = "year";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MovieListDB";
private static final String DATABASE_TABLE = "MoviesTable";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table MoviesTable (_id
integer primary key autoincrement, " +
"title text not null, year not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
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(DATABASE_CREATE);
} 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 MoviesTable");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insertMovie(String title, String year)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_YEAR, year);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "='" + rowID+"'", null ) >-1;
}
public Cursor getAllMovies()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_YEAR}, null, null, null, null, null);
}
public Cursor getMovie(long rowID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_YEAR}, KEY_ROWID + "=" + rowID, null, null, null, null, null);
if(mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateContact(long rowID, String title, String year)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_YEAR, year);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowID, null) > 0;
}
public void deleteAllMovies() {
int doneDelete = 0;
doneDelete = db.delete(DATABASE_TABLE, null, null);
}
}
You're using the position returned from your listview as the row id in your database. This won't necessarily match up with your autoincremented "_id" in your database. position is just what position in the list it is.
You might want to think about using movieDatabase.KEY_ROWID as the key for your intents. Right now I see a mix of "rowid", "rId", "_id", and KEY_ROWID. It would simplify thing to just use the same key everywhere when referring to the same thing.
It looks like you continuously add bundles to the viewM intent. Is that true? If that's not your intent, you should either create a new intent for each click, or remove the previous bundles first.
I'm assuming KEY_ROWID is actually the name of the column? Try the following:
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[] { String.valueOf(rowID) }) >-1;
}