How to handle java.util.concurrent.RejectedExecutionException in android - java

I am getting java.util.concurrent.RejectedExecutionException exception while trying to load images in ImageView.This is not occurring every time but occurring in sometime.I know why the problem happens but don't know how to handle it.
public void onPostExecute(HttpResource[] httpResources) {
if (httpResources != null) {
String imageUrl = httpResources[0].getUrl();
File imageFile = httpResources[0].getFile();
int count = 0;
ArrayList<ImageItem> list = map.get(imageUrl);
if (list != null) {
//TODO implement pagination or manage concurrent threads
for (ImageItem imageItem : list) {
ImageHelper.loadImage(context, imageItem.getImageView(), imageFile, imageItem.isAutoResize(), imageItem.isAutoOrientation(), CROP_LAYOUTS_PARAMS);
}
}
map.remove(imageUrl);
if (map.isEmpty()) {
LogHelper.i(LibConst.TAG, "HttpImageProvider cache is empty");
}
}
}
}

Related

use setPlaybackParameters in MediaControllerCompat

Following this demo: https://github.com/googlesamples/android-media-controller
I have this
if (playbackState == null) {
Log.e(TAG, "Failed to update media info, null PlaybackState.");
return null;
}
Map<String, String> mediaInfos = new HashMap<>();
mediaInfos.put(getString(R.string.info_state_string),
playbackStateToName(playbackState.getState()));
MediaMetadataCompat mediaMetadata = mController.getMetadata();
if (mediaMetadata != null) {
addMediaInfo(
mediaInfos,
getString(R.string.info_title_string),
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
addMediaInfo(
mediaInfos,
getString(R.string.info_artist_string),
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
addMediaInfo(
mediaInfos,
getString(R.string.info_album_string),
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM));
binding.controlsPage.mediaTitle.setText(
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
binding.controlsPage.mediaArtist.setText(
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
binding.controlsPage.mediaAlbum.setText(
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM));
final Bitmap art = mediaMetadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART);
if (art != null) {
binding.controlsPage.mediaArt.setImageBitmap(art);
} else {
binding.controlsPage.mediaArt.setImageResource(R.drawable.ic_album_black_24dp);
}
// Prefer user rating, but fall back to global rating if available.
RatingCompat rating =
mediaMetadata.getRating(MediaMetadataCompat.METADATA_KEY_USER_RATING);
if (rating == null) {
rating = mediaMetadata.getRating(MediaMetadataCompat.METADATA_KEY_RATING);
}
mRatingUiHelper.setRating(rating);
} else {
binding.controlsPage.mediaArtist.setText(R.string.media_info_default);
binding.controlsPage.mediaArt.setImageResource(R.drawable.ic_album_black_24dp);
mRatingUiHelper.setRating(null);
}
final long actions = playbackState.getActions();
`
I'm interested in getting the current pitch and changing it to the one I want.
I can see this api here https://developer.android.com/reference/androidx/media3/session/MediaController#setPlaybackParameters(androidx.media3.common.PlaybackParameters) does what I want, but it's only for the MediaController, not for the MediaControllerCompat.
I tried doing mController.getMediaController()
https://developer.android.com/reference/kotlin/android/support/v4/media/session/MediaControllerCompat#getMediaController() with no changes at all.
Any ideas?

Using Function Call Based on Cursor Position - Android

I am currently taking each column based on query and modifying variables based on the current position of the cursor. I was wondering if it would be possible to cut down the size of the code by doing something like this where a different function call would be made based on the column within the cursor that is currently being referenced:
do {
Ticket ticket = new Ticket();
for(int i = 0; i < cursor.getColumnCount(); i++)
{
if (cursor.getString(0) != null) {
/*Where the array contains a list of function calls*/
ticket.arrayList(i);
}
}while(cursor.moveToNext());
Below is the code I currently have. From what I know there isn't anything in Java that works like this, but I'm trying to cut down on the number of lines here as I will eventually have close to one hundred columns that will be pulled into the cursor.
public List<Ticket> getTickets(Context context, SQLiteDatabase db)
{
List<Ticket> ticketInfo = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_TICKET;
Cursor cursor = null;
try {
cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
do {
Ticket ticket = new Ticket();
//Set the ticket number
if (cursor.getString(0) != null) {
ticket.setTicketNr(Integer.parseInt(cursor.getString(0)));
}
//Set the ticket id
if (cursor.getString(1) != null) {
ticket.setTicketId(Integer.parseInt(cursor.getString(1)));
}
//
if (cursor.getString(2) != null) {
ticket.setServiceName(cursor.getString(2));
}
//
if (cursor.getString(3) != null) {
ticket.setServiceHouseNr(Integer.parseInt(cursor.getString(3)));
}
//
if (cursor.getString(4) != null) {
ticket.setServiceDirectional(cursor.getString(4));
}
//
if (cursor.getString(5) != null) {
ticket.setServiceStreetName(cursor.getString(5));
}
//
if (cursor.getString(6) != null) {
ticket.setServiceCommunityName(cursor.getString(6));
}
//
if (cursor.getString(7) != null) {
ticket.setServiceState(cursor.getString(7));
}
//
if (cursor.getString(8) != null) {
ticket.setServiceZip1(Integer.parseInt(cursor.getString(8)));
}
//
if (cursor.getString(9) != null) {
ticket.setServiceZip2(Integer.parseInt(cursor.getString(9)));
}
//
if (cursor.getString(10) != null) {
ticket.setTroubleReported(cursor.getString(10));
}
// Adding exercise to list
if (ticket != null) {
ticketInfo.add(ticket);
}
} while (cursor.moveToNext());
} else {
//No results from query
Toast.makeText(context.getApplicationContext(), "No tickets found", Toast.LENGTH_LONG).show();
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
}
catch(SQLiteException exception)//If exception is found
{
Log.d(TAG, "Error", exception);
//Display exception
Toast.makeText(context.getApplicationContext(), exception.toString(), Toast.LENGTH_LONG).show();
}
return ticketInfo;
}
Thank you for any insights into this.
I think this would do it. Just advance the cursor and pass it into the Ticket constructor. You may want to add some error checking.
public class Ticket {
private static class Field {
int intValue;
String stringValue;
final Class type;
Field(Class fieldType){
type = fieldType;
}
void set(String value){
if(type.equals(String.class)){
stringValue = value;
}
else {
intValue = Integer.parseInt(value);
}
}
}
private List<Field> fields = new ArrayList<>();
private Field addField(Field field){
fields.add(field);
return field;
}
// This solution relies on adding fields in the order they'll be retrieved in the cursor.
// Other options are possible such as a map by column index.
private Field ticketNumber = addField(new Field(Integer.class));
private Field serviceName = addField(new Field(String.class));
public Ticket(Cursor cursor){
for(int i=0; i < fields.size(); i++){
Field f = fields.get(i);
f.set(cursor.getString(i));
}
}
}
public int getTicketNumber(){
return ticketNumber.intValue;
}
// Don't know if you need setters
public void setTicketNumber(int value){
ticketNumber.intValue = value;
}
// etc for remaining fields
I would also consider using an ORM to make this stuff easier, rather than dealing with cursors.

detect concurrent access to syncronized function java

I Have a multithreaded environment in android app. I use a singleton class to store data. This singleton class contains a arraylist that is accessed using a synchronized method.
The app uses this arraylist to render images in app.
Initial problem : Concurrent modification error use to come so I made the get arraylist function syncronized.
Current Problem:Concurrent modification error not coming but in between empty arraylist returned (maybe when there is concurrent access).
Objective : I want to detect when Concurrent modification so that Instead of empty arraylist being return I can return last state of the arraylist.
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
//for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
Referred to Detecting concurrent modifications?
Please help!
EDIT1:
This problem occurs rarely not everytime.
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?? I'm new to multithreading , please guide
Edit 2
in oncreate following methods of singleton are called periodically
DataModelManager.getInstance().getCurrentDataToShow();
DataModelManager.getInstance().parseData(responseString);
Complete singleton class
public class DataModelManager {
private static DataModelManager dataModelManager;
private ImageFrameActivity imageFrameAct;
private String defaultFileName;
public List<FrameData> listFrameData = new ArrayList<FrameData>();
// public CopyOnWriteArrayList<FrameData> listFrameData= new CopyOnWriteArrayList<FrameData>();
private String screensaverName;
private boolean isToDownloadDeafultFiles;
private String tickerMsg = null;
private boolean showTicker = false;
private boolean showHotspot = false;
private String hotspotFileName=null;
public String getDefaultFileName() {
return defaultFileName;
}
public boolean isToDownloadDeafultFiles() {
return isToDownloadDeafultFiles;
}
public void setToDownloadDeafultFiles(boolean isToDownloadDeafultFiles) {
this.isToDownloadDeafultFiles = isToDownloadDeafultFiles;
}
private String fileNames;
private DataModelManager() {
}
public static DataModelManager getInstance() {
if (dataModelManager == null) {
synchronized (DataModelManager.class) {
if (dataModelManager == null) {
dataModelManager = new DataModelManager();
}
}
}
return dataModelManager;
}
private synchronized void addImageData(FrameData frameData) {
//Log.d("Frame Data","Start date "+frameData.getStartDate()+ " " +"end date "+frameData.getEndDate());
listFrameData.add(frameData);
}
public synchronized void parseData(String jsonStr) throws JSONException {
listFrameData.clear();
if (jsonStr == null) {
return;
}
List<String> listFileNames = new ArrayList<String>();
JSONArray jsonArr = new JSONArray(jsonStr);
int length = jsonArr.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
dataModelManager.addImageData(new FrameData(jsonObj.optString("filename", ""), jsonObj.optString("start", ""), jsonObj.optString("end", ""), jsonObj.optString("filetype", ""), jsonObj.optString("playTime", ""), jsonObj.optBoolean("allDay", false)));
listFileNames.add(jsonObj.optString("filename", ""));
}
fileNames = listFileNames.toString();
}
public void setDefaultFileData(String jsonStr) throws JSONException {
JSONObject jsonObj = new JSONObject(jsonStr);
defaultFileName = jsonObj.optString("default_image", "");
screensaverName = jsonObj.optString("default_screensaver ", "");
}
#Override
public String toString() {
return fileNames.replace("[", "").replace("]", "") + "," + defaultFileName + "," + screensaverName;
}
public FrameData getFrameData(int index) {
return listFrameData.get(index);
}
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
// for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
public String getCurrentFileNames() {
String currFileNames = "";
List<FrameData> currFrameData = getCurrentDataToShow();
for (FrameData data : currFrameData) {
currFileNames += "," + data.getFileName();
}
return currFileNames;
}
public ImageFrameActivity getImageFrameAct() {
return imageFrameAct;
}
public void setImageFrameAct(ImageFrameActivity imageFrameAct) {
this.imageFrameAct = imageFrameAct;
}
}
This is the only part of your question that is currently answerable:
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?
It depends on whether you are calling getCurrentDataToShow() on the same target object; i.e. what this is.
If this is the same for both calls, then the first call will complete before the second call starts.
If this is different, you will be locking on different objects, and the two calls could overlap. Two threads need to lock the same object to achieve mutual exclusion.
In either case, this method is not changing the listFrameData collection. Hence it doesn't matter whether the calls overlap! However, apparently something else is changing the contents of the collection. If that code is not synchronizing at all, or if it is synchronizing on a different lock, then that could be a source of problems.
Now you say that you are not seeing ConcurrentModificationException's at the moment. That suggests (but does not prove) that there isn't a synchronization problem at all. And that suggests (but does not prove) that your current problem is a logic error.
But (as I commented above) there are reasons to doubt that the code you have shown us is an true reflection of your real code. You need to supply an MVCE if you want a more definite diagnosis.

How to reliably detect device type on a MediaRoute select/unselect event

I have dug into the Android sources and found that under the hood, each time an Audio route event occurs, an AudioRoutesInfo object is based to the internal updateAudioRoutes method in MediaRouter:
void updateAudioRoutes(AudioRoutesInfo newRoutes) {
if (newRoutes.mMainType != mCurAudioRoutesInfo.mMainType) {
mCurAudioRoutesInfo.mMainType = newRoutes.mMainType;
int name;
if ((newRoutes.mMainType&AudioRoutesInfo.MAIN_HEADPHONES) != 0
|| (newRoutes.mMainType&AudioRoutesInfo.MAIN_HEADSET) != 0) {
name = com.android.internal.R.string.default_audio_route_name_headphones;
} else if ((newRoutes.mMainType&AudioRoutesInfo.MAIN_DOCK_SPEAKERS) != 0) {
name = com.android.internal.R.string.default_audio_route_name_dock_speakers;
} else if ((newRoutes.mMainType&AudioRoutesInfo.MAIN_HDMI) != 0) {
name = com.android.internal.R.string.default_media_route_name_hdmi;
} else {
name = com.android.internal.R.string.default_audio_route_name;
}
sStatic.mDefaultAudioVideo.mNameResId = name;
dispatchRouteChanged(sStatic.mDefaultAudioVideo);
}
final int mainType = mCurAudioRoutesInfo.mMainType;
boolean a2dpEnabled;
try {
a2dpEnabled = mAudioService.isBluetoothA2dpOn();
} catch (RemoteException e) {
Log.e(TAG, "Error querying Bluetooth A2DP state", e);
a2dpEnabled = false;
}
if (!TextUtils.equals(newRoutes.mBluetoothName, mCurAudioRoutesInfo.mBluetoothName)) {
mCurAudioRoutesInfo.mBluetoothName = newRoutes.mBluetoothName;
if (mCurAudioRoutesInfo.mBluetoothName != null) {
if (sStatic.mBluetoothA2dpRoute == null) {
final RouteInfo info = new RouteInfo(sStatic.mSystemCategory);
info.mName = mCurAudioRoutesInfo.mBluetoothName;
info.mDescription = sStatic.mResources.getText(
com.android.internal.R.string.bluetooth_a2dp_audio_route_name);
info.mSupportedTypes = ROUTE_TYPE_LIVE_AUDIO;
sStatic.mBluetoothA2dpRoute = info;
addRouteStatic(sStatic.mBluetoothA2dpRoute);
} else {
sStatic.mBluetoothA2dpRoute.mName = mCurAudioRoutesInfo.mBluetoothName;
dispatchRouteChanged(sStatic.mBluetoothA2dpRoute);
}
} else if (sStatic.mBluetoothA2dpRoute != null) {
removeRouteStatic(sStatic.mBluetoothA2dpRoute);
sStatic.mBluetoothA2dpRoute = null;
}
}
if (mBluetoothA2dpRoute != null) {
if (mainType != AudioRoutesInfo.MAIN_SPEAKER &&
mSelectedRoute == mBluetoothA2dpRoute && !a2dpEnabled) {
selectRouteStatic(ROUTE_TYPE_LIVE_AUDIO, mDefaultAudioVideo, false);
} else if ((mSelectedRoute == mDefaultAudioVideo || mSelectedRoute == null) &&
a2dpEnabled) {
selectRouteStatic(ROUTE_TYPE_LIVE_AUDIO, mBluetoothA2dpRoute, false);
}
}
}
Unfortunately, the only thing I have found that is exposed about the device type in the MediaRouter callbacks, is the internal string resource name of the device (e.g. Phone or Headphones). However, you can see that under the hood, this AudioRoutesInfo object has references to whether the device was a headphone, HDMI etc.
Has anyone found a solution to get at this information? The best way I have found is to use the internal resource names, which is pretty ugly. God, if they would just provide the AudioRoutesInfo object all this information could be accessed without having to rely on a resource hack.

android-market retrieve empty results

I wanted to harvest some data on specific apps in
Google play marketplace.
I have used this unofficial API:
https://code.google.com/p/android-market-api/
Here is my code, that basically gets list of apps' names
and try to fetch other data on each app:
public void printAllAppsData(ArrayList<AppHarvestedData> dataWithAppsNamesOnly)
{
MarketSession session = new MarketSession();
session.login("[myGamil]","[myPassword]");
session.getContext().setAndroidId("dead00beef");
final ArrayList<AppHarvestedData> finalResults = new ArrayList<AppHarvestedData>();
for (AppHarvestedData r : dataWithAppsNamesOnly)
{
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setQuery(query)
.setStartIndex(0).setEntriesCount(10)
//.setCategoryId("SOCIAL")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
for(AppHarvestedData res : finalResults)
{
System.out.println(res.toString());
}
}
}
Should I realyy call session.flush(); at this point?
all my quesries return empty collection as a result,
even though I see there are some names as input.
It works fine when I send only one hard coded app name as a query.
session.flush() close you session
you should open session for each query. pay attention the user can be locked for few minutes so you should have many users to to those queries.
if you have the AppId you should use that query:
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setAppId("com.example.android")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
if you want to download also screenshoot or images you should call this query:
GetImageRequest? imgReq; imgReq = GetImageRequest?.newBuilder().setAppId(appId).setImageUsage(AppImageUsage?.SCREENSHOT).setImageId("0").build();
session.append(imgReq, new Callback<GetImageResponse>() {
#Override public void onResult(ResponseContext? context, GetImageResponse? response) {
Log.d(tag, "------------------> Images response <----------------"); if(response != null) {
try {
//imageDownloader.download(image, holder.image, holder.imageLoader);
Log.d(tag, "Finished downloading screenshot 1...");
} catch(Exception ex) {
ex.printStackTrace();
}
} else {
Log.e(tag, "Response was null");
} Log.d(tag, "------------> End of Images response <------------");
}
});

Categories