textView.getLineCount() returns 0 after setTextSize method

I’m trying to resize my textview to fit in 1 line.

while (titleText.getLineCount() > 1) {
    float scaledDensity = ManagerStorage.mainActivity.getResources().getDisplayMetrics().scaledDensity;
    titleText.setTextSize(titleText.getTextSize() / scaledDensity - 0.5f);
    Log.i("lines", "" + titleText.getLineCount());
    }

However, while loop executes only once. After setTextSize method, getLineCount will always return 0. While loop is executed with runOnUiThread on runnable that works after view is returned by onCreateView method.

Solution:

Try this

while (titleText.getLineCount() > 1) {
        float scaledDensity = ManagerStorage.mainActivity.getResources().getDisplayMetrics().scaledDensity;
        titleText.setTextSize(titleText.getTextSize() / scaledDensity - 0.5f);

        titleText.post(new Runnable() {
            @Override
            public void run() {
                int lineCount = titleText.getLineCount();
                Log.i("lines", "" + titleText.getLineCount());
                // Use lineCount here
            }
        });
    }

How to hide item from the MainActivity toolbar in a fragment

In my application I have Toolbar in the MainActivity and inside the MainActivity I have a ViewPager to show 4 fragment.

The toolbar contains some images (button).

I want in one of these fragments to hide the image from the toolbar.
I wrote the code below, but it hides the image in all the fragments.

My code:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                troy.setVisibility(View.GONE);
            }
        }, 50);
    }
}

I want to hide it just in my current fragment, not all of them.

How can I do it?

Solution:

You can use addOnPageChangeListener() of your ViewPager

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {       

    }

    @Override
    public void onPageSelected(int position) {
         if (position == 0) { // Condition may vary according to your needs...
             troy.setVisibility(View.GONE);
         } else {
             troy.setVisibility(View.VISIBLE);
         }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
});

How to concatenate 2 or more strings as one inside a string array in Java?

I’d like to concatenate 2 or more consecutive strings into one string in an array according to two variables x and y meaning that starting from the x:th element, concatenate, until we have concatenated y elements. For example, if an Array ‘A’ has elements as:

A = {"europe", "france", "germany", "america"};
x=2;y=2;
//Here, I want to concatenate france and germany as :
A = {"europe", "france germany", "america"};
//Or 
x=2,y=3;

A= {"europe", "france germany america"};

Like this. Anyone know How This can be done without complex programming?

Solution:

Probably the most concise way is:

  1. Construct an array of the right size:

    String[] result = new String[A.length - (y-1)];
    
  2. Copy the start and the end of the array using System.arraycopy:

    System.arraycopy(A, 0, result, 0, x-1);
    System.arraycopy(A, x+y-1, result, x+1, A.length-(x+1));
    
  3. Build the concatenated string:

    result[x-1] = String.join(" ", Arrays.asList(A).subList(x-1, x-1+y));
    

(Note: out by one errors may be present, owing to the date of writing)

Wrong hours converted to epoch time

I’m trying to convert a date with epoch time method.
with these code below

long epoch = 0;
try {
    epoch = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("12/11/2017 23:20:23").getTime();
} catch (ParseException e) {
    e.printStackTrace();
}

It gives me the epoch time: 1513052423

Which once convert give: Tuesday 12 December 2017 04:20:23 and not 23:20:23 :/

Thank you.

Solution:

According to documentation SimpleDateFormat is locale-sensitive. Please check or set your timezone

sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

Error while integrating Realm in Android Studio

I am trying to integrate Realm 4.3.1 but I am getting weird error, which I am not able to resolve. I have referred Realm Documentation, I am using

Android Studio 3.0 Canary 4,

Gradle Version 4.1

Android Plugin Version 3.0.0-alpha4

Here is an error

Error:Cause: java.lang.NullPointerException
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:98)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
    at java.nio.file.Paths.get(Paths.java:84)
    at com.android.build.gradle.internal.scope.BuildOutput.getOutputPath(BuildOutput.java:222)
    at com.android.build.gradle.internal.scope.BuildOutputs.lambda$load$2(BuildOutputs.java:243)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at com.android.build.gradle.internal.scope.BuildOutputs.load(BuildOutputs.java:245)
    at com.android.build.gradle.internal.scope.BuildOutputs.load(BuildOutputs.java:184)
    at com.android.build.gradle.internal.scope.BuildOutputs.load(BuildOutputs.java:140)
    at com.android.build.gradle.internal.ide.BuildOutputsSupplier.lambda$get$1(BuildOutputsSupplier.java:54)
    at com.google.common.collect.ImmutableList.forEach(ImmutableList.java:397)
    at com.android.build.gradle.internal.ide.BuildOutputsSupplier.get(BuildOutputsSupplier.java:49)
    at com.android.build.gradle.internal.ide.BuildOutputsSupplier.get(BuildOutputsSupplier.java:34)
    at com.android.build.gradle.internal.ide.AndroidArtifactImpl.getOutputs(AndroidArtifactImpl.java:137)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.tooling.internal.adapter.ProtocolToModelAdapter$ReflectionMethodInvoker.invoke(ProtocolToModelAdapter.java:592)
    at org.gradle.tooling.internal.adapter.ProtocolToModelAdapter$AdaptingMethodInvoker.invoke(ProtocolToModelAdapter.java:397)
    at org.gradle.tooling.internal.adapter.ProtocolToModelAdapter$PropertyCachingMethodInvoker.invoke(ProtocolToModelAdapter.java:625)
    at org.gradle.tooling.internal.adapter.ProtocolToModelAdapter$SafeMethodInvoker.invoke(ProtocolToModelAdapter.java:647)
    at org.gradle.tooling.internal.adapter.ProtocolToModelAdapter$SupportedPropertyInvoker.invoke(ProtocolToModelAdapter.java:670)
    at org.gradle.tooling.internal.adapter.ProtocolToModelAdapter$InvocationHandlerImpl.invoke(ProtocolToModelAdapter.java:356)
    at com.sun.proxy.$Proxy187.getOutputs(Unknown Source)
    at com.android.tools.idea.gradle.project.model.ide.android.IdeAndroidArtifactImpl.<init>(IdeAndroidArtifactImpl.java:56)
    at com.android.tools.idea.gradle.project.model.ide.android.IdeVariantImpl.lambda$new$0(IdeVariantImpl.java:59)
    at com.android.tools.idea.gradle.project.model.ide.android.ModelCache.lambda$computeIfAbsent$0(ModelCache.java:31)
    at java.util.HashMap.computeIfAbsent(HashMap.java:1126)
    at com.android.tools.idea.gradle.project.model.ide.android.ModelCache.computeIfAbsent(ModelCache.java:31)
    at com.android.tools.idea.gradle.project.model.ide.android.IdeVariantImpl.<init>(IdeVariantImpl.java:58)
    at com.android.tools.idea.gradle.project.model.ide.android.IdeAndroidProjectImpl.lambda$new$4(IdeAndroidProjectImpl.java:87)
    at com.android.tools.idea.gradle.project.model.ide.android.ModelCache.lambda$computeIfAbsent$0(ModelCache.java:31)
    at java.util.HashMap.computeIfAbsent(HashMap.java:1126)
    at com.android.tools.idea.gradle.project.model.ide.android.ModelCache.computeIfAbsent(ModelCache.java:31)
    at com.android.tools.idea.gradle.project.model.ide.android.IdeModel.copy(IdeModel.java:74)
    at com.android.tools.idea.gradle.project.model.ide.android.IdeAndroidProjectImpl.<init>(IdeAndroidProjectImpl.java:86)
    at com.android.tools.idea.gradle.project.model.ide.android.IdeAndroidProjectImpl.<init>(IdeAndroidProjectImpl.java:67)
    at com.android.tools.idea.gradle.project.model.AndroidModuleModel.<init>(AndroidModuleModel.java:128)
    at com.android.tools.idea.gradle.project.sync.idea.AndroidGradleProjectResolver.populateModuleContentRoots(AndroidGradleProjectResolver.java:211)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.doResolveProjectInfo(GradleProjectResolver.java:366)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.access$200(GradleProjectResolver.java:79)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:902)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:886)
    at org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper.execute(GradleExecutionHelper.java:218)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:139)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:79)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.lambda$resolveProjectInfo$0(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:45)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:66)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:139)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:125)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3.execute(ExternalSystemUtil.java:388)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$5.run(ExternalSystemUtil.java:445)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:726)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:176)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:556)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:501)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:66)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:163)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:137)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:334)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Application gradle

apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.###.###"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 17
        versionName "1.17"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
//    compile 'com.github.chrisbanes:PhotoView:2.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    compile 'com.squareup.okhttp3:okhttp:3.8.0'
    compile 'id.zelory:compressor:2.1.0'

    compile 'com.github.bumptech.glide:glide:3.8.0'
    compile 'testfairy:testfairy-android-sdk:1.+@aar'

    compile 'io.realm:realm-android:4.3.1'

}
apply plugin: 'realm-android'

Project Gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
        classpath 'io.realm:realm-gradle-plugin:4.3.1'
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        maven { url "https://jitpack.io" }
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Solution:

Remove compile 'io.realm:realm-android:4.3.1' from you application level build.gradle file and apply apply plugin: 'realm-android' just below apply plugin: 'com.android.application'. Your application level build.geadle will look like below

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.###.###"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 17
        versionName "1.17"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
//    compile 'com.github.chrisbanes:PhotoView:2.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    compile 'com.squareup.okhttp3:okhttp:3.8.0'
    compile 'id.zelory:compressor:2.1.0'

    compile 'com.github.bumptech.glide:glide:3.8.0'
    compile 'testfairy:testfairy-android-sdk:1.+@aar'
}

Gson deserializes with empty fileds

The result variable contains corrected parsed JSON.
But after deserialization List contains correct amount of items but all of them are empty.
How to fix it?

Gson gson = new Gson();
List<UnitView> unitViews = new ArrayList<UnitView>();
// https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type
Type typeToken = new TypeToken<List<UnitView>>() { }.getType();
unitViews = gson.fromJson(result,typeToken); 

Even if I do like

UnitView[] unitViews = gson.fromJson(result, UnitView[].class);

The fields of items are empty as well.

UnitView

public class UnitView implements Serializable {

    public String id ;

    public String name ;

    public String description ;

    public String deviceTypeName ;


    public String categoryID ;

    public String lastOnline ;

    public String latitude ;

    public String longitude ;

    public String atTime ;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getDeviceTypeName() {
        return deviceTypeName;
    }

    public String getCategoryID() {
        return categoryID;
    }

    public String getLastOnline() {
        return lastOnline;
    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public String getAtTime() {
        return atTime;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setDeviceTypeName(String deviceTypeName) {
        this.deviceTypeName = deviceTypeName;
    }

    public void setCategoryID(String categoryID) {
        this.categoryID = categoryID;
    }

    public void setLastOnline(String lastOnline) {
        this.lastOnline = lastOnline;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public void setAtTime(String atTime) {
        this.atTime = atTime;
    }
}

JSON DATA

[{"ID":"294","Name":"Foton Tunland  № F110","Description":null,"DeviceTypeName":"Техника ТО","CategoryID":"18","LastOnline":"19.12.2017 20:38:04","Latitude":"11,40119","Longitude":"11,42403","AtTime":"19.12.2017 20:38:04"},{"ID":"295","Name":"DML LP1200  № 9793","Description":null,"DeviceTypeName":"Буровой станок дизельный","CategoryID":"15","LastOnline":null,"Latitude":null,"Longitude":null,"AtTime":null}]

Solution:

Ok , the problem is that the parser is case-sensitive, you can change the name of your attributes to match the name of the json value of you could use the SerializedName annotation like this:

@SerializedName("ID")
public String id ;
@SerializedName("Name")
    public String name ;
@SerializedName("Description")
    public String description;
...

or

    public String ID ;
    public String Name ;
    public String Description ;
...

Some drawables cannot be found

After I had added some more vector drawables, I noticed that some of the previous ones are not working (about 11). With the rest of them I don’t have any problems – they are shown properly. I link every drawable in Java class with method like image.setImageResource(R.drawable.path_to_image); and most of them are linked without any problems. I have such a problem with just a few ones.
After running an app and trying to show these drawables I got such error:

Unable to find resource: 2131099763
android.content.res.Resources$NotFoundException: Drawable com.example.example_app:drawable/f_user_achievements_learning1h with resource ID #0x7f060073
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/f_user_achievements_learning1h.xml from drawable resource ID #0x7f060073
    at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:725)
    at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:571)
    at android.content.res.Resources.getDrawable(Resources.java:767)
    at android.content.Context.getDrawable(Context.java:525)
    at android.widget.ImageView.resolveUri(ImageView.java:840)
    at android.widget.ImageView.onMeasure(ImageView.java:982)
    at android.view.View.measure(View.java:19734)
    at android.widget.TableRow.measureChildBeforeLayout(TableRow.java:222)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1117)
    at android.widget.TableRow.onMeasure(TableRow.java:113)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.LinearLayout.forceUniformWidth(LinearLayout.java:1000)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:980)
    at android.widget.TableLayout.measureVertical(TableLayout.java:473)
    at android.widget.TableLayout.onMeasure(TableLayout.java:436)
    at android.view.View.measure(View.java:19734)
    at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1293)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.widget.ScrollView.onMeasure(ScrollView.java:340)
    at android.view.View.measure(View.java:19734)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:911)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19734)
    at android.widget.RelativeLayout.measureChild(RelativeLayout.java:676)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:479)
    at android.view.View.measure(View.java:19734)
    at android.widget.RelativeLayout.measureChild(RelativeLayout.java:676)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:479)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:671)
    at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
    at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1319)
    at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:736)
    at android.view.View.measure(View.java:19734)
    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687)
    at android.view.View.measure(View.java:19734)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
    at android.view.Choreographer.doCallbacks(Choreographer.java:683)
    at android.view.Choreographer.doFrame(Choreographer.java:619)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
 Caused by: java.lang.IllegalArgumentException: Path string cannot be empty.
    at android.util.PathParser.nCreatePathDataFromString(Native Method)
    at android.util.PathParser.-wrap1(PathParser.java)
    at android.util.PathParser$PathData.<init>(PathParser.java:74)
    at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:1556)
    at android.graphics.drawable.VectorDrawable$VFullPath.inflate(VectorDrawable.java:1507)
    at android.graphics.drawable.VectorDrawable.inflateChildElements(VectorDrawable.java:693)
    at android.graphics.drawable.VectorDrawable.inflate(VectorDrawable.java:598)
    at android.graphics.drawable.DrawableInflater.inflateFromXml(DrawableInflater.java:130)
    at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1227)
    at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1200)
    at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:715)
        ... 74 more

This is the fragment of Java class, where I link drawable:

@Override
    protected void setChoiceState() {
        if(achievement.isAchieved()) {
            image.setAlpha(ITEM_CHOSEN);
            image.setImageResource(achievement.getResId());
        } else {
            image.setAlpha(ITEM_NOT_CHOSEN);
            image.setImageResource(R.drawable.f_user_achievements_not_achieved);
        }
    }

Where achievement.getResId() is path to drawable. I’ve also tried to change it to raw path like R.drawable.path_to_drawable but it also didn’t work. However, line with: image.setImageResource(R.drawable.f_user_achievements_not_achieved); is working properly.

Here are my .gradle files:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '27.0.2'

    defaultConfig {
        applicationId "com.example.example_app"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
    }

    dexOptions {
        jumboMode true
        javaMaxHeapSize "2g"
    }
}

repositories {
    maven {
        url "https://maven.google.com"
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/gson-2.8.0.jar')
    compile files('libs/commons-lang-2.3.jar')
    compile files('libs/httpclient-4.5.3.jar')
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:support-v4:24.1.1'
    compile 'com.google.android.gms:play-services-ads:11.6.2'
    compile 'com.google.android.gms:play-services-auth:11.6.2'
    compile 'com.android.support:multidex:1.0.0'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

If you need any other files, just write a comment and I’ll attach them

EDIT

I added two extra drawables (both Vector Assets) – one which hadn’t been working and the other one with which there hadn’t been any problems. First one is not working but the seconds one is working properly, so can be problem with just xml file representing vector drawable?

Here is an xml file for one of not working vector drawables:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.000002"
        android:viewportHeight="24.000002">
    <path
        android:pathData="M12,12m-11.803,0a11.803,11.803 0,1 1,23.605 0a11.803,11.803 0,1 1,-23.605 0"
        android:strokeLineCap="round"
        android:fillAlpha="1"
        android:strokeColor="#ffffff"
        android:fillColor="#1b1b1b"
        android:strokeWidth="0.40124387"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="m8.02,15.376 l0,-1.975c0,-0.821 1.742,-1.929 1.742,-1.929l0,-0.662c0,0 -1.742,-1.031 -1.742,-1.852l0,-1.975"
        android:strokeLineCap="round"
        android:strokeColor="#ffffff"
        android:fillColor="#00000000"
        android:strokeWidth="1.03580773"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="m12.623,15.376 l0,-1.975c0,-0.821 -1.742,-1.929 -1.742,-1.929l0,-0.662c0,0 1.742,-1.031 1.742,-1.852l0,-1.975"
        android:strokeLineCap="round"
        android:strokeColor="#ffffff"
        android:fillColor="#00000000"
        android:strokeWidth="1.03580773"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="M7.18,5.604L13.463,5.604A0.295,0.295 117.507,0 1,13.759 5.9L13.759,6.087A0.295,0.295 0,0 1,13.463 6.382L7.18,6.382A0.295,0.295 0,0 1,6.885 6.087L6.885,5.9A0.295,0.295 117.507,0 1,7.18 5.604z"
        android:strokeLineCap="round"
        android:fillAlpha="1"
        android:strokeColor="#00000000"
        android:fillColor="#ffffff"
        android:strokeWidth="0.39954987"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="M7.18,15.977L13.463,15.977A0.295,0.295 0,0 1,13.759 16.273L13.759,16.459A0.295,0.295 0,0 1,13.463 16.755L7.18,16.755A0.295,0.295 0,0 1,6.885 16.459L6.885,16.273A0.295,0.295 0,0 1,7.18 15.977z"
        android:strokeLineCap="round"
        android:fillAlpha="1"
        android:strokeColor="#00000000"
        android:fillColor="#ffffff"
        android:strokeWidth="0.39954987"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="m8.853,15.506 l2.937,0 -1.43,-0.988z"
        android:strokeLineCap="round"
        android:fillAlpha="1"
        android:strokeColor="#ffb3cc"
        android:fillColor="#ffb3cc"
        android:strokeWidth="0.43446419"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="m8.909,8.698 l2.804,0c0.314,0.066 -0.754,1.004 -1.399,1.366C9.655,9.709 8.665,8.784 8.909,8.698Z"
        android:strokeLineCap="round"
        android:fillAlpha="1"
        android:strokeColor="#ffb3cc"
        android:fillColor="#ffb3cc"
        android:strokeWidth="0.40527168"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="m-21.276,14.911c0.008,0.022 0.418,1.042 0.911,2.265 0.49,1.223 0.9,2.24 0.905,2.256 0.019,0.049 0.873,0.049 0.892,0.003 0.006,-0.019 0.416,-1.037 0.905,-2.259 0.492,-1.223 0.903,-2.243 0.911,-2.265 0.014,-0.033 -0.046,-0.038 -0.418,-0.033l-0.432,0.008 -0.7,1.701c-0.383,0.935 -0.703,1.701 -0.711,1.701 -0.008,0 -0.328,-0.766 -0.711,-1.701l-0.7,-1.701 -0.432,-0.008c-0.372,-0.006 -0.432,0 -0.418,0.033z"
        android:fillAlpha="1"
        android:strokeColor="#00000000"
        android:fillColor="#ffffff"/>
    <path
        android:pathData=""
        android:strokeLineCap="round"
        android:fillAlpha="1"
        android:strokeColor="#00000000"
        android:fillColor="#ffb3cc"
        android:strokeWidth="0.84933162"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="M17.063,16.438m-2.344,0a2.344,2.344 0,1 1,4.689 0a2.344,2.344 0,1 1,-4.689 0"
        android:strokeLineCap="round"
        android:fillAlpha="1"
        android:strokeColor="#ffffff"
        android:fillColor="#00000000"
        android:strokeWidth="0.43581513"
        android:strokeLineJoin="round"
        android:strokeAlpha="1"/>
    <path
        android:pathData="m16.973,16.438 l0,1.101 0.16,0 0.161,0 0.004,-0.492 0.004,-0.491 0.036,-0.078c0.072,-0.156 0.209,-0.238 0.395,-0.238 0.122,0 0.207,0.033 0.266,0.106 0.08,0.098 0.082,0.105 0.087,0.676l0.004,0.517 0.167,0 0.166,0 0,-0.525c0,-0.58 -0.006,-0.653 -0.073,-0.783 -0.181,-0.36 -0.752,-0.396 -0.997,-0.064l-0.056,0.075 0,-0.453 0,-0.453 -0.161,0 -0.161,0 0,1.101z"
        android:fillAlpha="1"
        android:strokeColor="#00000000"
        android:fillColor="#ffb3cc"/>
    <path
        android:pathData="m15.704,15.553 l0,0.155 0.21,0 0.21,0 0,0.885 0,0.885 0.167,0 0.167,0 0,-1.039 0,-1.039 -0.377,0 -0.377,0 0,0.155z"
        android:fillAlpha="1"
        android:strokeColor="#00000000"
        android:fillColor="#ffb3cc"/>
</vector>

Solution:

There is a line with an empty path data in the middle of the file. Maybe that’s the culprit (doesn’t look right for sure):

<path
    android:pathData=""
    android:strokeLineCap="round"
    android:fillAlpha="1"
    android:strokeColor="#00000000"
    android:fillColor="#ffb3cc"
    android:strokeWidth="0.84933162"
    android:strokeLineJoin="round"
    android:strokeAlpha="1"/>

Listen DialogFragment dismiss event from ViewPager Fragment

There are lot of (duplicate) questions and answers are available, I went through almost all of them and failed. On reference of this question, I made some changes recently.

Brief : In my app, MainActivity holds Fragment View Pager and FrangmentA,B and C. FrangmentA Shows a DialogFragment CDialog onClik. After dismissing CDialog I need to Call FragmentA’s doReload() which is not happening here.

MainActivity

protected void onCreate(Bundle savedInstanceState){
                          ...

            mSectionsPageAdapter = new FragmentAdapter(getSupportFragmentManager());
            mViewPager = (ViewPager) findViewById(R.id.container);
            setupViewPager(mViewPager);
            TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(mViewPager);
            int defaultValue = 0;
            int page = getIntent().getIntExtra("One", defaultValue);
            mViewPager.setCurrentItem(page);
    }

    private void setupViewPager(ViewPager viewPager)
        {
            FragmentAdapter adapter = new 
            FragmentAdapter(getSupportFragmentManager());
            adapter.addFragment(new FragmentA(), "FragA");
            adapter.addFragment(new FragmentB(), "FragB");
            adapter.addFragment(new FragmentC(), "FragC");
            viewPager.setAdapter(adapter);
        }

FragmentA

    public class FragmentA extends Fragment implements CDialog.Dismissed{
    @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ...
    button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                   FragmentManager fm =  getActivity().getFragmentManager();
                    DialogFragment f = new CDialog();
                    f.show(fm, "CDialog");
                    }
            });

 @Override
    public void dialogDismissed() {
        Log.e(DFD_1, "dialogDismiss Called" );// <-- This is not working*
        doReload();
    }
    }

And CDialogue

public  class CDialog extends DialogFragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
                                    ....
                      return v;
   }
  @Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
           ...

            dfd_1.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                        getDialog().dismiss(); //<--when this happens*
                    }
            });

}
    @Override
        public void onDismiss(DialogInterface dialog) {
            if (getActivity() != null && getActivity() instanceof Dismissed) {
                ((Dismissed) getActivity()).dialogDismissed();
            }
            super.onDismiss(dialog);
        }

        public interface Dismissed {
            public void dialogDismissed();  //<-- FragmentA implements this 
        }
}

Solution:

You can always have direct callback to your Fragment itself.

First step, is to set targetFragment using setTargetFragment():

DialogFragment#setTargetFragment(Fragment fragment, int requestCode);

I do it this way:

public void showDialogFragment(Fragment targetFragment, AppCompatDialogFragment appCompatDialogFragment, int requestCode) {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    appCompatDialogFragment.setTargetFragment(targetFragment, requestCode);
    fragmentTransaction.add(appCompatDialogFragment, appCompatDialogFragment.getClass().getSimpleName());
    fragmentTransaction.commitAllowingStateLoss();
}

and then call to this method to open dialog fragment as:

public static final int RC_CDIALOG = 111;

button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
               showDialogFragment(FragmentA.this, new CDialog(), RC_CDIALOG);
            }
        });

Then, in your DialogFragment’s onDismissListener(), have some code like below:

@Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);

    if (getTargetFragment() instanceof FragmentA)
        ((FragmentA) getTargetFragment()).doReload();

}

What you did this way is:

Show Dialog Fragment “CDialog” along with telling it that your target fragment is “FragmentA” whose reference you can use incase you have something to do with it. In your case you had to call doReload();