I have a Settings Preference screen.It has a ListPreference and a CheckBoxPreference. I want to change my app's date format when I choose an item of ListPreference. Also, by the CheckBoxPreference I want to show/hide notification on the status bar. Can anyone tell what I have to do to achieve that.
Also, how can I add a toolbar to the preference screen? I am stuck here. Please help. Thanks in advance.
I am stuck here. Please help.
Thanks in advance.
MainActivity.java
public void setCurrentDateOnView() {
String dateFormat = "dd - MM - yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
tv_Current_Date.setText(simpleDateFormat.format(calendar_now.getTime()));
String short_weekday = new DateFormatSymbols().getShortWeekdays()[day_of_current_week];
tv_Current_weekday.setText(short_weekday);
til_Current_Date.setError(null);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent_settings = new Intent(this, SettingsActivity.class);
startActivity(intent_settings);
Toast.makeText(this, "You have clicked on settings action menu.", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
NotificationManager mNotifyManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean notifyEnabled = sharedPreferences.getBoolean("pref_cb_notification", true);
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notifyEnabled) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean isChecked = sharedPreferences.getBoolean("pref_cb_notification", false);
if (isChecked) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
//Method to show notification
public void showNotification() {
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder)
new NotificationCompat.Builder(SettingsActivity.this)
.setSmallIcon(R.drawable.ic_notifications_white_24dp)
.setContentTitle("My Application")
.setSubText("Tap to start");
Intent resultIntent = new Intent(SettingsActivity.this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent
.getActivity(SettingsActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//System.currentTimeMillis();
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
//notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotifyManager.notify(1, notification);
}
//Method to hide notification
public void hideNotification() {
mNotifyManager.cancel(1);
}
}
Settings image
for adding toolbar you just need to use the coordinator layout in the layout file of your activity. Preference activity has simple layout like others and you just inflate preference fragments inside a container.
add appcompact design support library to your build.gradle
compile 'com.android.support:appcompat-v7:21.0.3'
Add toolbar.xml to your layout folder
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:elevation="4dp"
>
</android.support.v7.widget.Toolbar>
Then include toolbar in your activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<TextView
android:layout_below="#+id/tool_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/TextDimTop"
android:text="#string/hello_world" />
</RelativeLayout>
then you need to set up it in your activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
and then by using onCreateOptionsMenu you can add settings menu on it.
Related
I am a beginner and new to coding. I have a problem with ListView in Android Studio. I have created a simple activity with a simple Listview. The Listview contains locations, and when the user clicks on an item the app will open google maps and takes the user to that location. The problem occurred when I implemented a SearchView. When search is applied, whatever result is filtered it will always open the first location. So could you please help me with that. Thanks.
This is my code and sorry for the mess.
MainActivity.java
import com.example.myapplicationsecond.R;
public class MainActivity9 extends AppCompatActivity {
ListView listView;
String[] name = {"First Location","Second Location","Third Location","Fourth Location",};
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main9);
View view = getLayoutInflater().inflate(R.layout.abs_layout, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView Title = (TextView) view.findViewById(R.id.actionbar_title);
Title.setText("Search Here");
getSupportActionBar().setCustomView(view,params);
getSupportActionBar().setDisplayShowCustomEnabled(true); //show custom title
getSupportActionBar().setDisplayShowTitleEnabled(false); //hide the default title
getSupportActionBar().setTitle("Search Here");
listView = findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,name);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 21.422458, 39.826213"));
startActivity(intent);
}
if(position==1){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 24.467275, 39.610629"));
startActivity(intent);
}
if(position==2){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 25.173059, 45.142079"));
startActivity(intent);
}
if(position==3){
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("geo: 26.348400, 43.766664"));
startActivity(intent);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search Here");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
arrayAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
MainActivity.Xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity9">
<ListView
android:id="#+id/listview"
android:textDirection="locale"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
thats how you coded it, you have if(position==0) so no matter what will be on first position you will open same geo:. you should check WHAT is on first position when clicked, so inside onItemClick put:
String clickedText = arrayAdapter.getItem(position);
then find position of this item in all-items array
int positionInArray = java.util.Arrays.asList(name).indexOf(clickedText);
and now use positionInArray for your is else
but thats a quick fix, you should have some model, your custom class with two variables, String name and String geoUri or two longs for lat and lng
I am starting a new intent whenever a new geofence transition happens.
In GeofenceTransitionService.java:
Intent intent = new Intent(GeofenceTransitionService.this, VideoActivity.class);
intent.putExtra("videoID", videoURLS[i]);
startActivity(intent);
And I am initializing the fragment like this,
in VideoActivity.java:
public class VideoActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private String videoID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
videoID = getIntent().getStringExtra("videoID");
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtubePlayerFragment);
youTubePlayerFragment.initialize("APIKEY", this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION |
YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
if(!wasRestored) {
youTubePlayer.cueVideo(videoID);
}
youTubePlayer.setFullscreenControlFlags(0);
youTubePlayer.setFullscreen(true);
youTubePlayer.setShowFullscreenButton(false);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
final int REQUEST_CODE = 1;
if(error.isUserRecoverableError()) {
error.getErrorDialog(this,REQUEST_CODE).show();
} else {
String errorMessage = String.format("There was an error initializing the YoutubePlayer (%1$s)", error.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
}
activity_video.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".VideoActivity">
<fragment
android:id="#+id/youtubePlayerFragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.appcompat.widget.LinearLayoutCompat>
But the video will never load. It works fine on other activities though. I have checked the manifest but couldn't find anything that differentiates this activity from the other one that works. I use the same code for the other activity to initialize the other fragment.
I forgot to split the video url to get the videoID.
intent.putExtra("videoID", videoURLS[i].split("=")[1]);
I am new to Android & Fragment please help me. My app is using navbar menu which consists of Home (HomeFragment) and History (HistoryFragment).
I want to pass ArrayList (existingRecords) and a Record object (todayRecord) from HomeFragment to HistoryFragment when user navigate from Home to navbar and click on History. I've configured to send existingRecords to MainActivity class as below. I don't know how to pass todayRecord into the intent.
HomeFragment.class:
#Override
public void onStop() {
super.onStop();
//compare if the date of last record is the same as today
//if same, update today's record
Log.d(msg, "The onStop() event");
if(recordExist){
updateLastRecord(todayRecord);
Log.d(msg, "existing record updated");
}
//if record not found, add new record
else {
addRecord(todayRecord);
Log.d(msg, "New record added");
}
sendDataToMainActivity();
}
public void sendDataToMainActivity(){
Log.d("Android: ", "HomeFragment: Sending Data to MainActivity");
Intent intent = new Intent(getActivity().getBaseContext(), MainActivity.class);
intent.putParcelableArrayListExtra("existingRecords", existingRecords);
getActivity().startActivity(intent);
}
I don't know how to call sendReceiveData() when user clicked on History (R.id.nav_history) on navbar menu.
MainActivity.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_history, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
loadAdmob();
}
public void sendReceiveData(){
//receive data from HomeFragment
Intent intent = getIntent();
existingRecords = intent.getParcelableArrayListExtra("existingRecords");
//send data to History fragment
Bundle bundle=new Bundle();
bundle.putParcelableArrayList("existingRecords", existingRecords);
//set Fragmentclass Arguments
HistoryFragment fragobj=new HistoryFragment();
fragobj.setArguments(bundle);
}
I've configured HistoryFragment.class to receive data but when I ran the code, bundle is null because I have no way to pass the bundle in MainActivity.
HistoryFragment.class:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
historyViewModel = ViewModelProviders.of(this).get(HistoryViewModel.class);
View root = inflater.inflate(R.layout.fragment_history, container, false);
Bundle bundle = this.getArguments();
if(bundle!=null){
// handle your code here.
existingRecords = savedInstanceState.getParcelableArrayList("existingRecords");
txtThisMonthSummary = root.findViewById(R.id.txtThisMonthSummary);
txtThisWeekSummary = root.findViewById(R.id.txtThisWeekSummary);
txtThisMonthSummary = root.findViewById(R.id.txtYearSummary);
Log.d("Android: ", "HistoryFragment: Data received");
summary = new History(existingRecords);
txtThisWeekSummary.setText(summary.getWeeklySum());
txtThisMonthSummary.setText(summary.getMonthlySum());
txtThisYearSummary.setText(summary.getYearlySum());
}
return root;
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_zikir"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_history"
android:icon="#drawable/ic_achievement"
android:title="#string/menu_history" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_achievement" />
</group>
</menu>
Based on #kelvin feedback, I have managed to retrieve the data from SharedPreferences in HomeFragment. I didn't occur to me that data stored in SharedPreferences can be accessed through any class. *Noob*
Share Preference name/key:
public static final String PREFS_NAME = "Daily Zikir";
public static final String RECORDLIST = "Records";
Code used to store data, called in HomeFragment:
public void saveRecords(List records){
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
builder.excludeFieldsWithoutExposeAnnotation();
Gson sExposeGson = builder.create();
String jsonRecords = sExposeGson.toJson(records);
editor.putString(RECORDLIST, jsonRecords);
editor.commit();
Log.d("Android: ", "Jason string saved: "+ jsonRecords);
}
Code used to retrieve data, called in HistoryFragment:
public ArrayList loadRecords() {
// used for retrieving arraylist from json formatted string
SharedPreferences settings;
List records;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (settings.contains(RECORDLIST)) {
String jsonFavorites = settings.getString(RECORDLIST, null);
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
builder.excludeFieldsWithoutExposeAnnotation();
Gson sExposeGson = builder.create();
Record[] recordItems = sExposeGson.fromJson(jsonFavorites, Record[].class);
records = Arrays.asList(recordItems);
records = new ArrayList(records);
} else
return null;
return (ArrayList) records;
}
Will explore usage of SQLlite & ViewModel moving forward but this will do for now.
Ok I swear this is the last time I will ask this question. I've tried a trillion different solutions and non of them work.
First here is the blank Settings activity as created by Android Studio:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}
}
And here is my preferences xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:id="#+id/resetSettings"
android:defaultValue="true"
android:key="reset_settings"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="#string/reset_description"
android:title="#string/reset_title" />
<SwitchPreference
android:defaultValue="false"
android:key="switch_preference"
android:summary="Instead of values from 0 to 255, the seekBar will use percentages"
android:title="Use Percentages" />
</PreferenceScreen>
I want an OnClickListener attached to the Reset preference so it can open an Alert Dialog that asks the user if they want to delete all app data.
In settings fragment in onCreatePreference add:
Preference
resetPreference=findPreference("your Preference key");
Then for the click listener add:
resetPreference.setOnPreferenceClickListenere(new
Preference.OnPreferenceClickListener() {
#overide
public boolean onPreferenceClick(Preference preference)
{
//your code goes here
return false;
}
});
For the last 18 Months I have been building simple apps in android studio and I am really stuck trying to work this out so any help would be great
So far my app works great, open the app on the first activity and press the play button and the 2nd activity opens and plays the video, at the end of the video it returns back to the first activity, but I am trying to exit the app
guessing I should be able to add something like
public void onCompletion(MediaPlayer player) {
onStop();
onDestroy();
}
public class PlayVideo extends Activity {
boolean videoPlayed ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
);
videoPlayed = true;
playvideo();
FinishVideo();
}
public void playvideo() {
VideoView videoview = (VideoView) findViewById(R.id.videoview);
Uri uri = Uri.parse("android.resource://" + getPackageName()
+ "/"+ R.raw.sound_2);
videoview.setVideoURI(uri);
videoview.start();
}
public void FinishVideo() {
VideoView videoView = (VideoView) findViewById(R.id.videoview);
videoView.setOnCompletionListener
(newMediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
//Log.i("VideoView", "onCompletion()");
//Intent intent = new Intent
(PlayVideo.this,MainActivity.class);
//startActivity(intent);
System.exit(0);
}
});
}
}
----------------------------------------------------------------------------
<RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PlayVideo">
<VideoView
android:id="#+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
try this, it works for me, and you do not need to add finish(); function it will close the app if the FirstActivity is the MainActivity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
and in Second Activity add this
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
onBackPressed();
}
});
You have to finish() the first activity while starting the second activity,
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
finish();
and when the video play is completed in the second activity you have to call onBackPressed()
videoview.setVideoURI(uri);
videoview.start();
videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
onBackPressed();
}
});
and you don't have to call FinishVideo() method, you can set setOnCompletionListener in playvideo() method itself