How to use MediaMetadataRetriever SetDataSource for file in external storage - java

I'm trying to extract Album art from MP3 file But I not able to give proper location of song, which I can give it to SetDataSource method. I tried everything but still it gives me error IllegalArgumentException.
It all happens when this line metaRetriver.setDataSource(MainActivity.this, Uri.parse("/sdcard/song.mp3")); gets executed
My Code.
public class MainActivity extends AppCompatActivity {
MediaMetadataRetriever metaRetriver;
byte[] art;
ImageView album_art;
Bitmap songImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(MainActivity.this, Uri.parse("/sdcard/song.mp3"));
art = metaRetriver.getEmbeddedPicture();
if (art != null) {
songImage = BitmapFactory
.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
} else {
String error = "art is null";
Log.i("lolol", error);
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.album_art);
}
}
Can anyone solve this problem.

From the Android Documentation:
Throws IllegalArgumentException if the Uri is invalid
Double check that the song.mp3 file is in the right place, and the app has permission to see it.

Related

Loading images from firestore in image slider

I'm trying to load the images in an image slider from firestore. The image urls are there in firestore. I'm using the following library https://github.com/denzcoskun/ImageSlideshow for image slider, but it shows error instead of images.
Image of the output
Logcat Image
Image of firestore structure
This is the java code:
public class preview_product extends AppCompatActivity
{
private String position;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private ImageSlider imageSlider;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_product_preview);
imageSlider = findViewById(R.id.image_slider);
final List<SlideModel> displayImages = new ArrayList<>();
Bundle intent = getIntent().getExtras();
position = intent.get("key").toString();
db.collection("Store").document("name").collection("prod").document(position).collection("details").document("product_id").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>()
{
#Override
public void onSuccess(#NonNull DocumentSnapshot documentSnapshot)
{
List<String> Urls = (List<String>) documentSnapshot.get("Images");
displayImages.add(new SlideModel(Urls.toString(), ScaleTypes.FIT));
imageSlider.setImageList(displayImages,ScaleTypes.FIT);
imageSlider.startSliding(3000);
}
});
}
}
I guess you've copied the link of the webpage-showing the image ,instead of the link of actual image.
Try opening the image in a new tab, and then copy the link from the address-bar.
Maybe, this is what you've copied !
This is what you should try coping instead !
Hope this helps!

Unexpected Crash When trying to open the detailactivity

I am facing a strange problem in my material design app . Some thumbnails are opening and loading details activity as expected , but some are not opening instead there is crash happening . in this video u can see the problem I am facing .
I am attaching the link to my project ZIP file link with this ,My Project
this is the main activity ....
public class MainActivity extends AppCompatActivity implements ReaderAdapter.ReaderOnClickItemHandler {
public final static String READER_DATA = "reader";
public final static String POSITION = "position";
private final static String TAG = MainActivity.class.getSimpleName();
private static final String SAVED_ARRAYLIST = "saved_array_list";
private static final String SAVED_LAYOUT_MANAGER = "layout-manager-state";
private ApiInterface mApiInterface;
private List<Reader> mNetworkDataList;
#BindView(R.id.main_recycler_view)
RecyclerView mRecyclerView;
#BindView(R.id.main_linear_layout)
LinearLayout mErrorLinearLayout;
#BindView(R.id.main_progress_bar)
ProgressBar mProgressBar;
#BindView(R.id.toolbar_main)
Toolbar toolbar;
#BindView(R.id.main_reload_button)
Button mButton;
private ReaderAdapter mReaderAdapter;
private Parcelable onSavedInstanceState = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
if (null != toolbar) {
setSupportActionBar(toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
}
mApiInterface = ApiClient.getApiClient().create(ApiInterface.class);
mReaderAdapter = new ReaderAdapter(this, this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setAdapter(mReaderAdapter);
mRecyclerView.setLayoutManager(linearLayoutManager);
// getting the data from api using retrofit interface ApiInterface
if (savedInstanceState != null) {
onSavedInstanceState = savedInstanceState.getParcelable(SAVED_LAYOUT_MANAGER);
mNetworkDataList = savedInstanceState.getParcelableArrayList(SAVED_ARRAYLIST);
}
if (null == mNetworkDataList) {
loadData();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadData();
}
});
}else {
loadAdapter();
}
}
public void loadData() {
final Call<List<Reader>> listCall = mApiInterface.getAllReaderData();
// now binding the data in the pojo class
listCall.enqueue(new Callback<List<Reader>>() {
//if data is successfully binded from json to the pojo class onResponse is called
#Override
public void onResponse(Call<List<Reader>> call,
Response<List<Reader>> response) {
Log.d(TAG, "Response : " + response.code());
mNetworkDataList = response.body();
loadAdapter();
}
//if data binding is not successful onFailed called
#Override
public void onFailure(Call<List<Reader>> call, Throwable t) {
//cancelling the GET data request
listCall.cancel();
showError();
}
});
}
private void loadAdapter() {
if (null != mNetworkDataList) {
showReaderList();
mReaderAdapter.ifDataChanged(mNetworkDataList);
if (onSavedInstanceState != null) {
mRecyclerView.getLayoutManager().onRestoreInstanceState(onSavedInstanceState);
}
}
}
/**
* this method is for showing the error textview and making all other views gone
*/
private void showError() {
mRecyclerView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
mErrorLinearLayout.setVisibility(View.VISIBLE);
}
/**
* this method is for showing the recyclerview and making all other views gone
*/
private void showReaderList() {
mRecyclerView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mErrorLinearLayout.setVisibility(View.GONE);
}
private int numberOfColumns() {
DisplayMetrics displayMetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
// You can change this divider to adjust the size of the poster
int widthDivider = 400;
int width = displayMetrics.widthPixels;
int nColumns = width / widthDivider;
if (nColumns < 2) return 2;
return nColumns;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(SAVED_LAYOUT_MANAGER, mRecyclerView.getLayoutManager()
.onSaveInstanceState());
if (mNetworkDataList != null)
outState.putParcelableArrayList(SAVED_ARRAYLIST, new ArrayList<Parcelable>(mNetworkDataList));
}
#Override
public void onClickItem(int position, Reader reader, ImageView mImage, TextView mTitle) {
// Check if we're running on Android 5.0 or higher
Intent readerIntent = new Intent(this, ReaderDetailsActivity.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(READER_DATA, reader);
mBundle.putInt(POSITION, position);
readerIntent.putExtras(mBundle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Apply activity transition
ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
this,
// Now we provide a list of Pair items which contain the view we can transitioning
// from, and the name of the view it is transitioning to, in the launched activity
new Pair<View, String>(mImage,
ReaderDetailsActivity.VIEW_NAME_HEADER_IMAGE),
new Pair<View, String>(mTitle,
ReaderDetailsActivity.VIEW_NAME_HEADER_TITLE));
ActivityCompat.startActivity(this, readerIntent, activityOptions.toBundle());
} else {
// Swap without transition
startActivity(readerIntent);
}
}
}
this is details activity ......
public class ReaderDetailsActivity extends AppCompatActivity {
private static final String TAG = ReaderDetailsActivity.class.getSimpleName();
private static final String SAVED_ARRAYLIST = "saved_array_list";
private static final String SAVED_LAYOUT_MANAGER = "layout-manager-state";
private final static String ARTICLE_SCROLL_POSITION = "article_scroll_position";
// View name of the header image. Used for activity scene transitions
public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";
// View name of the header title. Used for activity scene transitions
public static final String VIEW_NAME_HEADER_TITLE = "detail:header:title";
private int position;
private Reader reader;
private int[] scrollPosition = null;
#BindView(R.id.scrollView_details)
ScrollView mScrollView;
#BindView(R.id.details_fragment_title)
TextView mTitle;
#BindView(R.id.imageView_details)
ImageView mImageView;
#BindView(R.id.textView_author_details)
TextView mAuthor;
#BindView(R.id.textView_published_date)
TextView mPublishDate;
#BindView(R.id.textView_description)
TextView mDescription;
#BindView(R.id.floatingActionButton_Up)
FloatingActionButton mFloatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader_details);
ButterKnife.bind(this);
Bundle bundle = getIntent().getExtras();
position=0;
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScrollView.scrollTo(0,0);
}
});
ViewCompat.setTransitionName(mImageView, VIEW_NAME_HEADER_IMAGE);
ViewCompat.setTransitionName(mTitle, VIEW_NAME_HEADER_TITLE);
if (null != bundle) {
position = bundle.getInt(MainActivity.POSITION);
reader = bundle.getParcelable(MainActivity.READER_DATA);
if(null != reader) {
mTitle.setText(reader.getTitle());
mPublishDate.setText(reader.getPublishedDate());
mAuthor.setText(reader.getAuthor());
GlideApp.with(this)
.load(reader.getPhoto())
.into(mImageView);
mDescription.setText(reader.getBody());
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
scrollPosition = savedInstanceState.getIntArray(ARTICLE_SCROLL_POSITION);
if (scrollPosition != null) {
mScrollView.postDelayed(new Runnable() {
public void run() {
mScrollView.scrollTo(scrollPosition[0], scrollPosition[0]);
}
}, 0);
}
}
}
Json link I am parsing for this project .
Here is a screen recording of my project where u can see the problem I am facing , recording
this is a console log when I am trying to debug ....
when it is working fine the console log is 08/09 20:31:31: Launching app
No apk changes detected since last installation, skipping installation of /home/soumyajit/AndroidStudioProjects/MaterialReader/app/build/outputs/apk/debug/app-debug.apk
$ adb shell am force-stop lordsomen.android.com.materialreader
$ adb shell am start -n "lordsomen.android.com.materialreader/lordsomen.android.com.materialreader.activities.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to lordsomen.android.com.materialreader
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
and when it is crashing the console log is
08/09 20:31:31: Launching app
No apk changes detected since last installation, skipping installation of /home/soumyajit/AndroidStudioProjects/MaterialReader/app/build/outputs/apk/debug/app-debug.apk
$ adb shell am force-stop lordsomen.android.com.materialreader
$ adb shell am start -n "lordsomen.android.com.materialreader/lordsomen.android.com.materialreader.activities.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to lordsomen.android.com.materialreader
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
thanks in advance ..
Maximum Parcelable size should not be exceed 1mb. In you app it is 2.1 Mb. Without passing app date to the next activity you can try to pass item id and load data in next activity. Otherwise you can cache the list data and you can load the data from the local database in the details activity. If you cannot see crash log in android studio it because it set as "show only selected activity". In this case app get close and then this type of logs doesnot show in the android studio. switch that to No Filter and you can see the all logs.

Thumbnail for video from server not getting displayed in ImageView

Need to generate thumbnail from video stored in server, below is my code but "path" variable is giving problem, how to get it resolved. If i remove path parameter with url parameter then i am getting the thumbnails but not in proper order or sometimes same thumbnail is generated for 2 or 3 videos, below is my code -
Video video = mVideos.get(position);
//play video using android api, when video view is clicked.
url = video.getVideoUrl(); // your URL here
Uri videoUri = Uri.parse(url);
new DownloadImage(holder.videothumbView).execute(url);
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView ) bmImage;
}
protected Bitmap doInBackground(String... urls) {
Bitmap myBitmap = null;
MediaMetadataRetriever mMRetriever = null;
try {
mMRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mMRetriever.setDataSource(path, new HashMap<String, String>());
else
mMRetriever.setDataSource(path);
myBitmap = mMRetriever.getFrameAtTime();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (mMRetriever != null) {
mMRetriever.release();
}
}
return myBitmap;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
All the network related task must be done in a separate thread. You can't do it in main thread. You can use Picasso image library. It is open source and you can show different image for different state like loading, error etc.
Picasso.with(context) // your activity of other context referance
.load(video.getVideoUrl())
.placeholder(R.drawable.user_placeholder) // this will show during image loading from network
.error(R.drawable.user_placeholder_error) // error image to display
.into(holder.videothumbView);

How to set Image from Uri with a file:// scheme

I managed to use myimageview.setImageUri when the scheme was content://
But it doesnt work if my Uri has a file:// scheme. What is wrong and how can I make it work?
I have given both read and write permission.
Edit:
To make sure I haven't messed up anything, I created a whole new project.
Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
ArrayList<Uri> myimageUri = null;
myimageUri = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
Uri theuri = myimageUri.get(0);
ImageView myimageView = findViewById(R.id.imageView);
myimageView.setImageURI(theuri);
}
Attaching a debugger I found out that theuri is
file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/IMG-20171101-WA0005.jpg
It still doesn't work, but content :/// URIs work.
Try following code:
InputStream in = myimageView.g etContext().getContentResolver(). openInputStream(theuri);
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();
myimageView.setImageBitmap(bitmap);
You need to decode image file to a bitmap and give it to ImageView.
Bitmap mBitmap = Media.getBitmap(this.getContentResolver(), yourUri);
imageView.setImageBitmap(bitmap);

Adding a raw .txt file to a layout

I'm trying to add a text file for a help page on my app but with the code I have it's just crashing the app when I select help from the options menu. I know it's to do with this code as when I comment it out it opens the help page fine.
The code is in my HelpActivity class:
public class HelpActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_page);
}
InputStream iFile = getResources().openRawResource(R.raw.gamehelp);
private String inputStreamToString(InputStream iFile) {
TextView helpText = (TextView) findViewById(R.id.tvHelpText);
String strFile = inputStreamToString(iFile);
helpText.setText(strFile);
return strFile;
}
}
Can anyone see any problem with how I'm trying to do this?
Thanks
Since you didn't include any error logs, I'm judging just from your code:
InputStream iFile = getResources().openRawResource(R.raw.gamehelp);
You are calling this in class body, but getResources() is not available here. What you should do is:
InputStream iFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_page);
iFile = getResources().openRawResource(R.raw.gamehelp);
}

Categories

Resources