Menu
  • HOME
  • TAGS

IBM MobileFirst - Can't subscribe, notification token is not updated on the server

Tag: android,mobilefirst,mobilefirst-server

I'm unable to subscribe my application, built using IBM MobileFirst Platform, for push notification. I'm getting the error message

WLPush.isAbleToSubscribe in WLPush.java:414 :: Can't subscribe, notification token is not updated on the server

LogCat

05-06 10:20:44.767  20941-20941/com.vdot.pushdemo D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-06 10:20:44.887  20941-21582/com.vdot.pushdemo D/WLClient﹕ WLClient.createInstance in WLClient.java:213 :: WLClient has already been created.
05-06 10:20:44.917  20941-21582/com.vdot.pushdemo D/GCMClientFactory﹕ GCMClientFactory.getInstance in GCMClientFactory.java:25 :: Using GCMAPIClient
05-06 10:20:44.937  20941-21582/com.vdot.pushdemo W/com.worklight.wlclient.api.WLPush﹕ WLPush.unregisterReceivers in WLPush.java:792 :: unregisterReceivers:Receiver not registered: [email protected]
05-06 10:20:44.967  20941-21582/com.vdot.pushdemo D/wl.request﹕ WLRequestSender.run in WLRequestSender.java:40 :: Sending request http://10.136.78.232:10080/MFPushDemo/apps/services/api/AndroidPushDemo/Androidnative/init
05-06 10:20:45.267  20941-21681/com.vdot.pushdemo I/System.out﹕ pool-3-thread-6 calls detatch()
05-06 10:20:45.307  20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.updateToken in WLPush.java:521 :: Registering at the GCM server.
05-06 10:20:45.327  20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.clearSubscribedEventSources in WLPush.java:596 :: Clearing notification subscriptions.
05-06 10:20:45.337  20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.updateSubscribedEventSources in WLPush.java:614 :: Updating notification subscriptions.
05-06 10:20:45.347  20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.clearSubscribedTags in WLPush.java:607 :: Clearing tag notification subscriptions.
05-06 10:20:45.357  20941-21681/com.vdot.pushdemo D/com.demo.push﹕ Mode Connect Success
05-06 10:20:45.367  20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.updateSubscribedTags in WLPush.java:635 :: Updating tag notification subscriptions.
05-06 10:20:45.497  20941-21582/com.vdot.pushdemo D/GCMAPIClient﹕ GCMAPIClient$1.doInBackground in GCMAPIClient.java:45 :: Successfully registered with GCM using Google Play Services. Returned deviceToken:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
05-06 10:20:45.507  20941-21682/com.vdot.pushdemo D/com.demo.push﹕ onReadyToSubscribe
05-06 10:20:50.697  20941-20941/com.vdot.pushdemo D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-06 10:20:50.827  20941-21582/com.vdot.pushdemo D/WLClient﹕ WLClient.createInstance in WLClient.java:213 :: WLClient has already been created.
05-06 10:20:50.847  20941-21582/com.vdot.pushdemo D/GCMClientFactory﹕ GCMClientFactory.getInstance in GCMClientFactory.java:25 :: Using GCMAPIClient
05-06 10:20:50.857  20941-21582/com.vdot.pushdemo W/com.worklight.wlclient.api.WLPush﹕ WLPush.unregisterReceivers in WLPush.java:792 :: unregisterReceivers:Receiver not registered: [email protected]
05-06 10:20:50.877  20941-21582/com.vdot.pushdemo E/com.worklight.wlclient.api.WLPush﹕ WLPush.isAbleToSubscribe in WLPush.java:414 :: Can't subscribe, notification token is not updated on the server

Main Activity

package com.vdot.pushdemo;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.worklight.wlclient.WLRequestListener;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLEventSourceListener;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLOnReadyToSubscribeListener;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLPush;
import com.worklight.wlclient.api.WLPushOptions;
import com.worklight.wlclient.api.WLRequestOptions;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;


public class MainActivity extends Activity {

    Button Push;
    Button Sub;
    Button UnSub;
    Button Test;
    Button Logout;
    WLClient client;
    WLPush push;

    final String realm = "SampleAppRealm";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Push =(Button) findViewById(R.id.button0);
        Sub =(Button) findViewById(R.id.button1);
        UnSub =(Button) findViewById(R.id.button2);
        Test =(Button) findViewById(R.id.button3);
        Logout = (Button) findViewById(R.id.button4);
        setupUIEvents();
    }




    void setupUIEvents(){

        Push.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    client = WLClient.createInstance(MainActivity.this);
                    push = client.getPush();

                    PushListener listener = new PushListener(PushListener.MODE_CONNECT, MainActivity.this);
                    push.setOnReadyToSubscribeListener(listener);
                    client.registerChallengeHandler(new LoginChallengeHandler(realm, "IBM User", MainActivity.this));
                    client.connect(listener);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });

        Sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                client = WLClient.createInstance(MainActivity.this);

                client.getPush().subscribe("myAndroid",new WLPushOptions(), new PushListener(PushListener.MODE_SUBSCRIBE,MainActivity.this));
            }
        });

        UnSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });

        Test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                client = WLClient.createInstance(MainActivity.this);
                PushListener listener = new PushListener(PushListener.MODE_CONNECT, MainActivity.this);
                client.registerChallengeHandler(new LoginChallengeHandler(realm, "IBM User", MainActivity.this));
                client.connect(listener);
               int i = 0;
                while (i < 10000)
                {
                    i++;
                }

                String adapterName = "PushAdapter";
                String procedureName = "getSecretData";

                WLProcedureInvocationData invocationData =
                        new WLProcedureInvocationData(adapterName, procedureName);


                Object[] parameters = new Object[]{};
                invocationData.setParameters(parameters);

                WLRequestOptions options = new WLRequestOptions();
                options.setTimeout(30000);


                client.getInstance().invokeProcedure(invocationData, listener, options);
            }
        });

        Logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                client = WLClient.createInstance(MainActivity.this);
                client.logout(realm,new MyListener());
            }
        });
    }

    public class MyListener implements WLRequestListener{

        @Override
        public void onSuccess(WLResponse wlResponse) {
            Log.d("com.demo.push", "Log out success");
        }

        @Override
        public void onFailure(WLFailResponse wlFailResponse) {
            Log.d("com.demo.push", "Log out failed");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (push != null)
            push.setForeground(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

        if(code == ConnectionResult.SERVICE_MISSING || code == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED || code == ConnectionResult.SERVICE_DISABLED) {
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(code, this, 1);
            dialog.show();
        }
        if (push != null)
            push.setForeground(true);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (push != null)
            push.unregisterReceivers();
    }

}

Login Challenge Handler

package com.vdot.pushdemo;

import android.content.Context;
import android.content.Intent;


import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLRequestOptions;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.challengehandler.ChallengeHandler;


public class LoginChallengeHandler extends ChallengeHandler {

    private String userName;
    private Context currentContext;


    public LoginChallengeHandler(String realm, String user, Context ctx) {
        super(realm);
        userName = user;
        currentContext = ctx;


    }

    @Override
    public boolean isCustomResponse(WLResponse wlResponse) {
        try {
            if(wlResponse!= null &&
                    wlResponse.getResponseJSON()!=null &&
                    wlResponse.getResponseJSON().isNull("authRequired") != true &&
                    wlResponse.getResponseJSON().getBoolean("authRequired") == true){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public void handleChallenge(WLResponse wlResponse) {

        submitLogin(userName,"dummyPassword");
    }

    @Override
    public void onSuccess(WLResponse wlResponse) {

       // activity.Loader("Authenticate","Authentcating via VDOT secure server",false);

        if(isCustomResponse(wlResponse))
        {
            handleChallenge(wlResponse);
        }

        else
        {

            submitSuccess(wlResponse);

        }
    }

    @Override
    public void onFailure(WLFailResponse wlFailResponse) {

        submitFailure(wlFailResponse);
    }


    public void submitLogin(String userName, String password){

        Object[] parameters = new Object[]{userName, password};
        WLProcedureInvocationData invocationData = new WLProcedureInvocationData("PushAdapter", "submitAuthentication");
        invocationData.setParameters(parameters);
        WLRequestOptions options = new WLRequestOptions();
        options.setTimeout(30000);
        submitAdapterAuthentication(invocationData, options);

    }


}

Push Listener

package com.vdot.pushdemo;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;

import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLEventSourceListener;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLOnReadyToSubscribeListener;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;



public class PushListener implements WLOnReadyToSubscribeListener,WLResponseListener,WLEventSourceListener {

    public static final int MODE_CONNECT = 0;
    public static final int MODE_SUBSCRIBE = 1;
    public static final int MODE_UNSUBSCRIBE =2;

    private int mode ;
    private Context currentContext;

    public PushListener(int mode, Context ctx){
        this.mode = mode;
        currentContext = ctx;
    }

    @Override
    public void onReadyToSubscribe() {

        WLClient.getInstance().getPush().registerEventSourceCallback("myAndroid", "PushAdapter","PushEventSource", this );

        Log.d("com.demo.push", "onReadyToSubscribe");

    }

    @Override
    public void onReceive(String arg0, String arg1) {

    }

    @Override
    public void onSuccess(WLResponse wlResponse) {

            switch (mode){
            case MODE_CONNECT:
                // connect =true ;
                Log.d("com.demo.push", "Mode Connect Success");
                break;

            case MODE_SUBSCRIBE:

                Log.d("com.demo.push", "Mode Subscribe Success ");
                break;

            case MODE_UNSUBSCRIBE:
                // unsubscribe = true;
                break;

        }
    }

    @Override
    public void onFailure(WLFailResponse wlFailResponse) {
        switch (mode){
            case MODE_CONNECT:
                Log.d("com.demo.push", "Mode Connect Fail");
                break;

            case MODE_SUBSCRIBE:
                Log.d("com.demo.push", "Mode Subscribe Fail");
                break;

            case MODE_UNSUBSCRIBE:
                //  unsubscribe = false;
                break;

        }
    }
}

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vdot.pushdemo" >

    <permission android:name="com.vdot.pushdemo.permission.C2D_MESSAGE" android:protectionLevel="signature" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="com.vdot.pushdemo.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.parse.push.notification_icon"
            android:resource="@drawable/push" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"

            android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="com.vdot.pushdemo.MainActivity.NOTIFICATION" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <service android:name="com.worklight.wlclient.push.GCMIntentService" />
        <receiver android:name="com.worklight.wlclient.push.WLBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.vdot.pushdemo" />
            </intent-filter>
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.vdot.pushdemo" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

WLCLient.Properties

wlServerProtocol = http
wlServerHost = NG00164378
wlServerPort = 10080
wlServerContext = /MFPushDemo/
wlAppId = AndroidPushDemo
wlAppVersion = 1.0
wlEnvironment = Androidnative
wlUid = wY/mbnwKTDDYQUvuQCdSgg==
wlPlatformVersion = 7.0.0.0
#languagePreferences = Add locales in order of preference (e.g. en, fr, fr-CA)
#For Push Notifications,uncomment below line and assign value to it
GcmSenderId = 64XXXXXXXXXX

Authentication Config.XML

<?xml version="1.0" encoding="UTF-8"?>
<tns:loginConfiguration xmlns:tns="http://www.worklight.com/auth/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

     <staticResources>

        <resource id="subscribeServlet" securityTest="SubscribeServlet">
            <urlPatterns>/subscribeSMS*;/receiveSMS*;/ussd*</urlPatterns>
        </resource>

    </staticResources> 


     <securityTests>
     <mobileSecurityTest name="MySecurityTest">
            <testUser realm="SampleAppRealm"/>
            <testDeviceId provisioningType="none"/>
        </mobileSecurityTest>


        <customSecurityTest name="SubscribeServlet">
            <test realm="SubscribeServlet" isInternalUserID="true"/>
        </customSecurityTest>           

    </securityTests> 

    <realms>
        <realm name="SampleAppRealm" loginModule="AuthLoginModule">
            <className>com.worklight.integration.auth.AdapterAuthenticator</className>
            <parameter name="login-function" value="PushAdapter.onAuthRequired"/>
            <parameter name="logout-function" value="PushAdapter.onLogout"/>
        </realm>



        <realm name="SubscribeServlet" loginModule="rejectAll">
            <className>com.worklight.core.auth.ext.HeaderAuthenticator</className>          
        </realm>




    </realms>

    <loginModules>

    <loginModule name="AuthLoginModule">
            <className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
        </loginModule>

        <loginModule name="requireLogin" expirationInSeconds="-1">
            <className>com.worklight.core.auth.ext.SingleIdentityLoginModule</className>
        </loginModule>

        <loginModule name="rejectAll">
            <className>com.worklight.core.auth.ext.RejectingLoginModule</className>
        </loginModule>

        <!-- Required for Trusteer - wl_basicTrusteerFraudDetectionRealm -->        
        <!-- loginModule name="trusteerFraudDetectionLogin" expirationInSeconds="300">
            <className>com.worklight.core.auth.ext.TrusteerLoginModule</className>
        </loginModule-->

        <!-- For websphere -->
        <!-- loginModule name="WASLTPAModule" expirationInSeconds="-1">
            <className>com.worklight.core.auth.ext.WebSphereLoginModule</className>
        </loginModule -->

        <!-- Login module for User Certificate Authentication -->
        <!-- <loginModule name="WLUserCertificateLoginModule" expirationInSeconds="-1">
            <className>com.worklight.core.auth.ext.UserCertificateLoginModule</className>
        </loginModule> -->


        <!-- For enabling SSO with no-provisioning device authentication -->
        <!-- <loginModule name="MySSO" ssoDeviceLoginModule="WLDeviceNoProvisioningLoginModule" expirationInSeconds="-1">
            <className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
        </loginModule> -->


        <!-- For enabling SSO with auto-provisioning device authentication -->
        <!-- <loginModule name="MySSO" ssoDeviceLoginModule="WLDeviceAutoProvisioningLoginModule" expirationInSeconds="-1">
            <className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
        </loginModule> -->
    </loginModules>

</tns:loginConfiguration>

Application Descriptor

<?xml version="1.0" encoding="UTF-8"?>

<nativeAndroidApp id="AndroidPushDemo" platformVersion="7.0.0.00.20150312-0731"
    version="1.0" xmlns="http://www.worklight.com/native-android-descriptor" securityTest="MySecurityTest">

    <displayName>AndroidPushDemo</displayName>
    <description>AndroidPushDemo</description>
    <publicSigningKey></publicSigningKey>
    <packageName></packageName>
    <accessTokenExpiration>3600</accessTokenExpiration>
    <userIdentityRealms></userIdentityRealms>

    <pushSender key="AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" senderId="XXXXXXXXXX"/>
</nativeAndroidApp>

PushAdapter

function onAuthRequired(headers, errorMessage){
    WL.Logger.error("onAuthRequired");
       errorMessage = errorMessage ? errorMessage : null;

       return {
       authRequired: true,
       errorMessage: errorMessage
       };
       }


function onLogout(){
    WL.Logger.debug("Logged out");
}

function getSecretData(){

    WL.Logger.error("getSecretData");
    return {
        secretData: "A secret data to invoke authentication"
    };
}


function submitAuthentication(username, password){
       // if (username==="user" && password === "user"){
        WL.Logger.error("submitAuthentication");
            var userIdentity = {
                    userId: username,
                    displayName: username,
                    attributes: {
                        foo: "bar"
                    }
            };

            WL.Server.setActiveUser("SampleAppRealm", userIdentity);



            return {
                authRequired: false,
                user :userIdentity
            };
       // }

       // return onAuthRequired(null, "Invalid login credentials");
    }

WL.Server.createEventSource({
    name: 'PushEventSource',
    onDeviceSubscribe: 'deviceSubscribeFunc',
    onDeviceUnsubscribe: 'deviceUnsubscribeFunc',
    securityTest:'MySecurityTest'
});

function deviceSubscribeFunc(userSubscription, deviceSubscription){
    WL.Logger.error("deviceSubscribeFunc");
    WL.Logger.debug(">> deviceSubscribeFunc");
}

function deviceUnsubscribeFunc(userSubscription, deviceSubscription){
    WL.Logger.debug(">> deviceUnsubscribeFunc");
}

function submitNotification(userId, notificationText) {
    var userSubscription = WL.Server.getUserNotificationSubscription('PushAdapter.PushEventSource', userId);

    if (userSubscription === null) {
        return { result: "No subscription found for user :: " + userId };
    }

    var badgeDigit = 1;
    var notification = WL.Server.createDefaultNotification(notificationText, badgeDigit, {custom:"data"});

        WL.Server.notifyAllDevices(userSubscription, notification);

    return {
        result: "Notification sent to user :: " + userId
    };
}

Best How To :

As per the documentation http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.0.0/com.ibm.worklight.apiref.doc/html/refjava-worklight-android-native/html/com/worklight/wlclient/api/WLClient.html?lang=en createinstance() method needs to be invoked at the beginning of the main activity of the application. Subsequent calls need to use getInstance() ... In the code you have pasted I see multiple calls to createInstance() this could overwrite the previous instance that is updated with the token. Hence can you use createInstance() once and getInstance() in the subsequent calls.

How to resolve Out of Memory Error on Bitmap in Android?

android,android-intent,android-activity,bitmap

use following method..... **************************************************** Bitmap bm = ShrinkBitmap(imagefile, 300, 300); image.setImageBitmap(bm); Bitmap ShrinkBitmap(String file, int width, int height) { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions); int heightRatio =(int)Math.ceil(bmpFactoryOptions.outHeight/(float)height); int widthRatio =...

Passing dynamic string resource to “setText()”

android

Try like this: Create a global variable like: private String name; then in "onCreateViewHolder" write like this: name= parent.getResources().getString(R.string.mac); now, in "onBindViewHolder" write like this: device.name.setText(name + data.macAddress); ...

Dagger 2 Custom Scope for each Fragment

android,android-fragments,dagger-2

Your understanding is correct. The named scopes allow you to communicate intention, but they all work the same way. For scoped provider methods, each Component instance will create 1 instance of the provided object. For unscoped provider methods, each Component instance will create a new instance of the provided object...

why is Android app publishing taking several days [on hold]

android,google-play,publishing

here is detail provided by the google and for more details http://www.appmakr.com/blog/how-long-app-approved/ https://somethingididnotknow.wordpress.com/2014/03/11/how-long-does-it-take-for-the-google-play-store-to-publish-my-app-in-beta/ Android application approval process in playstore ...

Error:(12) No resource identifier found for attribute 'scalteType' in package 'android'

android,android-studio

All the information you need is right here, before your eyes. No resource identifier found for attribute 'scalteType' in package 'android' There is no attribute called "scalteType" in ImageView. Find it in the layout file 'main.xml' and change to "scaleType"....

Android SQLite: Fast insert/update

java,android,sqlite

What would be a correct way for overwriting existing row? Specify a conflict resolution strategy, such as INSERT OR REPLACE INTO foo ... If the insert would result in a conflict, the conflicting row(s) are first deleted and then the new row is inserted....

Android Implicit Intent for Viewing a Video File

java,android,android-intent,uri,avd

Change your onClick method to below code. You should give the option to choose the external player. @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("https://youtu.be/jxoG_Y6dvU8"), "video/*"); startActivity(Intent.createChooser(intent, "Complete action using")); } ...

android imageView scale

android,imageview,scale

Try this code. adjustViewBounds attribute makes the ImageView the same size as image that you put in it. <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustViewBounds="true" /> If you need specific width or height change the wrap_content value....

Contexts and callbacks from asynchronous tasks

android,android-fragments,asynchronous

getActivity() returning null is a perfectly valid scenario which you should expect as well. This happens because by creating anonymous Handler in your onCreateView you're referencing Fragment which was already detached from Activity (therefore getActivity() returns null). Same goes for your AsyncTask - if you're creating it as an anonymous...

Is there any way to use a pre-existing database from Xamarin without copying it from Assets?

android,xamarin,xamarin.forms

You don't want to use it from assets, even if you could, because assets is a compressed read only file, part of your installation. You can't write updates into it, which kills 90% of database use. And its inefficient for reading as its zipped up. So you really do need...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]

java,android,eclipse,adt

In your MainActivity.java at line no 34 you are trying to initialize some widget that is not present in your xml layout which you have set it in your setContentView(R.layout.... That;s why you are geting nullpointerexception. EDIT: change your setContentView(R.layout.activity_main) to setContentView(R.layout.fragment_main)...

Android String if-statement

java,android,string

Correct me if I'm wrong. If you're saying that your code looks like this: new Thread(new Runnable() { public void run() { // thread code if (ready.equals("yes")) { // handler code } // more thread code }).start(); // later on... ready = "yes"; And you're asking why ready = "yes"...

How to restrict file copying shared using Content Provider in Android?

android,security

No, sorry. If you hand bytes over to a third-party app, that third-party app can do what it wants with those bytes. So only solution is to use some in-app pdf reader right? This will not completely stop people from copying your PDFs. However, it will limit attacks to those...

List view not returning to original state after clearing search

java,android,xml,android-activity,android-listfragment

You are operating on the original data instead of filtered data. You should maintain a reference to original data and use the filtered data for all other purposes. So that the original data is displayed when search is cleared. Replace all usages of mData with mFilteredData as below and only...

Keep HashMap with object data while app is idle - Android

android,android-activity

May be the activity is again loading that is onCreate() is called. So save the state and restore it. Use onSaveInstanceState() and onRestoreInstanceState(). Let me know whether it worked or not.

Android set clickable text to go one fragment to another fragment

java,android,android-fragments,spannablestring

If LoginActivity is a fragment class then it would be okay is you use setOnClickListener on textview. But for fragment change you have to change Intent to fragmentTransaction, Use something like, textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().beginTransaction().replace(R.id.container, new LoginActivity() ).addToBackStack("").commit(); }); But, if you want to...

BitmapFont class does not have getBound(String) method

java,android,libgdx

After the API 1.5.6 we have a different way to get the String bound. try this GlyphLayout layout = new GlyphLayout(); layout.setText(bitmapFont,"text"); float width = layout.width; float height = layout.height; and it's not recommended to create new GlyphLayout on each frame, create once and use it. ...

Crop does not work for gallery images

android,image,crop

Try this Working code Buttonclick to take camera dialog.show(); Add this inside Oncreate() captureImageInitialization(); try this it will work // for camera private void captureImageInitialization() { try { /** * a selector dialog to display two image source options, from * camera ‘Take from camera’ and from existing files ‘Select...

setOnClickListener error Null object

java,android

After super.onCreate(savedInstanceState); insert setContentView(R.layout.YourLayout); you need to make a request to a server in another thread. It might look like public class LoginTask extends AsyncTask<Void, Void, String>{ private String username; private String password; private Context context; public LoginTask(Context context, String username, String password) { this.username = username; this.password = password;...

Android programming, draw a rectangle with specific coordinates

android

http://android.okhelp.cz/draw-rect-android-basic-example/ http://alvinalexander.com/android/how-to-draw-rectangle-in-android-view-ondraw-canvas canvas.drawColor(Color.CYAN); Paint p = new Paint(); // smooths p.setAntiAlias(true); p.setColor(Color.RED); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(4.5f); canvas.drawRect(10, 10, 30, 30, p); ...

Twitter4j - cannot resolve method - setUsessl(boolean)

android,android-studio,twitter4j

Try to use the following configuration: ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthAuthenticationURL("https://api.twitter.com/oauth/request_token"); cb.setOAuthAccessTokenURL("https://api.twitter.com/oauth/access_token"); cb.setOAuthAuthorizationURL("https://api.twitter.com/oauth/authorize"); cb.setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token"); cb.setRestBaseURL("https://api.twitter.com/1.1/"); cb.setOAuthConsumerKey(consumerKey);...

Action view intent does not work

android,search-suggestion,custom-search-provider

Intent action names are case sensitive. Use this: android.intent.action.VIEW ...

Floating Action Button in Xamarin.Forms

android,xamarin,monodroid,xamarin.forms,floating-action-button

Before the official support library came out I ported the FAB over. There is now a Xamarin.Forms sample in my GitHub repo that you can use: https://github.com/jamesmontemagno/FloatingActionButton-for-Xamarin.Android...

Android custom calendar view disable specific dates

android,calendarview

Include CalendarPickerView in your layout XML. <com.squareup.timessquare.CalendarPickerView android:id="@+id/calendar_view" android:layout_width="match_parent" android:layout_height="match_parent" /> In the onCreate of your activity/dialog or the onCreateView of your fragment, initialize the view with a range of valid dates as well as the currently selected date. Calendar nextYear = Calendar.getInstance(); nextYear.add(Calendar.YEAR, 1); CalendarPickerView calendar = (CalendarPickerView) findViewById(R.id.calendar_view);...

Broken pipe error when executing Android method more than once?

java,android,illegalstateexception,broken-pipe

When you execute the command os.writeBytes("exit\n"); this ends your su session. The su process ends itself and the pipe your are using for writing commands to the su shell gets broken. Therefore if you want to execute another command you have to restart a new su session or do not...

android - service for interaction with wearable

android,android-service,android-wear,google-api-client,android-wear-data-api

override onCreate in your Service, and put the initialization of mGoogleApiClient in it private GoogleApiClient mGoogleApiClient; public void onCreate() { super.onCreate(); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); } ...

Notification whenever a new topic is created on mosquitto

android,mqtt,mosquitto,libmosquitto

A topics is only "created" when something is published to it the first time. There is no mechanism to detect this apart from subscribing to a wildcard topic that would match all topics of interest and triggering processing when the first message is received on a given topic. In the...

Action Bar activity is closed

android,android-actionbar

Nag and Maisse already provided you proper answers but if these answers not working try this. Check in style.xml to know which theme are you using for your activity. <!-- Base application theme. --> <style name="AppTheme" parent="android:Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> </style> to <!-- Base application theme. -->...

echo json_encode after mysql_query failure

php,android

You can use an if on the result. If mysql_query() fails it returns false: $result = mysql_query(/*the query*/); if(!$result){ //Do stuff here, the query failed //json_encode() } else { //Query succeeded } Sidenote: mysql_* is deprecated, I highly recommend to switch to mysqli_* or PDO...

Robolectric 3 : Load test specific resource

android,unit-testing,robolectric

Instead of putting the json in src/test/res/raw you might want to put it in src/test/resources/ and then you can use it ( with the latest build plugin and latest AS ) via getResource Be aware that there is a bug in older versions - you need to use AS from...

Blank screen on GridView

android,arrays,gridview

I executed ur code. Just add numberView.setTextColor(Color.BLACK); and it will work! :)...

Set value for Spinner with custom Adapter in Android

android,dynamic,android-arrayadapter,android-spinner

@Haresh Chhelana example is good, However if you want to show both name and code in spinner after selecting, check this out. List<Map<String, String>> items = new ArrayList<Map<String, String>>(); for (int i = 0; i < JA.length(); i++) { json = JA.getJSONObject(i); mapData = new HashMap<String, String>(); mapData.put("name", json.getString("Name")); mapData.put("code",...

Can I install 2 or more Android SDK when using Eclipse

java,android,eclipse,sdk,versions

There shouldn't be any problem if you use the latest SDK version ; actually, this is recommended. However, make sure to set the correct "Target SDK", i.e. the highest android version you have successfully tested your app with, and the "Minimum Required SDK" as well....

how does android ImageView resize my image?

android

I'm not sure what are you trying to do, are you trying to have the imageview to adapt to your image's size or are you trying to have your image view at a fixed size? When the image is shown on a xhdpi screen will the image be scaled to...

Get current latitude and longitude android

java,android,gps,geolocation,location

See my post at http://gabesechansoftware.com/location-tracking/. The code you're using is just broken. It should never be used. The behavior you're seeing is one of the bugs- it doesn't handle the case of getLastLocation returning null, an expected failure. It was written by someone who kind of knew what he was...

Why i get can not resolve method error in class android?

android,json

You didn't create setName() method in Person class. public class Person { private String name; private String country; private String twitter; //getters & setters.... public void setName(String pName) { this.name = pName; } public void getName() { return this.name; } } ...

error: cannot find symbol class AsyncCallWS Android

java,android,web-services

On the link you post, I see a class like below. Create this class in your project before using it. private class AsyncCallWS extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { Log.i(TAG, "doInBackground"); getFahrenheit(celcius); return null; } @Override protected void onPostExecute(Void result) { Log.i(TAG, "onPostExecute"); tv.setText(fahren +...

Getting particular view from expandable listview

java,android,listview,android-fragments,expandablelistview

You shouldn't pass your view item form a fragment to an other. You should retrieve the object associated with your group view, pass this object to your second/edition fragment. You can use setTargetFragment(...) and onActivityResult(...) to send the modified text from your second to your first fragment. And then you...

Bluetooth pairing - how to show the simple Cancel/Pair dialog?

android,android-intent,bluetooth,android-bluetooth,bluetooth-oob

You are being prompted for entering the pin because that is what you are requesting in your pairingIntent. Instead of using pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.PAIRING_VARIANT_PIN); pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 1234); Use pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PASSKEY_CONFIRMATION); As mentioned here, The user will be prompted to confirm the passkey displayed on the screen or an app will confirm the...

Problems implementing ViewHolder pattern

android,design-patterns

Try like this... public View getView(int poisition, View convertView , ViewGroup parent) { ViewHolder crimeHolder = null; //If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_crime, null); crimeHolder = new ViewHolder(); crimeHolder.titleTextView = (TextView)convertView.findViewById(R.id.listItemTitleTextView); crimeHolder.dateTextView = (TextView)convertView.findViewById(R.id.listItemDateTextView); crimeHolder.solvedCheckBox =...

how to add menu items to action bar in more than 30 activities

android,android-activity,android-studio,menu,menuitem

Option A A base Activity class that implements the logic for the menu items - in this case all 30 of your Activities should extend the base Activity. This approach has the serious limitation that it forces you to extend a class even though you may need to extend another...

adapter.notifyDataSetChanged() not working when I update ArrayList

android,android-listview

I have one way Create refresh method in your Adapter like public void refresh(ArrayList<Aviso> itemsw) { this.items = itemsw; notifyDataSetChanged(); } Now you just called this method from your Activity Aviso aviso = new Aviso(); aviso.setTitle("MMMMMMMMMMMMMMMMMMMMMM"); aviso.setDescription("Deskribapena"); aviso.setPubDate("Wed, 19 Mar 2016 12:40:00 GMT"); aviso.setDcDate("2016-03-19T12:40:00Z"); avisosList.add(aviso); adapter.refresh(avisosList); EDIT: To add the...

Get element starting with letter from List

java,android,list,indexof

The indexOf method doesn't accept a regex pattern. Instead you could do a method like this: public static int indexOfPattern(List<String> list, String regex) { Pattern pattern = Pattern.compile(regex); for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s != null && pattern.matcher(s).matches()) { return...

Facebook Android API asks for additional permission

android,facebook,facebook-graph-api

Use the loginManager to add more permission. you can add it on click button or on create view or fragment LoginManager.getInstance().logInWithReadPermissions( fragmentOrActivity, Arrays.asList("user_friends")); You can also get AccessToken via following if needed after getting new permission AccessToken.getCurrentAccessToken() ...

Is there any sdk to log exceptions, events and errors in production app?

android,logging,error-handling,sdk,production

Flurry analytics crashlytics They will give you the logs and errors in production app..I think this will suits you well...

How to set speaker phone off when the app is killed by the “Recent App drawer”

android,android-audiomanager,ondestroy

Use a service like: public class FirstService extends Service { private AudioManager audioManager; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onDestroy() { super.onDestroy(); audioManager.setSpeakerphoneOn(false); //Turn of speaker } } public void onDestroy () Added in API level 1 Called by the system to notify a...

custom arraylist get distinct

java,android

It's not possible to do this using only the ArrayList. Either implement your own method which can be as simple as: private List<mystatistik> getAllUniqueEnemies(List<mystatistik> list){ List<mystatistik> uniqueList = new ArrayList<mystatistik>(); List<String> enemyIds = new ArrayList<String>(); for (mystatistik entry : list){ if (!enemyIds.contains(entry.getEnemyId())){ enemyIds.add(entry.getEnemyId()); uniqueList.add(entry); } } return uniqueList; } Or...

Fixed element in android?

android,xml,android-fragments

You need a FrameLayout. In a FrameLayout, the children are overlapped on top of each other with the last child being at the topmost. activity_main.xml <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:fab="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"...

Add a ListView or RecyclerView to new NavigationView

android,listview,recyclerview,navigationview

You can just nest the ListView or RecyclerView inside the NavigationView. <?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"> <FrameLayout...

Android Espresso: Test running failed. No test results Empty test suite. Why?

android,android-espresso

Note that you are using the deprecated ActivityInstrumentationTestCase2 and that TestCases like ActivityInstrumentationTestCase2 or ServiceTestCase are deprecated in favor of ActivityTestRule or ServiceTestRule. So try switchwing to using the rules, which is actually pretty straightforward. Also, be sure to use the correct annotations. Check my other answer here to get...