Ideas to refactor code with many Lists - android

I need a little help to get an idea of how to refactor my code, but I can't see options besides what's done, I would like to add the objects but not using so many lists (and if's conditions).
Here is my code, if anyone could help, I appreciate. Thanks
#ViewById
BannerHomeViewPager place1, place2, place3, place4, place5, place6, place7,
place8, place9;
The lists:
private List<HomeItem> allHomeItems = new ArrayList<HomeItem>(),
placeItems1 = new ArrayList<HomeItem>(),
placeItems2 = new ArrayList<HomeItem>(),
placeItems3 = new ArrayList<HomeItem>(),
placeItems4 = new ArrayList<HomeItem>(),
placeItems5 = new ArrayList<HomeItem>(),
placeItems6 = new ArrayList<HomeItem>(),
placeItems7 = new ArrayList<HomeItem>(),
placeItems8 = new ArrayList<HomeItem>(),
placeItems9 = new ArrayList<HomeItem>();
1) Items mocked, ok.
2)
#UiThread
void updateUI() {
if (allHomeItems != null && allHomeItems.size() > 0) {
for (HomeItem item : allHomeItems) {
if (item.getPlacement().contains("1")) {
placeItems1.add(item);
} else if (item.getPlacement().contains("2")) {
placeItems2.add(item);
} else if (item.getPlacement().contains("3")) {
placeItems3.add(item);
} else if (item.getPlacement().contains("4")) {
placeItems4.add(item);
} else if (item.getPlacement().contains("5")) {
placeItems5.add(item);
} else if (item.getPlacement().contains("6")) {
placeItems6.add(item);
} else if (item.getPlacement().contains("7")) {
placeItems7.add(item);
} else if (item.getPlacement().contains("8")) {
placeItems8.add(item);
} else {
placeItems9.add(item);
}
}
}
setupAdapters();
}
3) setupAdapters()
private void setupAdapters() {
if (place1 != null)
place1.update(placeItems1);
if (place2 != null)
place2.update(placeItems2);
if (place3 != null)
place3.update(placeItems3);
if (place4 != null)
place4.update(placeItems4);
if (place5 != null)
place5.update(placeItems5);
if (place6 != null)
place6.update(placeItems6);
if (place7 != null)
place7.update(placeItems7);
if (place8 != null)
place8.update(placeItems8);
if (place9 != null)
place9.update(placeItems9);
}

As #DanielBo answer:
private Map<String, ArrayList<HomeItem>> placeItems = new HashMap<String,ArrayList<HomeItem>>();
void updateUI() {
if (allHomeItems != null && allHomeItems.size() > 0) {
for (HomeItem item : allHomeItems) {
if(!placeItems.containsKey(item.getPlacement())){
placeItems.put(item.getPlacement(), new ArrayList<HomeItem>());
}
placeItems.get(item.getPlacement()).add(item);
}
}
setupAdapters();
}
But why are you using so many views? I really can't say if this is correct bcs i don't know the purpose of this, but I can't figure a good use to so many list views in the same layout...

Related

Android Camera X ViewPort

I use this code for Camera X binding. When I run app for the first time everything works fine. But when I close app and start it again I get "ViewPort is NULL". Why viewPort is NULL I do not understand. What is wrong with my code?
#OptIn(markerClass = androidx.camera.lifecycle.ExperimentalUseCaseGroupLifecycle.class)
private void bindAllCameraUseCases() {
if (cameraProvider != null) {
// As required by CameraX API, unbinds all use cases before trying to re-bind any of them.
cameraProvider.unbindAll();
createPreviewUseCase();
createImageCaptureUseCase();
createAnalysisUseCase();
if (previewUseCase != null && analysisUseCase != null && imageCaptureUseCase != null) {
ViewPort viewPort = ((PreviewView)findViewById(R.id.preview_view)).getViewPort();
if (viewPort != null) {
#OptIn(markerClass = androidx.camera.core.ExperimentalUseCaseGroup.class)
UseCaseGroup useCaseGroup = new UseCaseGroup.Builder()
.addUseCase(previewUseCase)
.addUseCase(analysisUseCase)
.addUseCase(imageCaptureUseCase)
.setViewPort(viewPort)
.build();
camera = cameraProvider.bindToLifecycle(/* lifecycleOwner= */ this, cameraSelector, useCaseGroup);
LiveData<Integer> torchStateObserver = camera.getCameraInfo().getTorchState();
torchStateObserver.observe(this, new Observer<Integer>() {
#Override
public void onChanged(Integer state) {
torchState = state;
}
});
} else {
Toast.makeText(this, "VIEWPORT is NULL", Toast.LENGTH_SHORT).show();
}
}
}
}

Android webrtc still running after app exited with back button

I'm new to Webrtc, I'm using the AWS Webrtc demo with Android Nav Component. When I exited the app with the back button, I can see that Webrtc is still running or I can see the following log:
EglRenderer: cameraSurfaceViewDropping frame - No surface
In my fragment at the onStop method my code is as follow:
Thread.setDefaultUncaughtExceptionHandler(null)
if (rootEglBase != null) {
rootEglBase!!.release()
rootEglBase = null
}
if (remoteView != null) {
remoteView!!.release()
remoteView = null
}
if (localPeer != null) {
localPeer!!.dispose()
localPeer = null
}
if (videoSource != null) {
videoSource!!.dispose()
videoSource = null
}
if (videoCapturer != null) {
try {
videoCapturer?.stopCapture()
videoCapturer?.dispose()
} catch (e: InterruptedException) {
Timber.e("Failed to stop webrtc video capture. $e ")
}
videoCapturer = null
}
if (client != null) {
this.client!!.disconnect()
this.client = null
}
peerConnectionFoundMap.clear()
pendingIceCandidatesMap.clear()
However, I can see the problem only when I exited the app through the back button, if I killed the app, I don't get the log. Has anyone experienced this?
Thank you.
This is the way you should destroy your WebRTC session on onDestroy() or onStop().
if (videoCaptureAndroid != null) {
videoCaptureAndroid?.stopCapture()
videoCaptureAndroid = null
}
if (localPeer != null) {
localPeer?.close()
localPeer = null
}
if (videoSource != null) {
videoSource?.dispose()
videoSource = null
}
if (audioSource != null) {
audioSource?.dispose()
audioSource = null
}
if (localAudioTrack != null) {
localAudioTrack?.dispose()
localAudioTrack = null
}
if (currentRemoteMediaStream != null) {
currentRemoteMediaStream?.dispose()
currentRemoteMediaStream = null
}
if (localVideoView != null) {
localVideoView?.release()
localVideoView = null
}
if (remoteVideoView != null) {
remoteVideoView?.release()
remoteVideoView = null
}
rootEglBase.release();

How can I make other apps play/pause music?

I'm making a media controller app similar to this example made by google. https://github.com/googlesamples/android-media-controller
However, I want to make a function that can resume playing music or pause given package name. I managed to return a list of package names.
PS. I'm using react native that's why I need a fucntion that I can call from the react side.
public void getMediaApps (Callback callback) {
// = getPackageManager();
ArrayList<MediaAppDetails> mediaApps = new ArrayList<MediaAppDetails>();
Intent mediaBrowserIntent = new Intent(MediaBrowserServiceCompat.SERVICE_INTERFACE);
List<ResolveInfo> services = packageManager.queryIntentServices(
mediaBrowserIntent,
PackageManager.GET_RESOLVED_FILTER
);
if (services != null && !services.isEmpty()) {
for (ResolveInfo info : services) {
mediaApps.add(
new MediaAppDetails(info.serviceInfo, packageManager, resources)
);
}
}
WritableArray waPackagenames = Arguments.createArray();
// ArrayList<String> packagenames = ArrayList<String>()
if(mediaApps != null && !mediaApps.isEmpty()){
for(MediaAppDetails mediaApp : mediaApps){
waPackagenames.pushString(mediaApp.packageName);
}
}
callback.invoke(waPackagenames);
}
I've been trying to do this for 3 days now, but no luck.
Probably won't make such of a difference but this is where I got so far with the play function.
#ReactMethod
public void play (String packageName) {
PackageManager pm = this.packageManager;
Resources res = this.resources;
ServiceInfo serviceInfo = MediaAppDetails.findServiceInfo(packageName, pm);
mMediaAppDetails = new MediaAppDetails(serviceInfo, pm, res);
MediaSessionCompat.Token token = mMediaAppDetails.sessionToken;
if (token == null) {
if (mMediaAppDetails.componentName != null) {
mBrowser = new MediaBrowserCompat(this.reactContext, mMediaAppDetails.componentName,
new MediaBrowserCompat.ConnectionCallback() {
#Override
public void onConnected() {
setupMediaController();
// mBrowseMediaItemsAdapter.setRoot(mBrowser.getRoot());
}
#Override
public void onConnectionSuspended() {
//TODO(rasekh): shut down browser.
// mBrowseMediaItemsAdapter.setRoot(null);
}
#Override
public void onConnectionFailed() {
showToastAndFinish("connection failed .. shit!");
}
}, null);
mBrowser.connect();
} else if (mMediaAppDetails.sessionToken != null) {
setupMediaController();
}
token = mBrowser.getSessionToken();
Toast.makeText(this.reactContext, "no token can't open controller", Toast.LENGTH_SHORT).show();
// toast
}
// Toast.makeText(this.reactContext, "found token", Toast.LENGTH_SHORT).show();
if(mBrowser == null )mBrowser = new MediaBrowserCompat(this.reactContext, new ComponentName(packageName, "MainActivity"), null, null);
MediaControllerCompat.TransportControls transportControls;
try{
mController = new MediaControllerCompat(this.reactContext, token);
if(mController!= null) {
transportControls = mController.getTransportControls();
transportControls.play();
}
}catch(Exception E){
Log.w("Error",E);
Log.w("Error","couldn't create mediaControllerCompat");
// System.out.println(E);
// System.out.println("couldn't create mediaControllerCompat");
}
}

how to know AsyncTask working in background or not?

I am calling one webservice in home page in that i will send all the details in that this process is working in bacground. when i come to this home page again i want to know prvious AsyncTask is end or not
what iam doing exactly here
public void callAsynchronousTask() {
//http://stackoverflow.com/questions/6531950/how-to-execute-async-task-repeatedly-after-fixed-time-intervals
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (vist != null && saves != null && prof != null && semail != null) {
if (vist.getStatus() != AsyncTask.Status.RUNNING) {
if (saves.getStatus() == AsyncTask.Status.PENDING || saves.getStatus() == AsyncTask.Status.FINISHED && saves.getStatus() != AsyncTask.Status.RUNNING)
{
if (prof.getStatus() == AsyncTask.Status.PENDING || prof.getStatus() == AsyncTask.Status.FINISHED && prof.getStatus() != AsyncTask.Status.RUNNING)
{
if (semail.getStatus() == AsyncTask.Status.PENDING || semail.getStatus() == AsyncTask.Status.FINISHED && semail.getStatus() != AsyncTask.Status.RUNNING)
{
checkandsave();
}
}
}
}
} else {
checkandsave();
}
public void checkandsave(){
ConnectionDetector cd = new ConnectionDetector(Home_page.this);
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DatabaseToadd da = new DatabaseToadd(Home_page.this);
mu = new ArrayList<>();
mu = da.getAllUser();
if (mu.size() > 0) {
vist = new Getvisiterid();
saves=new SaveVisitor();
semail=new sendemail();
prof=new saveprofpic();
vist.executeOnExecutor(THREAD_POOL_EXECUTOR);
}
}
else {
System.out.println("null db");
}
but in this when i come back to this actvity if asynctask running in background then also its showing null if i create object on top its showing pending
Based on your text I'm making the assumption you only need this task run in this activity, and dont need multiple tasks run at once. If this is the case use an asynctaskloader. The asynctask is tied to the lifecycle of the activity and you receive callbacks when it is starting, running in background, and done.
AsyncTaskLoader basic example. (Android)

Horizontal and Vertical ViewPager

Do anyone have successfully implemented ViewPager which scrolls Horizontally and Vertically?
I know Directional ViewPager,When i use it it gives
<i>31 12:11:29.954: E/AndroidRuntime(14670): java.lang.NoClassDefFoundError: com.directionalviewpager.DirectionalViewPager$DataSetObserver
10-31 12:11:29.954: E/AndroidRuntime(14670): at com.directionalviewpager.DirectionalViewPager.setAdapter(DirectionalViewPager.java:164)</i>
line no 164:mObserver = new DataSetObserver();
public void setAdapter(PagerAdapter adapter) {
if (mAdapter != null) {
VerticalViewPagerCompat.setDataSetObserver(mAdapter, null);
}
mAdapter = adapter;
if (mAdapter != null) {
if (mObserver == null) {
mObserver = new DataSetObserver();
}
VerticalViewPagerCompat.setDataSetObserver(mAdapter, mObserver);
mPopulatePending = false;
if (mRestoredCurItem >= 0) {
mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader);
setCurrentItemInternal(mRestoredCurItem, false, true);
mRestoredCurItem = -1;
mRestoredAdapterState = null;
mRestoredClassLoader = null;
} else {
populate();
}
}
}
Thanks,
I found your answer You just add the DirectionalViewPager as a library into your project
This libray is located at Android-DirectionalViewPager-master\Android-DirectionalViewPager-master\library\bin
and ya dont forget to include it from order and export tab

Categories

Resources