I have made an app that lets the user add location through place picker and add them into the SQLite database.I am displaying these locations in recyclerview. In order to delete an item from recyclerview, this is what I have done so far.
1) User long presses on an item in recyclerview and then alert dialogue appears with 2 buttons (Delete and Cancel).
What I can't-do:
1) Now I don't know how to delete an item from recyclerview and from SQLite database when the user taps on the delete button.
I have searched for it but don't how it can be implemented. I am posting the code for MainActivity.java class, PlaceDbhelper.java class, and PlacelistAdapter.java class.
MainActivity.java class
public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener {
// Constants
public static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final int PLACE_PICKER_REQUEST = 1;
// Member variables
private PlaceListAdapter mAdapter;
private RecyclerView mRecyclerView;
private boolean mIsEnabled;
private GoogleApiClient mClient;
private Geofencing mGeofencing;
//String arr;
/**
* Called when the activity is starting
*
* #param savedInstanceState The Bundle that contains the data supplied in onSaveInstanceState
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the recycler view
mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlaceListAdapter(this, null);
mRecyclerView=(RecyclerView)findViewById(R.id.places_list_recycler_view);
mRecyclerView.setAdapter(mAdapter);
Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch);
mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled), false);
onOffSwitch.setChecked(mIsEnabled);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putBoolean(getString(R.string.setting_enabled), isChecked);
mIsEnabled = isChecked;
editor.commit();
if (isChecked) mGeofencing.registerAllGeofences();
else mGeofencing.unRegisterAllGeofences();
}
});
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.build();
mGeofencing = new Geofencing(this, mClient);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
mRecyclerView, new ClickListener() {
public void onClick(View view, final int position) {
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*/
}
public void onItemClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
final AlertDialog alertDialog =new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Are you want to delete this");
alertDialog.setCancelable(false);
alertDialog.setMessage("By deleting this, item will permanently be deleted. Are you still want to delete this?");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
Toast.makeText(MainActivity.this, "Long press on position :"+position,
Toast.LENGTH_LONG).show();
}
}));
}
/***
* Called when the Google API Client is successfully connected
*
* #param connectionHint Bundle of data provided to clients by Google Play services
*/
#Override
public void onConnected(#Nullable Bundle connectionHint) {
refreshPlacesData();
Log.i(TAG, "API Client Connection Successful!");
}
/***
* Called when the Google API Client is suspended
*
* #param cause cause The reason for the disconnection. Defined by constants CAUSE_*.
*/
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "API Client Connection Suspended!");
}
/***
* Called when the Google API Client failed to connect to Google Play Services
*
* #param result A ConnectionResult that can be used for resolving the error
*/
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.e(TAG, "API Client Connection Failed!");
}
public void refreshPlacesData() {
Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
Cursor data = getContentResolver().query(
uri,
null,
null,
null,
null);
if (data == null || data.getCount() == 0) return;
List<String> guids = new ArrayList<String>();
while (data.moveToNext()) {
guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID)));
}
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient,
guids.toArray(new String[guids.size()]));
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
mAdapter.swapPlaces(places);
mGeofencing.updateGeofencesList(places);
if (mIsEnabled) mGeofencing.registerAllGeofences();
}
});
}
public void onAddPlaceButtonClicked(View view) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_LONG).show();
return;
}
try {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Intent i = builder.build(this);
startActivityForResult(i, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
} catch (Exception e) {
Log.e(TAG, String.format("PlacePicker Exception: %s", e.getMessage()));
}
}
/***
* Called when the Place Picker Activity returns back with a selected place (or after canceling)
*
* #param requestCode The request code passed when calling startActivityForResult
* #param resultCode The result code specified by the second activity
* #param data The Intent that carries the result data.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
if (place == null) {
Log.i(TAG, "No place selected");
return;
}
String placeID = place.getId();
// Insert a new place into DB
ContentValues contentValues = new ContentValues();
contentValues.put(PlaceContract.PlaceEntry.COLUMN_PLACE_ID, placeID);
getContentResolver().insert(PlaceContract.PlaceEntry.CONTENT_URI, contentValues);
// Get live data information
refreshPlacesData();
}
}
#Override
public void onResume() {
super.onResume();
// Initialize location permissions checkbox
CheckBox locationPermissions = (CheckBox) findViewById(R.id.location_permission_checkbox);
if (ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
locationPermissions.setChecked(false);
} else {
locationPermissions.setChecked(true);
locationPermissions.setEnabled(false);
}
// Initialize ringer permissions checkbox
CheckBox ringerPermissions = (CheckBox) findViewById(R.id.ringer_permissions_checkbox);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Check if the API supports such permission change and check if permission is granted
if (android.os.Build.VERSION.SDK_INT >= 24 && !nm.isNotificationPolicyAccessGranted()) {
ringerPermissions.setChecked(false);
} else {
ringerPermissions.setChecked(true);
ringerPermissions.setEnabled(false);
}
}
public void onRingerPermissionsClicked(View view) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
public void onLocationPermissionClicked(View view) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_FINE_LOCATION);
}
public static interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
PlaceDbhelper.java class
public class PlaceDbHelper extends SQLiteOpenHelper {
// The database name
private static final String DATABASE_NAME = "location.db";
PlaceListAdapter obj1;
// If you change the database schema, you must increment the database version
private static final int DATABASE_VERSION = 1;
// Constructor
public PlaceDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create a table to hold the places data
final String SQL_CREATE_PLACES_TABLE = "CREATE TABLE " + PlaceEntry.TABLE_NAME + " (" +
PlaceEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
PlaceEntry.COLUMN_PLACE_ID + " TEXT NOT NULL, " +
"UNIQUE (" + PlaceEntry.COLUMN_PLACE_ID + ") ON CONFLICT REPLACE" +
"); ";
sqLiteDatabase.execSQL(SQL_CREATE_PLACES_TABLE);
}
String pe=PlaceEntry._ID.toString();
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// For now simply drop the table and create a new one.
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + PlaceEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
PlacelistAdapter.java class
public class PlaceListAdapter extends
RecyclerView.Adapter<PlaceListAdapter.PlaceViewHolder> {
private Context mContext;
private PlaceBuffer mPlaces;
PlaceDbHelper obj1;
RecyclerView recycleview;
public PlaceListAdapter(Context context, PlaceBuffer places) {
this.mContext = context;
this.mPlaces = places;
}
#Override
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Get the RecyclerView item layout
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.item_place_card, parent, false);
//final Activity activity;
return new PlaceViewHolder(view);
}
#Override
public void onBindViewHolder(PlaceViewHolder holder, int position) {
String placeName = mPlaces.get(position).getName().toString();
String placeAddress = mPlaces.get(position).getAddress().toString();
holder.nameTextView.setText(placeName);
holder.addressTextView.setText(placeAddress);
}
public void swapPlaces(PlaceBuffer newPlaces) {
mPlaces = newPlaces;
if (mPlaces != null) {
// Force the RecyclerView to refresh
this.notifyDataSetChanged();
}
}
#Override
public int getItemCount() {
if (mPlaces == null) return 0;
return mPlaces.getCount();
}
/**
* PlaceViewHolder class for the recycler view item
*/
class PlaceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
public PlaceViewHolder(final View itemView) {
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.name_text_view);
addressTextView = (TextView) itemView.findViewById(R.id.address_text_view);
}
#Override
public void onClick(View v) {
}
I have solution for you, you need to delete row from db and then remove from your arraylist and after it notify you adapter. like below.
Use this method in your PlaceDbhelper.java class
public void removePlace(String placeId){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(PlaceEntry.TABLE_NAME, PlaceEntry.COLUMN_PLACE_ID + "=\"" + placeId+"\"", null) ;
}
now call this method in alert when click DELETE
private void deletePlace(int position){
PlaceDbhelper dbHelper = new PlaceDbhelper(MainActivity.this);
dbHelper.removePlace(placeArraylist.get(position).getPlaceId());
placeArraylist.remove(position);
mAdapter.notifyDataSetChanged();
}
Hope this will help you, If this solve your problem make it approved. Ask if you need help.
Related
**Main Activity.java**
This is main activity where I instantiate all methods/objects. Here I use Dexter library to grab files from user's external storage, then I made one method called find songs which helps in finding the path of files and list them accordingly. Then I made another method called display songs which will help in getting the whole size of songs and then display the whole list with their names accordingly. Then with the help of custom adapter I passed my list of songs which is in array named item.
public class MainActivity extends AppCompatActivity {
ListView listView;
String [] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission(){
Dexter.withContext(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest
.permissi
on.RECORD_AUDIO)
.withListener(new MultiplePermissionsListener() {
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
public void
onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport)
{
displaySongs();
}
#Override
public void
onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file){
ArrayList arrayList = new ArrayList();
Log.d(TAG, "findSong:"+ file.getPath());
File [] files = file.listFiles();
if (files!=null) {
Log.d(TAG, "findSong:"+ files.length);
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") &&
!singleFile.getName().startsWith(".")) {
arrayList.add(singleFile);
}
}
}
}
return arrayList;
}
public void displaySongs(){
ArrayList<File> mySongs =
findSong(Environment.getExternalStorageDirectory());
String [] items = new String [mySongs.size()];
if(mySongs == null)return; // this is very important function
otherwise app will crash
for (int i=0; i<mySongs.size(); i++){
items[i] = mySongs.get(i).getName().replace(".mp3",
"");
}
Log.d(TAG, "displaySongs:"+ items.length);
(this,
android.R.layout.simple_list_item_1,items);
CustomAdapter customAdapter = new CustomAdapter(this,
Arrays.asList(items));
Log.d(TAG, "displaySongs:"+ customAdapter.getCount());
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String currentSong = (String)
listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),
PlayerActivity.class)
.putExtra("currentSong", currentSong)
.putExtra("position",position)
.putExtra("songs",mySongs));
}
});
}
class CustomAdapter extends ArrayAdapter {
public android.util.Log Log;
List<String> names;
LayoutInflater inflater;
Context context;
public CustomAdapter(Context context, List<String> names) {
super(context,R.layout.list_item ,names);
this.names=names;
this.context=context;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
inflater=LayoutInflater.from(getContext()); //inflater is
responsible for taking your xml files that defines your layout
// and converting them into view objects.
View
customview=inflater.inflate(R.layout.list_item,parent,false);
String data=names.get(position);
//String data1=names.get(position+1);
TextView tv=
(TextView)customview.findViewById(R.id.textsongname);
tv.setText(data);
tv.setSelected(true);
//TextView tv1=(TextView)customview.findViewById(R.id.TeamB);
//tv1.setText(data1);
return customview;
}
}
}
**PlayerActivity.java**
I tried to make a Thread named update seek bar which will update my seek bar to current position after that I applied set on click bar change listener so that whenever user update position of sidebar it should get updated. But error here is that when I run my app using this code on emulator its working completely fine but when installed in my phone 2 errors are coming. One after completion of song its not jumping automatically to the next song and second when user update sidebar and press next, sidebar is not coming to position 0, and this whole error is showing on my phone not in emulator.
public class PlayerActivity extends AppCompatActivity {
Button play,next,fastforward, previous, fastrewind;
TextView txtsn, txtsstart, txtsstop;
SeekBar seekBar;
BarVisualizer visualizer;
Thread updateSeekBar;
String sName;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs;
ImageView imageView;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (visualizer != null){
visualizer.release();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
fastforward = findViewById(R.id.fastforward);
fastrewind = findViewById(R.id.fastrewind);
txtsn = findViewById(R.id.txtsn);
txtsstart = findViewById(R.id.txtsstart);
txtsstop = findViewById(R.id.txtsstop);
seekBar = findViewById(R.id.seekbar);
visualizer = findViewById(R.id.blast);
imageView = findViewById(R.id.iamgeView);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
sName = intent.getStringExtra("currentSong");
position = bundle.getInt("position",0);
txtsn.setText(sName);
txtsn.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString()); // uri is
usually use tell a content provider what we want to access by
reference
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
updateSeekBar = new Thread(){
#Override
public void run() {
int currentPosition = 0;
while (currentPosition<mediaPlayer.getDuration()){
try {
currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
sleep(500);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
updateSeekBar.start();
seekBar.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtsstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime =
createTime(mediaPlayer.getCurrentPosition());
txtsstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
play.setBackgroundResource(R.drawable.ic_play);
mediaPlayer.pause();
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=mySongs.size()-1){
position = position + 1;
}
else{
position = 0;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.performClick();
}
});
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=0){
position = position - 1;
}
else{
position = mySongs.size() - 1;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
fastforward.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+1000);
}
}
});
fastrewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-1000);
}
}
});
}
private boolean isPermissionGranted(){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}
else {
int readExternalStoragePermission =
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
return readExternalStoragePermission ==
PackageManager.PERMISSION_GRANTED;
}
}
public void startAnimation(View view){
ObjectAnimator animator =
ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
animator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animator);
animatorSet.start();
}
public String createTime(int duration) {
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10) {
time+="0";
}
time+=sec;
return time;
}
}
i have a problem and my problem is : when i kill the app or shutting down the device , all the information was erased and i can find it , first of all and what i want to do in the first place is: i want to check if this is the first time of the user to use this app or not , if that is the first time then save what he chosen in the sharedPreference xml and if not , then retrieve was chosen and show it , sorry for my bad english , it's not my mother tongue
this is the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quran);
readers= (CardView)findViewById(R.id.readers);
readers_name=(TextView)findViewById(R.id.readers_name);
rewaya=(TextView)findViewById(R.id.rewaya);
count=(TextView)findViewById(R.id.count);
Intent i = getIntent();
String txtData = i.getStringExtra("reciters_name");
String txtData1 = i.getStringExtra("reciters_rewaya");
String txtData2 = i.getStringExtra("reciters_count");
shareRef=getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor myedit = shareRef.edit();
boolean firstRun = shareRef.getBoolean("firstRun", true);
if(firstRun) {
myedit.clear();
myedit.putString("reciters", txtData);
myedit.putBoolean("firstRun", false);
myedit.putString("rewaya", txtData1);
myedit.putString("count", txtData2);
myedit.commit();
readers_name.setText(txtData);
rewaya.setText(txtData1);
count.setText(txtData2);
}else {
readers_name.setText(shareRef.getString("reciters", ""));
rewaya.setText(shareRef.getString("rewaya", ""));
count.setText(shareRef.getString("count", ""));
}
fav_suras=(RecyclerView)findViewById(R.id.fav_suras);
fav_suras.setLayoutManager(new LinearLayoutManager(this));
suras=(RecyclerView)findViewById(R.id.suras);
suras.setHasFixedSize(true);
suras.setLayoutManager(new LinearLayoutManager(this));
suras.setAdapter(Mquraan_adapter);
//mSuras_api = new ArrayList<>();
getRetrofit();
readers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (quran.this, Readers.class);
startActivity(intent);
}
});
}
public void getRetrofit() {
RequestInterface requestInterface = PostClient.getApiClient().create(RequestInterface.class);
Call<FomCombine> call = requestInterface.getPosts();
call.enqueue(new Callback <FomCombine>() {
#Override
public void onResponse(Call<FomCombine> call, retrofit2.Response <FomCombine> response) {
Toast.makeText(quran.this, "success", Toast.LENGTH_SHORT).show();
mSuras_api = response.body().getfom_combine();
Mquraan_adapter= new quran_adapter(quran.this, (ArrayList<suras_api>) mSuras_api);
suras.setAdapter(Mquraan_adapter);
Mquraan_adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<FomCombine> call, Throwable t) {
Log.d("Tag", t.getMessage());
}
});
}}
this is the adapter
private Context mContext ;
private ArrayList<Reciters_api> mReciters_api;
public Reciters_adapter(Context context, ArrayList<Reciters_api> mmReciters_api) {
mContext=context;
mReciters_api=mmReciters_api;
}
#NonNull
#Override
public Reciters_adapter.ReadersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.single_row,parent,false);
return new ReadersViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ReadersViewHolder holder, int position) {
Reciters_api reciters = mReciters_api.get(position);
String ID_number = reciters.getId1();
String Name =reciters.getName1();
String Rewaya = reciters.getRewaya();
String count =reciters.getCount();
holder.readers_names.setText(Name);
holder.countt.setText(count);
holder.rewayya.setText(Rewaya);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent Reciters = new Intent(context, quran.class);
Reciters.putExtra("reciters_name", Name);
Reciters.putExtra("reciters_rewaya", Rewaya);
Reciters.putExtra("reciters_count", count);
context.startActivity(Reciters);
}
});
}
#Override
public int getItemCount() {
return mReciters_api.size();
}
public class ReadersViewHolder extends RecyclerView.ViewHolder{
public TextView readers_names ,rewayya ,countt;
public ReadersViewHolder(#NonNull View itemView) {
super(itemView);
readers_names=itemView.findViewById(R.id.readers_names);
rewayya=itemView.findViewById(R.id.rewayya);
countt=itemView.findViewById(R.id.countt);
}
}
}
I've recently learned of ListAdapter and applied to my RecyclerView. I followed a tutorial and the list of items (retrieved from a database via Retrofit) is displayed as expected. However, when I add a new item the list does not update unless I leave the activity and return. What am I missing here?
ViewModel
public class NoteViewModel extends ViewModel {
private static final String TAG = "NoteViewModel";
MutableLiveData<List<Note>> mutableLiveData;
public LiveData<List<Note>> getNoteList(String userID) {
if (mutableLiveData == null) {
mutableLiveData = new MutableLiveData<>();
}
initNoteList(userID);
return mutableLiveData;
}
private void initNoteList(String userID) {
List<Note> noteList = new ArrayList<>();
Call<List<Note>> noteCall = APIClient.getUserService().retrieveUserNotes(userID);
noteCall.enqueue(new Callback<List<Note>>() {
#Override
public void onResponse(Call<List<Note>> call, Response<List<Note>> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
noteList.addAll(response.body());
mutableLiveData.setValue(noteList);
Log.d(TAG, "onResponse: " + noteList.size());
} else {
Log.d(TAG, "onResponse: Retrieve Note List Body Error");
}
} else {
Log.d(TAG, "onResponse: Response Fail");
}
}
#Override
public void onFailure(Call<List<Note>> call, Throwable t) {
Log.d(TAG, "onFailure: Retrieve Note List Failure: " + t.getMessage());
}
});
}
ListAdapter
public class NoteListAdapter extends ListAdapter<Note, NoteListAdapter.NoteViewHolder> {
NoteClickListener noteClickListener;
public NoteListAdapter(#NonNull DiffUtil.ItemCallback<Note> diffCallback, NoteClickListener noteClickListener) {
super(diffCallback);
this.noteClickListener = noteClickListener;
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_item, parent, false);
return new NoteViewHolder(v, noteClickListener);
}
#Override
public void onBindViewHolder(#NonNull NoteViewHolder holder, int position) {
Note note = getItem(position);
assert note != null;
holder.bind(note);
}
public static class NoteViewHolder extends RecyclerView.ViewHolder {
NoteClickListener noteClickListener;
TextView noteTitle;
public NoteViewHolder(View itemView, NoteClickListener noteClickListener) {
super(itemView);
this.noteClickListener = noteClickListener;
noteTitle = itemView.findViewById(R.id.note_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
noteClickListener.onNoteClick(getAbsoluteAdapterPosition());
}
});
public void bind(Note note) {
noteTitle.setText(note.getTitle());
}
}
public interface NoteClickListener {
void onNoteClick(int position);
void onNoteLongClick(int position);
}
Activity
public class NotesList extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
Toolbar toolbar;
FloatingActionButton addNote, deleteNote;
User user;
NoteListAdapter noteListAdapter;
NoteViewModel noteViewModel;
private static final int EDIT_NOTE = 10001;
private static final int SAVE_NOTE = 10002;
private boolean reloadNotes = false;
List<Note> noteList;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes_list);
Intent notes = getIntent();
user = (User) notes.getParcelableExtra("user");
addNote = findViewById(R.id.fab_notes);
deleteNote = findViewById(R.id.delete_notes);
deleteNote.setVisibility(View.GONE);
toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_24);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotesList.this.onBackPressed();
}
});
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
addNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newNote = new Intent(NotesList.this, CreateUserNote.class);
newNote.putExtra("user", user);
NotesList.this.startActivity(newNote);
}
});
recyclerView = findViewById(R.id.notesRecyclerView);
noteListAdapter = new NoteListAdapter(Note.itemCallback, new NoteListAdapter.NoteClickListener() {
#Override
public void onNoteClick(int position) {
// TODO: Edit Note
Toast.makeText(NotesList.this, noteListAdapter.getCurrentList().get(position).getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNoteLongClick(int position) {
// TODO: Delete Note
}
});
recyclerView.setAdapter(noteListAdapter);
noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
noteViewModel.getNoteList(user.getUser_id()).observe(NotesList.this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
noteListAdapter.submitList(notes);
}
});
}
I found a workaround which is to call submitList() in onActivityResult() after adding a new item. However, I would like to know if this is good programming.
Here is what I added:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SAVE_NOTE) {
if (resultCode == CreateUserNote.RESULT_OK) {
noteListAdapter.submitList(noteViewModel.getNoteList(user.getUser_id()).getValue());
}
}
}
Changed the following:
addNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newNote = new Intent(NotesList.this, CreateUserNote.class);
newNote.putExtra("user", user);
NotesList.this.startActivityForResult(newNote, SAVE_NOTE);
}
});
Create new item activity retrofit call:
private void saveNote(String user_id, String title, String content) {
Call<String> noteCall = APIClient.getUserService().addUserNote(user_id, title, content);
noteCall.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
if (response.body().equals("true")) {
setResult(CreateUserNote.RESULT_OK);
finish();
} else {
Toast.makeText(CreateUserNote.this, "Save User Note Failure", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(CreateUserNote.this, "Save User Note Failure: " + t.getMessage(), Toast.LENGTH_SHORT).show();
Log.w("Error", "Save User Note Failure: " + t.getMessage());
}
});
}
building an Android App using Room DB. I've uninstalled the app various times but always seem to get the same entry as i re-install it.
I can't seem to reach the onCreate part of the RoomDatabase.Callback as I'm trying to add some dummy entries and log some info to the logs.
public class MainActivity extends AppCompatActivity {
private ContactsAdapter contactsAdapter;
private ArrayList<Contact> contactArrayList = new ArrayList<>();
private RecyclerView recyclerView;
private ContactsAppDatabase contactsAppDatabase;
private static final String TAG="MainActivityTag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" Contacts Manager ");
recyclerView = findViewById(R.id.recycler_view_contacts);
contactsAppDatabase= Room.databaseBuilder(getApplicationContext(),ContactsAppDatabase.class,"ContactDB")
.addCallback(callback)
.build();
new GetAllContactsAsyncTask().execute();
contactsAdapter = new ContactsAdapter(this, contactArrayList, MainActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(contactsAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addAndEditContacts(false, null, -1);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addAndEditContacts(final boolean isUpdate, final Contact contact, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = layoutInflaterAndroid.inflate(R.layout.layout_add_contact, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilderUserInput.setView(view);
TextView contactTitle = view.findViewById(R.id.new_contact_title);
final EditText newContact = view.findViewById(R.id.name);
final EditText contactEmail = view.findViewById(R.id.email);
contactTitle.setText(!isUpdate ? "Add New Contact" : "Edit Contact");
if (isUpdate && contact != null) {
newContact.setText(contact.getName());
contactEmail.setText(contact.getEmail());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(isUpdate ? "Update" : "Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
if (isUpdate) {
deleteContact(contact, position);
} else {
dialogBox.cancel();
}
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(newContact.getText().toString())) {
Toast.makeText(MainActivity.this, "Enter contact name!", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
if (isUpdate && contact != null) {
updateContact(newContact.getText().toString(), contactEmail.getText().toString(), position);
} else {
createContact(newContact.getText().toString(), contactEmail.getText().toString());
}
}
});
}
private void deleteContact(Contact contact, int position) {
contactArrayList.remove(position);
new DeleteContactAsyncTask().execute(contact);
}
private void updateContact(String name, String email, int position) {
Contact contact = contactArrayList.get(position);
contact.setName(name);
contact.setEmail(email);
new UpdateContactAsyncTask().execute(contact);
contactArrayList.set(position, contact);
}
private void createContact(String name, String email) {
new CreateContactAsyncTask().execute(new Contact(0,name,email));
}
private class GetAllContactsAsyncTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
contactArrayList.addAll(contactsAppDatabase.getContactDAO().getContacts());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
private class CreateContactAsyncTask extends AsyncTask<Contact,Void,Void>{
#Override
protected Void doInBackground(Contact... contacts) {
long id = contactsAppDatabase.getContactDAO().addContact(contacts[0]);
Contact contact = contactsAppDatabase.getContactDAO().getContact(id);
if (contact != null) {
contactArrayList.add(0, contact);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
private class UpdateContactAsyncTask extends AsyncTask<Contact,Void,Void>{
#Override
protected Void doInBackground(Contact... contacts) {
contactsAppDatabase.getContactDAO().updateContact(contacts[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
private class DeleteContactAsyncTask extends AsyncTask<Contact,Void,Void>{
#Override
protected Void doInBackground(Contact... contacts) {
contactsAppDatabase.getContactDAO().deleteContact(contacts[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
RoomDatabase.Callback callback = new RoomDatabase.Callback() {
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
//Toast.makeText(getApplicationContext()," On Create Called ",Toast.LENGTH_LONG).show();
Log.i(TAG, " on create invoked ");
createContact("name 1","email 1");
createContact("name 2","email 2");
createContact("name 3","email 3");
}
#Override
public void onOpen(#NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
// Toast.makeText(getApplicationContext()," On Create Called ",Toast.LENGTH_LONG).show();
Log.i(TAG, " on open invoked ");
}
};
}
I've added write/ read external storage in the manifest unsure if thats important.
Things is onOpen gets invoked from within the callback so it seems a little weird.
github repo
when I install the app onanother device it works fine. obviously on the other (the first) device I still get the error even after deleting and reinstalling the app.
Please help.
i was trying to use intent pass data from MainActivity class down below
to DBManager class, but i've failed at the moment.
so please tell me how if there is anyway to use intent data from another class
i will appreaciate it.
public class MainActivity extends Activity{
private ViewPager mPager;
private DBManager dbManager;
private DatePicker datePicker;
String selectedDate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pager);
dbManager = new DBManager(getApplicationContext(),"Calorie_test1.db",null,1);
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(new PagerAdapterClass(getApplicationContext()));
mPager.setCurrentItem(1);
mPager.setPageTransformer(false, new ViewPager.PageTransformer()
{
#Override
public void transformPage(View page, float position)
{
// TODO Auto-generated method stub
float normalizedposition = Math.abs(1 - Math.abs(position));
page.setAlpha(normalizedposition);
page.setScaleX(normalizedposition / 2 + 0.5f);
page.setScaleY(normalizedposition / 2 + 0.5f);
page.setRotationY(position * 80);
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}*/
private void setCurrentInflateItem(int type){
if(type==0){
mPager.setCurrentItem(0);
}else if(type==1){
mPager.setCurrentItem(1);
}else{
mPager.setCurrentItem(2);
}
}
/**
* PagerAdapter
*/
private class PagerAdapterClass extends PagerAdapter
{
private LayoutInflater mInflater;
public PagerAdapterClass(Context c){
super();
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
return 3;
}
#Override
public Object instantiateItem(View pager, int position) {
View v = null;
ProgressBar progressExercise;
ProgressBar progressFood;
int exerciseCalorie;
int calorie;
if(position==0){
v = mInflater.inflate(R.layout.side_menu, null);
}
else if(position==1){
v = mInflater.inflate(R.layout.activity_main, null);
datePicker = (DatePicker)v.findViewById(R.id.datepicker);
datePicker.init(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
new DatePicker.OnDateChangedListener()
{
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
*selectedDate* = String.format("%d%d%d",year,monthOfYear+1,dayOfMonth);
//Intent intent = new Intent(MainActivity.this,DBManager.class);
//intent.putExtra("selectedDate",uri.toString());
//uri = intent.getParcelableExtra("uri");
Intent intent = new Intent(MainActivity.this,DBManager.class);
intent.putExtra("selectedDate",selectedDate);
}
});
//Intent intent = getIntent();
//int calorieExercise = intent.getIntExtra("calorieExercise",0);
progressExercise = (ProgressBar)v.findViewById(R.id.progressExercise);
progressExercise.setMax(500);
//progressExercise.setProgress(calorieExercise);
progressExercise.setProgress(dbManager.getExercise_Calorie());
//int calorieFood = intent.getIntExtra("calorieFood",0);
progressFood = (ProgressBar)v.findViewById(R.id.progressCalorie);
progressFood.setMax(2400);
progressFood.setProgress(dbManager.getFood_Calorie());
}else if(position== 2){
v = mInflater.inflate(R.layout.program_list, null);
v.findViewById(R.id.btn_food).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, FoodsearchActivity.class);
startActivity(intent);
finish();
}
});
v.findViewById(R.id.btn_exercise).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,ExerciseActivity.class);
startActivity(intent);
finish();
}
});
v.findViewById(R.id.btn_fermeted).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,FermentedActivity.class);
startActivity(intent);
finish();
}
});
}
((ViewPager)pager).addView(v, 0);
return v;
}
#Override
public void destroyItem(View pager, int position, Object view) {
((ViewPager)pager).removeView((View)view);
}
#Override
public boolean isViewFromObject(View pager, Object obj) {
return pager == obj;
}
#Override public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override public Parcelable saveState() { return null; }
#Override public void startUpdate(View arg0) {}
#Override public void finishUpdate(View arg0) {}
}
}
///
public class DBManager extends SQLiteOpenHelper{
public DBManager(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE test_table(_id INTEGER PRIMARY KEY AUTOINCREMENT, calorie_exercise INTEGER, calorie_food INTEGER, date_ TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
public void insert(String _query)
{
SQLiteDatabase db = getWritableDatabase();
db.execSQL(_query);
db.close();
}
public int getExercise_Calorie()
{
SQLiteDatabase db = getReadableDatabase();
int calorie = 0;
//Intent selectedDate = Intent.getIntent("selectedDate");
//String date = selectedDate.getStringExtra("selectedDate");
Test aa = new Test();
String date = aa.getSelectedDate();
Log.d("log.d",String.valueOf(date));
Cursor cursor = db.rawQuery("select * from test_table where date_ = '" + date + "';", null);
//Cursor cursor = db.rawQuery("select * from test_table",null);
while(cursor.moveToNext())
{
calorie += cursor.getInt(1);
}
return calorie;
}
public int getFood_Calorie()
{
SQLiteDatabase db = getReadableDatabase();
int calorie = 0;
Cursor cursor = db.rawQuery("select * from test_table",null);
while(cursor.moveToNext())
{
calorie += cursor.getInt(2);
}
return calorie;
}
}
You haven't started the next activity after putting data in the Intent.
Intent intent = new Intent(MainActivity.this,DBManager.class);
intent.putExtra("selectedDate",selectedDate);
startActivity(intent);