I am new with android and i am making a simple application where i will get a video from local device and play it in a videoview in my layout. Playing the video works fine but when i change orientation from portrait to landscape, the video disappear. I believe i need to save the state of the activity. Here is my code.
public class MainActivity extends AppCompatActivity {
private int position = 0;
private VideoView vidView;
private static int RESULT_LOAD_VIDEO = 1;
String vidDecodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadVideo = (Button)findViewById(R.id.buttonLoadVideo);
this.vidView = (VideoView)findViewById(R.id.myVideo);
buttonLoadVideo.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_VIDEO);
}
});
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
try {
if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK && null != data){
Uri selectedVideo = data.getData();
String[] filePathColumn = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
vidDecodableString = cursor.getString(columnIndex);
//URI
Uri vidUri = Uri.parse(vidDecodableString);
vidView.setVideoURI(vidUri);
MediaController vidControl = new MediaController(this);
vidControl.setAnchorView(vidView);
vidView.setMediaController(vidControl);
vidView.start();
} else {
Toast.makeText(this, "Please select video to play.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("Position", vidView.getCurrentPosition());
vidView.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
position = savedInstanceState.getInt("Position");
vidView.seekTo(position);
}
}
After i run the code, the selecting and playing of the video works but when i change the orientation, the video loaded disappear. Where am i doing wrong. Please advice.
add this attribute in manifest
<activity
android:name=".YourActivity"
android:configChanges="keyboardHidden|orientation|screenSize" />
Related
I am making a birthday wisher app, everthing works fine but I want that user can select image from gallary and it passes to 2nd activity, when timer is finised, I used ticker coundown in this.
My MainActivity
public class MainActivity extends AppCompatActivity {
CircularView circularViewWithTimer;
EditText entertime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
entertime = (EditText) findViewById(R.id.Txt_time);
circularViewWithTimer = findViewById(R.id.circular_view);
CircularView.OptionsBuilder builderWithTimer =
new CircularView.OptionsBuilder()
.shouldDisplayText(true)
.setCounterInSeconds(15)
.setCircularViewCallback(new CircularViewCallback() {
#Override
public void onTimerFinish() {
String name = entertime.getText().toString();
Intent i = new Intent(MainActivity.this, Bday_page.class);
i.putExtra("text", name);
startActivity(i);
finish();
}
#Override
public void onTimerCancelled() {
// Will be called if stopTimer is called
Toast.makeText(MainActivity.this, "CircularCallback: Timer Cancelled ", Toast.LENGTH_SHORT).show();
}
});
circularViewWithTimer.setOptions(builderWithTimer);
}
public void btn_pause(View view) {
circularViewWithTimer.pauseTimer();
}
public void btn_start(View view) {
MediaPlayer mMediaPlayer;
if(entertime.getText().toString().isEmpty()){
Toast.makeText(this, "Enter name of bday boy", Toast.LENGTH_SHORT).show();
}
else {
circularViewWithTimer.startTimer();
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this,R.raw.count);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
}
public void btn_resume(View view) {
circularViewWithTimer.resumeTimer();
}
}
My 2nd Activity
public class Bday_page extends AppCompatActivity {
TextView nameuser;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bday_page);
nameuser = (TextView)findViewById(R.id.txt_imagename);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.happybady);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
Intent i = getIntent();
nameuser.setText(i.getStringExtra("text"));
}
}
first of all you have to request the storage permission in the manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
after that in your MainActivity make your onTimerFinish methods like these
#Override
public void onTimerFinish() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent,1777);
}
now you requsted the image from Galary then add onActivityResult method to your main activity to receive the image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
Uri uri = data.getData();
Cursor cursor;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
String name = entertime.getText().toString();
Intent i = new Intent(MainActivity.this, Bday_page.class);
i.putExtra("text", name);
i.putExtra("imagePath",picturePath )
startActivity(i);
finish();
}}}
now you get the path of selected image and send it to the next activity
and in your 2nd Activity receive the image like these
Intent i = getIntent();
nameuser.setText(i.getStringExtra("text"));
String imagePath = i.getStringExtra("imagePath") //add these
now you have the image Path in the new activity you can do what you want to do with it
I am trying to attach video file in my app. I tried the following code to get video from Android device. After attaching the video, if I try to play it using the MediaController class, the screen becomes blank. Please help me with this.
void pickVideo() {
Intent videoIntent = new Intent(Intent.ACTION_GET_CONTENT);
videoIntent.setType("video/*");
startActivityForResult(videoIntent, PICK_VIDEO_FILE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_VIDEO_FILE:
Uri videoUri = data.getData();
if (mChooseFileDialogListener != null) {
mChooseFileDialogListener.onVideoClick(videoUri, ViewModel.FILE_TYPE_VIDEO);
}
break;
}
}
ChooseFileDialogFragment.ChooseFileDialogListener mChooseFileDialogListener = new ChooseFileDialogFragment.ChooseFileDialogListener() {
#Override
public void onVideoClick(Uri videoUri, int fileType) {
mPath = videoUri.toString();
}
}
AttachmentAdapter.ItemClickListener = new AttachmentAdapter.ItemClickListener() {
#Override
public void onClick(String path) {
playVideo(path);
}
}
private void playVideo(String path) {
MediaController mediaControls = new MediaController(getActivity());
try {
//set the media controller in the VideoView
mBinding.videoPlayer.setMediaController(mediaControls);
//set the uri of the video to be played
if (file != null) {
mBinding.videoPlayer.setVideoPath(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.
I am implementing video uploading functionality in an android application.I can choose a video from gallery but I can not view it in my activity.I dont know how to put a video from gallery to videoview of an activity
My code to select video from gallery is :
mChoose.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("video/*");
startActivityForResult(intent, REQUEST_ID);
}
});
onActivityResult Method code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
InputStream stream = null;
if(requestCode == REQUEST_ID && resultCode == Activity.RESULT_OK)
{
try
{
stream = getContentResolver().openInputStream(data.getData());
//System.out.println(data.getData());
mVideo.setVideoPath(path);
path = getRealPathFromURI(getApplicationContext(), data.getData());
//getRealPathFromURI is method in class to obtain path from uri
System.out.println(path);
}
catch(Exception ex)
{
ex.printStackTrace();
}
if(stream != null)
{
try
{
stream.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
Use this Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVideo = (VideoView) findViewById(R.id.videoView);
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("video/*");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == 1 && resultCode == Activity.RESULT_OK)
{
try
{
String path = data.getData().toString();
mVideo.setVideoPath(path);
mVideo.requestFocus();
mVideo.start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
VideoView videoView = (VideoView) findViewById(R.id.videoview);
Uri vidFile = Uri.parse(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "path of the video");
videoView.setVideoURI(vidFile);
videoView
.setMediaController(new MediaController(PlayVideoActivity.this));
videoView.setVisibility(1);
videoView.bringToFront();
videoView.requestFocus();
Here, I have to select an image from gallery or camera. When user selects image from gallery, that selected image should be displayed to next activity. But here these both activities are under the same tab, say tab A. Means in tab A there are two activities. In first activity, user has two options to select image either from gallery or from camera. And in second activity under same tab A, user gets that selected image. But here I'm not getting the expected output. Below is my code...
MainActivity.java
public class MainActivity extends TabActivity {
TabHost tabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources ressources = getResources();
tabHost = getTabHost();
Intent intentProfile = new Intent().setClass(this, Tab1.class);
TabSpec tabProfile = tabHost
.newTabSpec("Profile")
.setIndicator("Profile", ressources.getDrawable(R.drawable.ic_launcher))
.setContent(intentProfile);
Intent intentFriends = new Intent().setClass(this, Tab2.class);
TabSpec tabFriends = tabHost
.newTabSpec("Friends")
.setIndicator("Friends", ressources.getDrawable(R.drawable.ic_launcher))
.setContent(intentFriends);
tabHost.addTab(tabProfile);
tabHost.addTab(tabFriends);
tabHost.setCurrentTab(0);
}
public void switchTabBar(int tab) {
tabHost.setCurrentTab(tab);
}
#Override
public void onBackPressed() {
// Called by children
MainActivity.this.finish();
}
}
ABCGroup.java
public class ABCGroup extends ActivityGroup{
public static ABCGroup group;
private ArrayList<View> history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList<View>();
group = this;
View view = getLocalActivityManager().startActivity
("ParentActivity",
new Intent(ABCGroup.this, Tab1.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
}
public void replaceView(View v) {
// Adds the old one to history
history.add(v);
// Changes this Groups View to the new View.
setContentView(v);
}
public void back() {
if(history.size() > 0) {
history.remove(history.size()-1);
if(history.size()<=0){
finish();
}else{
setContentView(history.get(history.size()-1));
}
}else {
finish();
}
}
#Override
public void onBackPressed() {
ABCGroup.group.back();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
ABCGroup.group.back();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Tab1.java
public class Tab1 extends ActivityGroup {
Button gallery, camera;
private ArrayList<View> myActivityHistory;
private static final int REQUEST_ID = 1;
private static final int HALF = 2;
private static final int TAKE_PICTURE = 3;
private Uri mUri;
private Bitmap mPhoto;
int i = 0;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
myActivityHistory = new ArrayList<View>();
gallery = (Button)findViewById(R.id.gallery);
camera = (Button)findViewById(R.id.camera);
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_ID);
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void replaceContentView(String id, Intent newIntent, int flag)
{
View mview = getLocalActivityManager().startActivity(id,newIntent.addFlags(flag)).getDecorView();
ABCGroup.group.replaceView(mview);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK)
{
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try
{
mPhoto = null;
mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, mUri);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
break;
case REQUEST_ID :
InputStream stream = null;
if (resultCode == Activity.RESULT_OK) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original;
original = null;
original= BitmapFactory.decodeStream(stream);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
Intent in = new Intent(Tab1.this, Second.class);
replaceContentView("activity3", in, Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Toast.makeText(getBaseContext(), "" + cursor.getString(column_index) , 5000).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("data", cursor.getString(column_index) );
editor.commit();
return cursor.getString(column_index);
}
}
Second.java
public class Second extends ActivityGroup {
public static Bitmap bmp;
String path;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button btn = (Button)findViewById(R.id.button1);
iv = (ImageView)findViewById(R.id.imageView1);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ABCGroup.group.back();
}
});
}
#Override
public void onBackPressed() {
// this.getParent().onBackPressed();
Intent intent = new Intent(Second.this, Tab1.class);
Tab1 parentActivity = (Tab1)getParent();
parentActivity.replaceContentView("Profile", new Intent(Second.this, Tab1.class), Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
}