Categories
discuss

Android Studio XML Error

Currently testing out Android Instant Apps using Android Studio 3.0 Canary 3 and I’m getting this error when I try to build the app and emulate it.
Any ways to fix it? (I’m making a multi-feature Instant App).

Error:

~/Documents/GitHub/AndroidInstantApp/android-topeka/topeka-ui/build/intermediates/manifests/full/feature/debug/AndroidManifest.xml:2
attribute ‘split’ in tag is not a valid split name
Error:com.android.builder.internal.aapt.AaptException: AAPT2 link
failed: Error:java.util.concurrent.ExecutionException:
com.android.builder.internal.aapt.AaptException: AAPT2 link failed:
Error:Execution failed for task
‘:topeka-ui:processDebugFeatureResources’.

Failed to execute aapt

Answer

I think we may have found a bug of this alpha release.
I solved the problem by removing the dash (“-“) from the module name:

Apparently it is not well supported for split names.

The strange part is, both the codelabs and my project were initially working correctly with the dash.

Categories
discuss

How can I sort a list of maps by value of some specific key using Java 8?

How can I sort a List of Map<String, String> using Java 8? The map contains a key called last_name, and the value associated with it may be null. I’m not sure how to do it because the following results in a compiler error:

List<Map<String, String>> peopleList = ...

peopleList.sort(Comparator.comparing(Map::get, Comparator.nullsLast(Comparator.naturalOrder())));

Is using an anonymous class the only way to do it?

Note that I am not trying to sort each map in the list. I want to sort the list itself based on a key in each map.

Answer

It looks like you can rewrite your code like

peopleList.sort(Comparator.comparing(
                    m -> m.get("yourKey"), 
                    Comparator.nullsLast(Comparator.naturalOrder()))
               )
Categories
discuss

read failed: EBADF (Bad file descriptor) while reading from InputStream Nougat

With the recent changes in android N, I had to upgrade my code to use FileProvider to fetch images/files using camera/file manager. The code is working fine in emulator(genymotion) but throwing IO exception in Moto G4 plus.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                try {
                    ParcelFileDescriptor fcd = getContentResolver().openFileDescriptor(uriOrig,"r");// uriOrig is the uri returned from camera
                    if(fcd != null) {
                        InputStream inputStream = new FileInputStream(fcd.getFileDescriptor());
                        uploadCall =RestService.getInstance().uploadFile(mimeType, name, size,
                                inputStream, defaultResponseCallback);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

Here is the upload file method.

public Call<Attachment> uploadFile(final String mimeType, final String name, final long length,final InputStream is, final Callback<Attachment> callback) {
final int byteCount = 8192;
    if (length > 0) {
        RequestBody fileBody = new RequestBody() {

            @Override
            public MediaType contentType() {
                return !TextUtils.isEmpty(mimeType) ? MediaType.parse(mimeType) : null;
            }

            @Override
            public long contentLength() throws IOException {
                return length;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                final long fileLength = contentLength();
                byte[] buffer = new byte[byteCount];
                long uploaded = 0;

                try {
                    final Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {

                        @Override
                        public boolean handleMessage(Message msg) {
                            if (callback instanceof Callback2) {
                                Callback2 callback2 = (Callback2) callback;
                                long uploaded = (long) msg.obj;
                                callback2.onProgress(uploaded, fileLength);
                            }

                            return true;
                        }
                    });

                    int read;
                    while ((read = is.read(buffer)) != -1) {
                        uploaded += read;
                        sink.write(buffer, 0, read);
                        Log.d("write: ", "bytes: "+ new String(buffer));
                        Log.e("writeTo: ", uploaded + " up fd->");
                        // update progress on UI thread
                        handler.sendMessage(handler.obtainMessage(0, uploaded));
                    }

                    is.close();
                } catch (IOException e) {
                    Log.e("file_upload", "Exception thrown while uploading", e);
                }
                Log.e("sink: "+uploaded + " bytes ", sink.toString(), new Exception("check"));
            }
        };

        String fileName = name;
        int index = name.lastIndexOf(".");
        if (index < 0) {
            String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
            fileName += "." + extension;
        }

        MultipartBody.Part part = MultipartBody.Part.createFormData("file", fileName, fileBody);
        Call<Attachment> call = companyRestInterface.uploadFile(part);
        call.enqueue(callback);
        return call;
    }
}

The stack trace

java.io.IOException: read failed: EBADF (Bad file descriptor)
                                                          at libcore.io.IoBridge.read(IoBridge.java:481)
                                                          at java.io.FileInputStream.read(FileInputStream.java:252)
                                                          at java.io.FileInputStream.read(FileInputStream.java:223)
                                                          at xend.app.http.RestService$10.writeTo(RestService.java:767)
                                                          at okhttp3.MultipartBody.writeOrCountBytes(MultipartBody.java:173)
                                                          at okhttp3.MultipartBody.writeTo(MultipartBody.java:114)
                                                          at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:62)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                          at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                          at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                          at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                          at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                          at xend.app.http.MyInterceptor.intercept(MyInterceptor.java:51)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                          at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
                                                          at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
                                                          at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                          at java.lang.Thread.run(Thread.java:761)
                                                       Caused by: android.system.ErrnoException: read failed: EBADF (Bad file descriptor)
                                                          at libcore.io.Posix.readBytes(Native Method)
                                                          at libcore.io.Posix.read(Posix.java:169)
                                                          at libcore.io.BlockGuardOs.read(BlockGuardOs.java:231)
                                                          at libcore.io.IoBridge.read(IoBridge.java:471)
                                                          at java.io.FileInputStream.read(FileInputStream.java:252) 
                                                          at java.io.FileInputStream.read(FileInputStream.java:223) 
                                                          at xend.app.http.RestService$10.writeTo(RestService.java:767) 
                                                          at okhttp3.MultipartBody.writeOrCountBytes(MultipartBody.java:173) 
                                                          at okhttp3.MultipartBody.writeTo(MultipartBody.java:114) 
                                                          at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:62) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92) 
                                                          at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67) 
                                                          at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67) 
                                                          at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92) 
                                                          at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67) 
                                                          at xend.app.http.MyInterceptor.intercept(MyInterceptor.java:51) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92) 
                                                          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67) 
                                                          at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185) 
                                                          at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135) 
                                                          at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 
                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
                                                          at java.lang.Thread.run(Thread.java:761) 

Any help would be very much appreciated.

EDIT

The image uri part.

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File externalCacheDir = getExternalCacheDir();
File extFile = new File(externalCacheDir,
                        String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = FileProvider.getUriForFile(DirectChatActivity.this,
                            BuildConfig.APPLICATION_ID + ".provider",extFile);
                    grantUriPermission("xend.app", mImageCaptureUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    cameraIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

This mImageCaptureUri is later referred as uriOrig. Taken all permissions and have worked accordingly.

Answer

The problem is with ParcelFileDescriptor. It closes the input stream. So replacing the line

ParcelFileDescriptor fcd = getContentResolver().openFileDescriptor(uriOrig,"r");// uriOrig is the uri returned from camera
                    if(fcd != null) {
                        InputStream inputStream = new FileInputStream(fcd.getFileDescriptor());
                        uploadCall =RestService.getInstance().uploadFile(mimeType, name, size,
                                inputStream, defaultResponseCallback);
                    }

with

InputStream inputStream = getContentResolver().openInputStream(uriOrig);
uploadCall =RestService.getInstance().uploadFile(mimeType, name, size,
                                inputStream, defaultResponseCallback);

did the work.

Categories
discuss

Android Camera2 API Flash doesnt work on galaxy devices

I am using the Android Camera2 API to take photos for an app and I can’t get the flash to work properly on most Samsung Galaxy devices (galaxy s6 edge, galaxy s7, galaxy j7). I believe I have implemented the flash logic properly because Google’s Camera app that used to be on the Play Store also exhibits the same behaviors. Also the galaxy s8 seems to work with the flash pretty well (although results definitely have inconsistent lighting)

The issue with the galaxy j7 is that when I take a picture with flash (either with flash locked on or with auto flash in a scene that requires flash) the flash will stay on for a long time, the preview will lock, and then after maybe 7 seconds the image will take, and the flash is not a part of the image.

I have the following method handling flash modes:

private void setAutoFlash(CaptureRequest.Builder requestBuilder)
{
    switch (mFlashState)
    {
        case FLASH_STATE_AUTO:
            requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            //requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            break;
        case FLASH_STATE_ON:
            requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
            //requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_SINGLE);
            break;
        case FLASH_STATE_OFF:
            requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
            //requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            break;
    }
}

This flash logic is called every time a CaptureRequest.Builder is needed

The 3 commented out lines are something else I read that was suggested to help flash work properly for me, but it doesn’t seem to do anything

Samsung has their own camera API (http://developer.samsung.com/galaxy/camera) but I read that it is just a wrapper over Camera2 and I am worried that their API won’t even fix my issue.

Additional Information:

  • I have tried some camera apps from the play store, some work and others don’t.
  • ZCamera works fine with flash, which made me think they use Samsungs camera API to get it working, but then I noticed that ZCamera’s touch metering doesn’t work on Samsung devices which is another issue I came across while debugging my Camera2 implementation.
  • Flash seems to work fine if I stick with the deprecated Camera API

Any help on how to accomplish a working flash would be greatly appreciated

Answer

After working at this on and off for a bit I realized a few things. I mentioned that ZCamera (from the play store) works with flash, and I thought they accomplished this by using the Samsung SDK. I checked the app and it does not use the Samsung SDK.

I also incorporated the Samsung SDK into my app and that didn’t change anything. The Samsung SDK is really just a wrapper around google’s camera 2 so you can add some Samsung specific features, adding it to your project wont fix any Samsung compatibilities.

What I finally realized was that the touch metering flow I had programmed myself (touch to focus/then take a photo) worked very differently than my logic that ran when we take a photo without touch to focus. The regular photo logic was borrowed from googles camera2 api example code and it wasnt working propery.

The trick to get the flash to fire on Samsung devices (or at least what worked for me) was to first trigger a check for AE levels, and once that converges then start the auto focus trigger. If flash is turned on this will fire the flash to check AE levels and to focus, and then fire the flash once more to take the photo

Categories
discuss

Android style a SeekBar

I want to create a style for my app’s Seekbars. I just want to change the color of the thumb and the bar itself.

I managed to change the thumb name like this:

<style name="MySeekBar" parent="@style/Widget.AppCompat.SeekBar">
    <item name="android:thumbTint"> @color/turquoise </item>        
 </style>

but I’m not sure how to change the bar’s color. I know how to do it with code, but not in the xml:

seekBar.getProgressDrawable().setColorFilter(getContext().getResources().getColor(R.color.turquoise), Mode.SRC_ATOP);

How can I style the color filter with a style defined in xml?

Answer

You can use

android:progressTint

to change the color of progressing part of the seek bar and

android:progressBackgroundTint

to change bar background’s color in your style

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..