lundi 29 juin 2015

Error in starting emulator in android studio


I got this error when start emulator please help me i tried many solutions. Updated graphics drivers, ram changes and screen resolution is 1280*1024.

Logcat error:

Failed to create Context 0x3005
could not get wglGetExtensionsStringARB
emulator: WARNING: Could not initialize OpenglES emulation, using software renderer.
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
emulator: device fd:512
could not get wglGetExtensionsStringARB
Could not initialize emulated framebufferHAX is not working and emulator runs in emulation mode
emulator: The memory needed by this VM exceeds the driver limit.
ERROR: Could not create window texture: Texture dimensions are limited to 2048x2048


Overwrite default list view highlighted color in AppCompat theme


My application's main theme inherits from Theme.AppCompat, and I've created a selector that allows for the Ripple effect to take place when you press and focus a button on Lollipop.

However, when I go back to a 4.0 device, it defaults back to an ugly blue color when I focus a list view item. I've looked everywhere for the trait that defines this color hoping to override it without any luck - any idea how I can do this?


Android get files from pc folder


I have a problem with the connection from my Android device to my local PC. I want to get all the files from a folder that is shared in my pc to everyone.

This is the code that I have:

private void connectToPC(){
        try {
            String username = "Alex";
            String password = ".";
            String sharedFolder = "Fisiere Date Senzori";
            String path = "smb://"+ip+"/Users/Alex/Documents/"+sharedFolder+"/";

            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",username,password);
            SmbFile smbFile = new SmbFile(path,auth);

            String[] files = smbFile.list();

            for (String fileName : files) {
                Log.d("log_tag", "Fisier: " + fileName);
            }

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

and this is the result that I get:

06-29 22:35:37.752: W/System.err(17081): jcifs.smb.SmbException: Failed to connect to server
06-29 22:35:37.752: W/System.err(17081): java.net.UnknownHostException: null
06-29 22:35:37.752: W/System.err(17081):    at jcifs.UniAddress.getAllByName(UniAddress.java:315)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.getFirstAddress(SmbFile.java:810)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.connect(SmbFile.java:897)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.connect0(SmbFile.java:826)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.resolveDfs(SmbFile.java:664)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.send(SmbFile.java:726)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.doFindFirstNext(SmbFile.java:1930)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.doEnum(SmbFile.java:1682)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.list(SmbFile.java:1653)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.list(SmbFile.java:1550)
06-29 22:35:37.752: W/System.err(17081):    at com.rasp.pi.StartingPoint.connectToPC(StartingPoint.java:149)
06-29 22:35:37.752: W/System.err(17081):    at com.rasp.pi.StartingPoint.onCreate(StartingPoint.java:56)
06-29 22:35:37.752: W/System.err(17081):    at android.app.Activity.performCreate(Activity.java:6289)
06-29 22:35:37.752: W/System.err(17081):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
06-29 22:35:37.752: W/System.err(17081):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647)
06-29 22:35:37.752: W/System.err(17081):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759)
06-29 22:35:37.752: W/System.err(17081):    at android.app.ActivityThread.access$900(ActivityThread.java:178)
06-29 22:35:37.752: W/System.err(17081):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
06-29 22:35:37.752: W/System.err(17081):    at android.os.Handler.dispatchMessage(Handler.java:102)
06-29 22:35:37.752: W/System.err(17081):    at android.os.Looper.loop(Looper.java:145)
06-29 22:35:37.752: W/System.err(17081):    at android.app.ActivityThread.main(ActivityThread.java:5944)
06-29 22:35:37.752: W/System.err(17081):    at java.lang.reflect.Method.invoke(Native Method)
06-29 22:35:37.752: W/System.err(17081):    at java.lang.reflect.Method.invoke(Method.java:372)
06-29 22:35:37.752: W/System.err(17081):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
06-29 22:35:37.752: W/System.err(17081):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.connect0(SmbFile.java:828)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.resolveDfs(SmbFile.java:664)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.send(SmbFile.java:726)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.doFindFirstNext(SmbFile.java:1930)
06-29 22:35:37.752: W/System.err(17081):    at jcifs.smb.SmbFile.doEnum(SmbFile.java:1682)
06-29 22:35:37.762: W/System.err(17081):    at jcifs.smb.SmbFile.list(SmbFile.java:1653)
06-29 22:35:37.762: W/System.err(17081):    at jcifs.smb.SmbFile.list(SmbFile.java:1550)
06-29 22:35:37.762: W/System.err(17081):    at com.rasp.pi.StartingPoint.connectToPC(StartingPoint.java:149)
06-29 22:35:37.762: W/System.err(17081):    at com.rasp.pi.StartingPoint.onCreate(StartingPoint.java:56)
06-29 22:35:37.762: W/System.err(17081):    at android.app.Activity.performCreate(Activity.java:6289)
06-29 22:35:37.762: W/System.err(17081):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
06-29 22:35:37.762: W/System.err(17081):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647)
06-29 22:35:37.772: W/System.err(17081):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759)
06-29 22:35:37.772: W/System.err(17081):    at android.app.ActivityThread.access$900(ActivityThread.java:178)
06-29 22:35:37.772: W/System.err(17081):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
06-29 22:35:37.772: W/System.err(17081):    at android.os.Handler.dispatchMessage(Handler.java:102)
06-29 22:35:37.772: W/System.err(17081):    at android.os.Looper.loop(Looper.java:145)
06-29 22:35:37.772: W/System.err(17081):    at android.app.ActivityThread.main(ActivityThread.java:5944)
06-29 22:35:37.772: W/System.err(17081):    at java.lang.reflect.Method.invoke(Native Method)
06-29 22:35:37.772: W/System.err(17081):    at java.lang.reflect.Method.invoke(Method.java:372)
06-29 22:35:37.772: W/System.err(17081):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
06-29 22:35:37.772: W/System.err(17081):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

This method is called in onCreate method from an Android Activity. I am using jcifs-1.3.8.jar. What can I do to make this working?

Thanks.


HorizontalScrollView jumps between updates when preforming a scroll animation in tandum with another.


I have a Horizontal ScrollView that I am trying to get to move while at the same time setting the weight of another, separate Linear Layout. The problem is when the view is calculating the weight (or maybe its just when it calculates the new height) of the H-Scrollview it jumps to position 512px and stays there. This makes the scrollview look like it is jumping when the two animations are played together. I have also tried setting just the weight of the scrollview alone and it still does it.

Code that animates the Horizontal Scroll view:

if(currentPlace == 2){
currentPlace--;
if(currentPlace < 0){currentPlace = 0;}

DriverManagerV2.this.getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        ValueAnimator ani = ValueAnimator.ofInt((int) scroller.getScrollX(), screenWidth *currentPlace);
        ani.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) lay.getLayoutParams();
                lp.weight = .7f - (.7f*animation.getAnimatedFraction());
                lay.requestLayout();

                LinearLayout.LayoutParams lp2 = (LinearLayout.LayoutParams) scroller.getLayoutParams();
                lp2.weight = 4f + (.7f*animation.getAnimatedFraction());
                scroller.requestLayout();
                scroller.setScrollX((int) animation.getAnimatedValue());
                Log.e("KICKU",""+scroller.getScrollX());
            }
        });
        ani.setDuration(1500);
        ani.start();
    }
});

}

And the XML for the HorizontalScrollView:

 <HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:fillViewport="true"
    android:id="@+id/driver_manager_content"
    android:layout_weight="4">

Any idea how to fix this?


glMapBufferRange returning all zeros in Android


I am having trouble reading out from a buffer mapped with glMapBufferRange

If I simply put some data in a buffer

    // Create input VBO and vertex format
    int bufferLength = 5 * 4; //5 floats 4 bytes each
    FloatBuffer data = ByteBuffer.allocateDirect(bufferLength)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();
    float[] floatData = { 1.0f, 4.0f, 9.0f, 16.0f, 25.0f };
    data.put(floatData).position(0);

Generate a Array Buffer in GL and fill it with the data

    int[] vbo = new int[1];
    GLES30.glGenBuffers(1, vbo, 0);
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vbo[0]);
    GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, bufferLength, data, GLES30.GL_STATIC_DRAW);
    MyGLRenderer.checkGlError(TAG + " glBufferData GL_ARRAY_BUFFER");

When I map the buffer using glMapBufferRange and read the results

    Buffer mappedBuffer =  GLES30.glMapBufferRange(GLES30 .GL_ARRAY_BUFFER,
            0, bufferLength, GLES30.GL_MAP_READ_BIT);

    if (mappedBuffer!=null){
        FloatBuffer transformedBuffer = ((ByteBuffer) mappedBuffer).asFloatBuffer();
        MyGLRenderer.checkGlError(TAG + " glMapBufferRange");

        Log.d(TAG, String.format("pre-run input values = %f %f %f %f %f\n", transformedBuffer.get(),
                transformedBuffer.get(), transformedBuffer.get(), transformedBuffer.get(), transformedBuffer.get()));
        transformedBuffer.position(0);

    }
    GLES30.glUnmapBuffer(GLES30.GL_ARRAY_BUFFER);

The logcat reads all zeros

D/TransformFeedback﹕ pre-run input values = 0.000000 0.000000 0.000000 0.000000 0.000000

No other errors are generated and I am not really sure what else to check. I have tried GLES30.glCopyBufferSubData(GLES30.GL_ARRAY_BUFFER, GLES30.GL_COPY_READ_BUFFER, 0, 0, bufferLength); and mapping GL_COPY_READ_BUFFER and gotten the same results.

I am testing on a Nexus 6 which supports OpenGL ES 3.1 so this functionality should be present.

This question suggests removing the OPENGL_FORWARD_COMPAT hint in glfw, could there be something similar that needs to happen in MyGLSurfaceView?


PARSE this and use for login password edit text condition how i can


{"vsUserName":"d475","vsPassword":"8080","vsIPAddress":"192.168.1.1"}

This is the key value peers which i have to parse in android and used to login and password. I am new in android so no knolege of parsing


Android thread controlling multiple texture views causes strange flickering


I am trying to use a single thread to render three separate TextureView's off the UI thread using canvas lock/unlock. The problem observed is the consistent flickering of each of the Texture Views being drawn, with the flicker consisting of a DIFFERENT TextureView's frame. So for example, I draw frames A,B and C in that order. Frame C will appear fine, however frames A and B will flicker with occasional instances of Frame C, and frame A will occasionally flicker with instances of Frame B.

I have read through the documentation describing Android Core Graphics, and have a fairly good understanding of how android's frame buffering system works. In a nutshell, my suspicion is that I am performing lockCanvas/unlockCanvasAndPost call's too quickly in succession, and that the framebuffer is unable to complete my request and simply draws the previous (incorrect) frame instead.

I've tried several things to resolve this issue. Attempting to use Choreographer to wait for VSYNC before continuing to call canvas helped, but as expected lowered my frame rate however the problem was still there. I've also tried an alternative render loop sans sleep command, with no difference in the observed phenomenon.

Essentially I am out of ideas on how to tackle this problem, and was hoping to get some outside input on it. Thanks in advance, code snippet is below:

Main render loop:

 while (running) {

        long now = System.nanoTime();
        long updateLength = now - lastLoopTime;
        lastLoopTime = now;
        float delta = updateLength / ((float)OPTIMAL_TIME.get());

        lastFpsTime += updateLength;
        fps++;

        if (lastFpsTime >= 1000000000)
        {
            Log.e(TAG, "(FPS Target: " + TARGET_FPS+ " ,FPS Actual: " + fps + ")");
            lastFpsTime = 0;
            fps = 0;
        }


        for (MyTextureView mtv : mItemList){
            if (!mtv.isLocked()) {
                mtv.doUpdate(delta);
                mtv.doRender();
            }
        }

        long sleepTime = (lastLoopTime-System.nanoTime() + OPTIMAL_TIME.get())/1000000;
        sleepTime = sleepTime < 0 ? 0 : sleepTime;

        try{
            Thread.sleep( sleepTime );
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

MyTextureView doRender() method:

public void doRender() {
    doubleBufferCanvas.drawPaint(Colors.BLACK);
    doDraw(doubleBufferCanvas); //draws content onto secondary canvas

        Canvas c = lockCanvas();
        c.drawPaint(Colors.BLACK);
        c.save();
        c.drawBitmap(dbbmp, 0, 0, null);
        c.restore();
        unlockCanvasAndPost(c);
}


basic Code reading in android


This is a part of android app project, i have got this code I am not able to understand that setOnItemClickListener takes (AdapterView.OnItemClickListener listener) as paramter but the other method void onItemClick is also in paramter space . I am not able to understand that how the object of AdapterView.OnItemClickListener() is calling/using onItemClick ? listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            String forecast = mForecastAdapter.getItem(position);
            Intent intent = new Intent(getActivity(), MainActivity2Activity.class)
                    .putExtra(Intent.EXTRA_TEXT, forecast);
            startActivity(intent);
        }
    })


as: unrecognized option '-EL' while compiling android kernel on ubuntu 14


ARCH=arm64
SUBARCH=arm64
CROSS_COMPILE=aarch64-linux-android-

Following is the output of make

# make
CHK     include/generated/uapi/linux/version.h
CHK     include/generated/utsrelease.h
CALL    scripts/checksyscalls.sh
CC      scripts/mod/empty.o
as: unrecognized option '-EL'
make[2]: *** [scripts/mod/empty.o] Error 1
make[1]: *** [scripts/mod] Error 2    
make: *** [scripts] Error 2

still the "as" is used from binutils (/usr/bin/as) instead of /usr/bin/aarch64-linux-android-as despite of gcc versions, gcc-4.4 gcc-4.6 gcc-4.8, ubuntu always install same binutils

renaming /usr/bin/as does not help & make fails

how can I make "make" use right "as" while cross compile.


Whatsapp button working on Android but Blank on IOS


This code is working good on android device like Samsung Galaxy Tab and S3 etc. After selecting a contact, it appears TheTitle -> TheURL.

But it's not working at iOS device like iPhone 6 plus and iPhone 5. After selecting a contact, the TheTitle -> TheURL does not appear, it's just blank.

How can I fix this?

var TheTitle = "post Title Text", TheURL = "http://ift.tt/1GV84XP";

$('#myID').after('<a class="button-share whatsapp" data-action="share/whatsapp/share" href="whatsapp://send?text=' + TheTitle + ' -> ' + TheURL + '" target="_blank">WhatsApp</a>');


Feching facebook session from default facebook


I am developing following requirements for android app-

  1. Check if Facebook session is available (if user is logged into his default facebook app of android device).
  2. If he has session fetch token from it and use graph api.
  3. If not show him error that he should login to default facebook app.

In my app there is only service and no activity, so I don't want to show activity to user to enter his facebook credentials and then use graph apis. I WANT TO FETCH SESSION FROM DEFAULT FACEBOOK APP


Trouble understanding Braintree integration into Android


I've read through the docs on http://ift.tt/1GrDpnH and I'm having trouble understanding what to do.

As I understand it, we must build a server to generate a client token which Android Studio then deals with. What I don't understand is how to build the server to generate a client token with each request, along with generating customers and updating customers.

I'm relatively familiar with Ruby, and I know that Sinatra is a good way to host servers with Ruby knowledge.. but can anyone lend some sort of clarity on what are the steps to going from no server to accepting credit card details?

Another confusing aspect is that some blogs say that using Braintree is as easy as copy/pasting a few lines in Studio, and others say that you have to build your own server. Anyway, please let me know your thoughts!


fire in every five seconds with libGdx


how do call fire method in every five seconds with libGdx ?

this is my Enemy class :

I wrote the following code, but it is wrong.

public class Enemy {

    private List<Bullet> bullets;
    private boolean isFire;

    public Enemy(){
        bullets=new ArrayList<Bullet>();
    }
    public void update(float delta) {
        Gdx.app.log("State", "State Fire");
        if(!isFire){
            Gdx.app.log("State", "Fire");
            fire();
        }else{
            Gdx.app.log("State", "No Fire");
        }
    }
    private void fire() {
        isFire=true;
        bullets.add(new Bullet(5, 32));
        Timer.schedule(new Task(){
            @Override
            public void run() {
                reload();
            }
        }, getDelay());
    }
    private void reload(){
        isFire=false;
    }
    private int getDelay() {
        return 5;
    }
    public List<Bullet> getBullets(){
        return bullets;
    }
}

Is there a way to solve the problem? I have no idea


Google Cloud Messaging for Cordova Clarification


I am implementing Google Cloud Messaging service in my cordova app. so far everything is working well. I however have some few issues bothering I wish someone can clarify them for me. 1) At this section of the code where I get the device GCM regID and further save it to on my server. I will like to know if I should call this script and thus save GCM regID to my server anytime the user opens the App or it should be called and saved once..

function onNotification(e) {
switch( e.event )
{
case 'registered':
    if ( e.regid.length > 0 )
    {                    
        console.log("regID = " + e.regid);
    }
   break;
   }
 }

2) I have noticed on the console that my registered ID sometime changes. I will like to know why that happens, whether it is normal and also if I should be updating the users GCM regID on my server.

I wil be glad if anyone can clarify these for me. Thank you


Android: how should an app handle the device's language change


Actually I'm handling 3 languages in my app so I have:

values/strings.xml

values-it/strings.xml

values-de/strings.xml

When I install the app, it is properly installed in the current language of the device. But if I change the language of the device, the language of the app doesn't switch. I have to reinstall it to switch the language.

I've seent that this happens also to other apps, but not to all. The "big" ones (whatsapp, viber, all google's, etc) change.

So the question is: how can an app follow the device's language change ?


The method parse(String) from the type Date is deprecated [duplicate]


This question already has an answer here:

I have the following snippit of code. Eclipse is telling me that "the method parse(String) from the type Date is deprecated". How can I fix my code so that I no longer get the deprecation warning?

String date = query.getString("somevariable");
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Date.parse(date));
setFireTime(cal.getTime());

My setFireTime method:

public void setFireTime(Date fireTime) {
   this.fireTime = fireTime;
}

After the suggestions below in the comment section, I have updated the code below:

String date = query.getString("fireTime");
Calendar cal = Calendar.getInstance();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.getDefault());
try {
    Date parsed = formatter.parse(date);            
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
cal.setTimeInMillis(parsed);
setFireTime(cal.getTime());

But I am getting parsed cannot be resolved to a variable error referring to cal.setTimeInMillis(parsed); now.


Cordova: WebRTC media refused


I want to build a cordova application on android that can use WebRTC to call and receive calls. I have :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />

in my android manifest, but when I use SIPML5 to call, it tells me media stream permission denied. (See SIPML5 live demo at http://ift.tt/1C2EFw8 if required). I tried on the Google Chrome browser on my computer and on my android and it works perfectly. It asks to use my microphone, and I allow. But, once I try it as an cordova application on my android, it doesn't ask me anything, it just refuses the media.


Change Packets in Android


I want to implement an android app that can control and change packets on network communications. like a parental control app. some web sites restricted by app and show a predefined page instead of original source. one solution i have already read about is vpn connection. as far as i know this solution need a server that can handle packets. if any solution or example exist with or without vpn solution please guide me.


actionscript make tutorial appear only once when launching game 1st time


I maka a mobile game for Android and I need tutorial for my game that appears only once when game installed and opened first time. Is there a nice way to do it? What to add in my code for this?


Cannot update the column information in table parse.com


I have a table lets call "Post" which has 3 columns "UserA"<ParseUser>, "UserB" and "Status"<String>. Data consists of UserA currentUser, UserB another ParseUser, status => A When I am going to update the status from "A" to "B" it throw me error

com.parse.ParseException: java.lang.IllegalArgumentException: Cannot save a ParseUser that is not authenticated.

Can anyone help me please?


FlexJson ClassNotFound Exception on Android 4.4.4


I´ve got a multidex project for Android devices. I use Flexjson. I´ve already tested it with flexjson 3.3 and 2.x.

It works perfectly well with android 5.x but crashes in Android 4.4.4.

It looks like the Dex support library is not working propperly with older Android versions but I cannot tell.

Here´s my stacktrace:

06-29 03:50:44.763  11884-11884/com.pigdroid.gameboard E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.pigdroid.gameboard, PID: 11884
flexjson.JSONException: [ layers.values ]:  Could not load com.pigdroid.game.board.tile.model.IntTileLayer
        at flexjson.ObjectBinder.findClassInMap(ObjectBinder.java:250)
        at flexjson.ObjectBinder.findClassName(ObjectBinder.java:213)
        at flexjson.ObjectBinder.bind(ObjectBinder.java:92)
        at flexjson.ObjectBinder.bindIntoCollection(ObjectBinder.java:110)
        at flexjson.factories.ListObjectFactory.instantiate(ListObjectFactory.java:13)
        at flexjson.ObjectBinder.bind(ObjectBinder.java:95)
        at flexjson.ObjectBinder.bindIntoObject(ObjectBinder.java:149)
        at flexjson.factories.ExistingObjectFactory.instantiate(ExistingObjectFactory.java:25)
        at flexjson.ObjectBinder.bind(ObjectBinder.java:95)
        at flexjson.ObjectBinder.bind(ObjectBinder.java:74)
        at flexjson.JSONDeserializer.deserialize(JSONDeserializer.java:241)
        at flexjson.JSONDeserializer.deserializeInto(JSONDeserializer.java:301)
        at com.pigdroid.game.model.memento.UndoableObject.from(UndoableObject.java:35)
        at com.pigdroid.game.controller.GameController.loadModelFromSerialized(GameController.java:108)
        at com.pigdroid.gameboard.view.detail.game.tile.TileBoardGameFragmentController.setGame(TileBoardGameFragmentController.java:692)
        at com.pigdroid.gameboard.view.detail.game.GameDetailFragment.onKickOff(GameDetailFragment.java:168)
        at com.pigdroid.gameboard.view.ServiceFragment.kickOffIf(ServiceFragment.java:71)
        at com.pigdroid.gameboard.view.detail.game.GameDetailFragment.kickOffIf(GameDetailFragment.java:159)
        at com.pigdroid.gameboard.view.ServiceFragment$3.bound(ServiceFragment.java:52)
        at com.pigdroid.gameboard.view.ServiceFragment$3.bound(ServiceFragment.java:48)
        at com.pigdroid.android.hateaidl.HateAIDLConnection$3.onServiceConnected(HateAIDLConnection.java:118)
        at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1101)
        at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1118)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.pigdroid.game.board.tile.model.IntTileLayer" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
        at android.app.LoadedApk$WarningContextClassLoader.loadClass(LoadedApk.java:430)
        at flexjson.ObjectBinder.findClassInMap(ObjectBinder.java:243)

            at flexjson.ObjectBinder.findClassName(ObjectBinder.java:213)             at flexjson.ObjectBinder.bind(ObjectBinder.java:92)             at flexjson.ObjectBinder.bindIntoCollection(ObjectBinder.java:110)             at flexjson.factories.ListObjectFactory.instantiate(ListObjectFactory.java:13)             at flexjson.ObjectBinder.bind(ObjectBinder.java:95)             at flexjson.ObjectBinder.bindIntoObject(ObjectBinder.java:149)             at flexjson.factories.ExistingObjectFactory.instantiate(ExistingObjectFactory.java:25)             at flexjson.ObjectBinder.bind(ObjectBinder.java:95)             at flexjson.ObjectBinder.bind(ObjectBinder.java:74)             at flexjson.JSONDeserializer.deserialize(JSONDeserializer.java:241)             at flexjson.JSONDeserializer.deserializeInto(JSONDeserializer.java:301)             at com.pigdroid.game.model.memento.UndoableObject.from(UndoableObject.java:35)             at com.pigdroid.game.controller.GameController.loadModelFromSerialized(GameController.java:108)             at com.pigdroid.gameboard.view.detail.game.tile.TileBoardGameFragmentController.setGame(TileBoardGameFragmentController.java:692)             at com.pigdroid.gameboard.view.detail.game.GameDetailFragment.onKickOff(GameDetailFragment.java:168)             at com.pigdroid.gameboard.view.ServiceFragment.kickOffIf(ServiceFragment.java:71)             at com.pigdroid.gameboard.view.detail.game.GameDetailFragment.kickOffIf(GameDetailFragment.java:159)             at com.pigdroid.gameboard.view.ServiceFragment$3.bound(ServiceFragment.java:52)             at com.pigdroid.gameboard.view.ServiceFragment$3.bound(ServiceFragment.java:48)             at com.pigdroid.android.hateaidl.HateAIDLConnection$3.onServiceConnected(HateAIDLConnection.java:118)             at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1101)             at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1118)             at android.os.Handler.handleCallback(Handler.java:733)             at android.os.Handler.dispatchMessage(Handler.java:95)             at android.os.Looper.loop(Looper.java:136)             at android.app.ActivityThread.main(ActivityThread.java:5001)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:515)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)             at dalvik.system.NativeStart.main(Native Method)



This question already has an answer here:

I need to store a large dictionary of natural language words -- up to 120,000, depending on the language. These need to be kept in memory as profiling has shown that the algorithm which utilises the array is the time bottleneck in the system. (It's essentially a spellchecking/autocorrect algorithm, though the details don't matter.) On Android devices with 16MB memory, the memory overhead associated with Java Strings is causing us to run out of space. Note that each String has a 38 byte overhead associated with it, which gives up to a 5MB overhead.

At first sight, one option is to substitute char[] for String. (Or even byte[], as UTF-8 is more compact in this case.) But again, the memory overhead is an issue: each Java array has a 32 byte overhead.

One alternative to ArrayList<String>, etc. is to create an class with much the same interface that internally concatenates all the strings into one gigantic string, e.g. represented as a single byte[], and then store offsets into that huge string. Each offset would take up 4 bytes, giving a much more space-efficient solution.

My questions are a) are there any other solutions to the problem with similarly low overheads* and b) is any solution available off-the-shelf? Searching through the Guava, trove and PCJ collection libraries yields nothing.

*I know one can get the overhead down below 4 bytes, but there are diminishing returns.

NB. Is support for compressed Strings being dropped? suggests that the JVM option -XX:+UseCompressedStrings isn't going to help here.


Edittext color is white in appcompat 22.2


In an appcompat-v7:22.2.0 I used an EditText. An I'musing following theme for an Activity

<style name="AppThemeNoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/myPrimaryColor</item>
    <item name="colorPrimaryDark">@color/myPrimaryDarkColor</item>
    <item name="colorAccent">@color/myAccentColor</item>
    <item name="android:windowBackground">@color/myWindowBackground</item>
    <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
    <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
    <item name="colorControlHighlight">#0000AA</item>
</style>

But the color of an EditText is coming in white color. Bottom line, hint and text all are in white. I heard there is a bug in AppCompat But how to resolve this?

EDIT Adding more information

XML file :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_marginTop="@dimen/marintopforelements"
          android:gravity="center"
          android:orientation="vertical"
          android:padding="10dp"
          android:paddingTop="@dimen/templatePaddingTop">

          <android.support.v7.widget.AppCompatEditText
                android:id="@+id/emailresponse"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center"
                android:layout_marginLeft="@dimen/examtextdiff"
                android:imeOptions="actionNext"
                android:inputType="textEmailAddress"
                android:minLines="2"
                android:paddingRight="5dp"
                android:textSize="@dimen/inboxTabTextSize"/>

</LinearLayout>

colors.xml

<color name="myPrimaryColor">#3F51B5</color>
<color name="myPrimaryDarkColor">#FF304081</color>
<color name="myAccentColor">#3F51B5</color>

So previously when I was using AppCompat-V7:21 It was coming like below imageenter image description here

But after upgrading to AppCompat-V7:22.2.0 Its like below image enter image description here

So if it focused its coming like below image enter image description here

Only that cursor line is in given accent color. But the hint and text are always in white! And this is happening even in both EditText and AppCompatEditText Hope this helps


Having issues with ios UIWebView scrolling


I have this function I am running in a UIWebView. It works in Android as window.onscroll = scrollFunc; .. with ios I am doing document.ontouchend = scrollFunc; not sure if this is the right method. (I don't think it is, considering I also need to add an onclick method).

The other problem I am having is that ONLY the scroll up action is being called even though the diffY number comes back as negative when scrolling down and positive when scrolling up. I can't figure out why.

var prevDate = Date.now(); var curDate = prevDate;
                                function scrollFunc(e) {
                                    curDate = Date.now();
                                    if((curDate - prevDate) > 1000){ 
                                        if ( typeof scrollFunc.y == 'undefined' ) {
                                            scrollFunc.y=window.pageYOffset;
                                        }
                                        var diffY=scrollFunc.y-window.pageYOffset;
                                        if( diffY<-3 ) {
                                            // Scroll down action here
                                        } else if( diffY>5 ) {
                                            // Scroll up action here
                                        } else {
                                            // First scroll event
                                        }

                                        scrollFunc.y=window.pageYOffset;
                                        prevDate = curDate;
                                    }
                                }


android many icons to show but one id to render


im new to android programming so please bare with me.

I want to show many icons which i will be getting from the fonticon.ttf which works fine

the onCreate function is like below

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Typeface font = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
        Button button = (Button)findViewById( R.id.like2 );
        button.setTypeface(font);

    }

But as u can see this is restricted to a single button with id as like2 . But i want to have something like a html class or something which i can call so that when ever i use it, it automatically renders the icon for me .

My simple design goes like below

<RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/login_button1"
                android:layout_alignParentLeft="true"
                android:background="#7000"
                android:orientation="vertical"
                android:paddingTop="5dp" >

                <Button
                    android:id="@+id/like1"
                    android:layout_width="10dp"
                    android:layout_height="10dp"
                    android:text="@string/icon_heart"
                    android:textColor="#CCC"
                    android:layout_alignParentRight="true"
                    android:background="#00000000"
                    android:layout_marginRight="5dp"
                    android:textSize="50sp" />
            </RelativeLayout>

I will be using same icons many times and it seems impossible to include all of them in one onCreate as they will be loaded once and http get request is completed.

Could someone Please assist me. Thanks guys


Invisible android.support.v4.app.Fragment on Android 5.1


I have got a problem. I have written an android app that uses fragments. I created fragments in a loop and they are visible on android 2.2 but not on android 5.1! I could not find out what is my mistake although I was looking for answers a lot. I hope you can help me. (Don't worry about the words in the frame they are a german timetable ;) )

enter image description here

public void setInfo(String date, ArrayList<Lesson> l) {
    TextView dv = (TextView) getActivity().findViewById(R.id.dayview);
    dv.setText(date);
    LinearLayout ll = (LinearLayout) getActivity().findViewById(R.id.lessonlayout);
    ll.removeAllViews();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    for(int i = 0; i < l.size(); i ++) {
        Log.d("GCG", "Fragment: " + Integer.toString(i));
        Fragment lf = new LessonFragment(l.get(i));
        fragmentTransaction.add(R.id.lessonlayout, lf);
    }
    fragmentTransaction.commit();
}

This method loads the fragments. Lesson is a my class to save information and is not important.

And here is my class LessonFragment:

public class LessonFragment extends Fragment {

    private Lesson lesson;

    public LessonFragment(Lesson l) {
        lesson = l;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_lesson, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Log.d("GCG", "on View Created!");
        TextView tlesson = (TextView) view.findViewById(R.id.lesson);
        TextView tsubject = (TextView) view.findViewById(R.id.subject);
        TextView troom = (TextView) view.findViewById(R.id.room);
        TextView tteacher = (TextView) view.findViewById(R.id.teacher);
        TextView tinformations = (TextView) view.findViewById(R.id.informations);

        tlesson.setText(lesson.getNumber());
        tsubject.setText(lesson.getSubject());
        troom.setText(lesson.getRoom());
        tteacher.setText(lesson.getTeacher());
        tinformations.setText(lesson.getInformation());
    }

    @Override
    public void onStart() {
        super.onStart();
    }
}


Android: I can't seem to get my custom toolbar's back arrow to act like the device's physical back arrow


I have the back arrow implimented and working but instead of just finishing the activityB and going back to the previous view the user was on in activityA. It instead closes activityB and reloads activityA which means you have to go back through a few menus to get back to where you were.

The physical back arrow does exactly as I want it to in that it just closes the activtyB and puts the user back to where they were within activtyA originally before they moved to activtyB.

This is my current code for the toolbar back arrow but maybe I'm just not fully grasping how the physical back arrow works. I appreciate any and all advice!

toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);


won't accept A's child classes


I'm working with Android Studio and I keep getting a problem I don't know how to solve. I don't know whether it's a problem with Android Studio, with Java or a mistake a make.

I have a class whose constructor is the following:

public MakeQuery(Callable<ArrayList<? extends A>) {
     ...
}

I try to create an object of that class with the following lines:

Callable<ArrayList<B>> callable = new Callable<ArrayList<B>>() {...};
MakeQuery makeQuery = new MakeQuery(callable);

(Of course, class B extends A. Double checked)

But when I call the constructor the IDE tells me that it expects another type of argument.

What mistake am I making? Thanks for all the help! :)


Shape Drawable does not show in ImageView


I am trying to make rectangular blocks in my Android app. I tries to use Shape Drawable but it does not work. rectangle.xml:

<?xml version="1.0" encoding="utf-8"?><shape
xmlns:android="http://ift.tt/nIICcg"
android:shape="rectangle">
<stroke
    android:width="1dp"
    android:color="#000000">
</stroke>
<solid android:color="#f0600000"/>
<size android:height="30dp" android:width="30dp"/></shape>

activity_main.xml:

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="200dp"
    android:layout_height="200dp" android:background="@android:color/holo_red_dark"
    android:layout_centerInParent="true"
    android:scaleType="center"
    android:src="@drawable/rectangle">

</ImageView></RelativeLayout>

MainActivity.java ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = (ImageView) findViewById(R.id.imageView);
    setDrawable();

}

private void  setDrawable(){
    imageView.setImageResource(R.drawable.rectangle);
}

All that I see in emulator is square, without solid stroke. Why the drawable resourse is not displayed? Thanks


SharedPreferences Long value


Here I'm creating a SharedPreferences if I'm not wrong i'm using this code :

SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("ExactTime", minutesToMilliseconds(NumberPicker2.getValue()));
editor.commit();

What I'm doing is I get a value from a NumberPicker and I want to save this value and once an user restart the APP or even reboot the device (I don't know if SharedPreferences does it...) when the user opens the APP it still the same number picked from NumberPicker.

And I want to use this in a class that extends a Service. What I've tried is :

SharedPreferences sp = this.getSharedPreferences("ExactTime", Context.MODE_PRIVATE);
WifiTimeSearch = sp.getLong("ExactTime", 0);

Here is where I'm lost... I've read that this "0" means a default value but I want to use the same value that I've stored on SharedPreferences... And when I try to use this Long value, the value is "0".

What I'm doing wrong?


How to validate the Nymi band Asynchronously?


I am trying to validate the Nymi band asynchronously . But when I try to do that, I get the following exception:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I have all the toasts in the on the following method as you can see:

runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
                    }
                });

But Still I get the exception. The method works fine when run normally in the onCreate() method,but fails to run asynchronously .

Here is my Thread class,where I am calling the validate() asynchronously :

public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {

@Override
protected Integer doInBackground(Integer... integers) {

    try{
        TestBluetooth tb=new TestBluetooth();
        tb.startValidatingNymi();
    }catch (Exception e){
        e.printStackTrace();
    }
    return 0;
}

}

Here is the main class where I have the validate methods:

public class TestBluetooth extends  Activity implements OnClickListener,ProvisionController.ProvisionProcessListener,
    ValidationController.ValidationProcessListener {

boolean isBluetoothEnabled = false;
static boolean nclInitialized = false;
static final String LOG_TAG = "AndroidExample";

SharedPreferences prefs;

Button checkBlue,proviNymi,validateNymi,disconnectNymi;

ProvisionController provisionController;
ValidationController valiationController;
boolean connectNymi = true;
int nymiHandle = Ncl.NYMI_HANDLE_ANY;
NclProvision provision;
//NclProvision provisionmid;

String temp_ID,temp_Key;
public String keyuse;
public String iduse;
public  LinearLayout progressbar;
public ProgressBar pbHeaderProgress;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testbluetooth);

    final Handler timedThread=new Handler();
    timedThread.postDelayed(new Runnable() {
        @Override
        public void run() {

            NymiAsync task=new NymiAsync();
            task.execute(1,1,1);
        }
    },10000);



}

public void startValidatingNymi(){

    progressbar = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
    pbHeaderProgress=(ProgressBar) findViewById(R.id.pbHeaderProgress);
    pbHeaderProgress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#1109EE"), android.graphics.PorterDuff.Mode.SRC_ATOP);

    //  prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
    //  prefs.edit().clear().commit();

    prefs=getSharedPreferences(Util.SharedPrefKey,MODE_PRIVATE);

    temp_ID = prefs.getString(Util.provID, null);

    temp_Key = prefs.getString(Util.provKey, null);

    if ((temp_ID!=null) || (temp_Key!=null)){

        // SHOW THE SPINNER WHILE LOADING FEEDS
        progressbar.setVisibility(View.VISIBLE);

        //Toast.makeText(getBaseContext(), "Nymi band is already provisined" , Toast.LENGTH_SHORT ).show();
        initializeNcl();

        provision = new NclProvision();
        load();

        if (valiationController == null) {
            valiationController = new ValidationController(TestBluetooth.this);
        }
        else {
            valiationController.stop();
        }

        valiationController.startValidation(TestBluetooth.this, provision);




        proviNymi = (Button) findViewById(R.id.provisionNymi);
        proviNymi.setOnClickListener(this);
        proviNymi.setEnabled(false);

        validateNymi = (Button) findViewById(R.id.validateNymi);
        validateNymi.setOnClickListener(this);
        validateNymi.setEnabled(false);

        disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
        disconnectNymi.setOnClickListener(this);
        disconnectNymi.setEnabled(false);


    }else {

      //  Toast.makeText(getBaseContext(), "provision key is null!" , Toast.LENGTH_SHORT ).show();

        checkBlue = (Button) findViewById(R.id.testBLuetooth);
        checkBlue.setOnClickListener(this);

        proviNymi = (Button) findViewById(R.id.provisionNymi);
        proviNymi.setOnClickListener(this);

        validateNymi = (Button) findViewById(R.id.validateNymi);
        validateNymi.setOnClickListener(this);
        validateNymi.setEnabled(false);

        disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
        disconnectNymi.setOnClickListener(this);
        disconnectNymi.setEnabled(false);
    }


}



public void load(){

    iduse = prefs.getString(Util.provID,null);
    Toast.makeText(getBaseContext(), iduse , Toast.LENGTH_SHORT ).show();
    keyuse = prefs.getString(Util.provKey,null);

    if ((iduse!=null)||(keyuse!=null)) {

        provision.id = new NclProvisionId();
        provision.id.v = Base64.decode(iduse, Base64.DEFAULT);
        provision.key = new NclProvisionKey();
        provision.key.v = Base64.decode(keyuse, Base64.DEFAULT);
        final String temp= keyuse.toString();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                  Toast.makeText(getBaseContext(), "the temp provision key is " +temp , Toast.LENGTH_SHORT ).show();

            }
        });

    }else {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                   Toast.makeText(getBaseContext(), "Provision key is null!" , Toast.LENGTH_SHORT ).show();
            }
        });


    }
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    if(v.getId() == checkBlue.getId()){

       // Toast.makeText(getBaseContext(), "Checking bluetooth is enabled or not!" , Toast.LENGTH_SHORT ).show();

        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
        } else {
            if (!mBluetoothAdapter.isEnabled()) {
                // Bluetooth is not enable :)
               // Toast.makeText(getBaseContext(), " bluetooth is not enabled !" , Toast.LENGTH_SHORT ).show();
                isBluetoothEnabled=false;
            }else {

             //   Toast.makeText(getBaseContext(), " bluetooth is enabled !" , Toast.LENGTH_SHORT ).show();
                isBluetoothEnabled=true;
                Log.d("is nabled", "blue is enalble");




            }
        }

    }


    if (v.getId()==proviNymi.getId()){

        connectNymi = true;

        initializeNcl();

        nymiHandle = -1;
        if (provisionController == null) {
            provisionController = new ProvisionController(TestBluetooth.this);
        }
        else {
            provisionController.stop();
        }
        provisionController.startProvision(TestBluetooth.this);
    }


    if (v.getId()==validateNymi.getId()){

        proviNymi.setEnabled(false);
        if (valiationController == null) {
            valiationController = new ValidationController(TestBluetooth.this);
        }
        else {
            valiationController.stop();
        }
        valiationController.startValidation(TestBluetooth.this, provisionController.getProvision());
    }



    if (v.getId()==disconnectNymi.getId()){

        prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
        prefs.edit().clear().commit();

        if (nymiHandle >= 0) {
            disconnectNymi.setEnabled(false);
            validateNymi.setEnabled(true);
            proviNymi.setEnabled(true);
            Ncl.disconnect(nymiHandle);
            nymiHandle = -1;
        }
    }



}

/**
 * Initialize the NCL library
 */
protected void initializeNcl() {
    if (!nclInitialized) {
        if (connectNymi) {
            initializeNclForNymiBand();

        }
    }
}

/**
 * Initialize NCL library for connecting to a Nymi Band
 * @return true if the library is initialized
 */
protected boolean initializeNclForNymiBand() {
    if (!nclInitialized) {


        NclCallback nclCallback = new MyNclCallback();
        boolean result = Ncl.init(nclCallback, null, "NCLExample", NclMode.NCL_MODE_DEFAULT, this);

        if (!result) { // failed to initialize NCL

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                     Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();

                }
            });

            return false;
        }
        nclInitialized = true;
       // nclInitialized();
    }
    return true;
}

@Override
public void onStartProcess(ProvisionController controller) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(TestBluetooth.this, "Nymi start provision ..",
                    Toast.LENGTH_LONG).show();

        }
    });
}




public void save(){



   final String id = Base64.encodeToString(provision.id.v, Base64.DEFAULT);
    final String key = Base64.encodeToString(provision.key.v, Base64.DEFAULT);
    SharedPreferences pref = getSharedPreferences(Util.SharedPrefKey, MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString(Util.provID, id);
    editor.putString(Util.provKey, key);
    editor.apply();
    editor.commit();

    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(TestBluetooth.this, id + key,
                    Toast.LENGTH_LONG).show();
        }
    });

}

@Override
public void onAgreement(final ProvisionController controller) {
    nymiHandle = controller.getNymiHandle();
    controller.accept();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(TestBluetooth.this, "Agree on pattern: " + Arrays.toString(controller.getLedPatterns()),
                    Toast.LENGTH_LONG).show();
        }
    });
}

@Override
public void onProvisioned(final ProvisionController controller) {
    nymiHandle = controller.getNymiHandle();
    provision = controller.getProvision();
    controller.stop();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            proviNymi.setEnabled(false);
            validateNymi.setEnabled(true);
            Toast.makeText(TestBluetooth.this, "Nymi provisioned: " + Arrays.toString(provision.id.v),
                    Toast.LENGTH_LONG).show();
            save();
        }
    });
}

@Override
public void onFailure(ProvisionController controller) {
    controller.stop();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(TestBluetooth.this, "Nymi provision failed!",
                    Toast.LENGTH_LONG).show();
        }
    });
}

@Override
public void onDisconnected(ProvisionController controller) {
    controller.stop();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            validateNymi.setEnabled(provision != null);
            disconnectNymi.setEnabled(false);
            Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
                    Toast.LENGTH_LONG).show();
        }
    });
}

@Override
public void onStartProcess(ValidationController controller) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(TestBluetooth.this, "Nymi start validation for: " + Arrays.toString(provision.id.v),
                    Toast.LENGTH_LONG).show();

        }
    });
}

@Override
public void onFound(ValidationController controller) {
    nymiHandle = controller.getNymiHandle();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(TestBluetooth.this, "Nymi validation found Nymi on: " + Arrays.toString(provision.id.v),
                    Toast.LENGTH_LONG).show();



        }
    });
}



@Override
public void onValidated(ValidationController controller) {
    nymiHandle = controller.getNymiHandle();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            validateNymi.setEnabled(false);
            disconnectNymi.setEnabled(true);

            // HIDE THE SPINNER AFTER LOADING FEEDS
            progressbar.setVisibility(View.GONE);

            Toast.makeText(TestBluetooth.this, "Nymi validated!",
                    Toast.LENGTH_LONG).show();

            prefs.edit().putBoolean(Util.isValidated, true).commit();

           //move to new activity once nymi is validated
            Intent intent = new Intent(TestBluetooth.this,CustomNotificationTest.class);
            startActivity(intent);

        }
    });


}

@Override
public void onFailure(ValidationController controller) {
    controller.stop();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(TestBluetooth.this, "Nymi validated failed!",
                    Toast.LENGTH_LONG).show();
        }
    });
}

@Override
public void onDisconnected(ValidationController controller) {
    controller.stop();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            disconnectNymi.setEnabled(false);
            validateNymi.setEnabled(true);
            proviNymi.setEnabled(true);
            Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
                    Toast.LENGTH_LONG).show();
        }
    });
}

/**
 * Callback for NclEventInit
 *
 */
class MyNclCallback implements NclCallback {
    @Override
    public void call(NclEvent event, Object userData) {
        Log.d(LOG_TAG, this.toString() + ": " + event.getClass().getName());
        if (event instanceof NclEventInit) {
            if (!((NclEventInit) event).success) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }
}

}


Android Head Tracking/VR in OpenGL - Rotation Matrix Issues


So the short version is that I'm trying to do head tracking on an Android device to move/tilt a camera in an OpenGL ES 2.0 virtual environment. Should be simple enough but I can't get it to work

I'm new to almost all of this. It's my first time working with Android, OpenGL, VR, and the math (matrices) associated with it. That being said I understand the hardware and sensor side very well.

I'm using the rotation matrix from the sensors. I can't use the quaternion because the API version (15) doesn't support the w component, and google cardboard is out of the question. The matrix seems to work, but the axis the device is tilted along does not match up with the tilt axis of the camera.

This seems like something that should be really simple, especially given how many demos of the tech are out there, but I can't seem to get it to work properly. Can someone tell me what I'm doing wrong with the rotation matrix?

OpenGL Renderer Class:

/*
Based on Android tutorials
 */
package com.example.android.opengl;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;


/**
 * Provides drawing instructions for a GLSurfaceView object. This class
 * must override the OpenGL ES drawing lifecycle methods:
 * <ul>
 *   <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceCreated}</li>
 *   <li>{@link android.opengl.GLSurfaceView.Renderer#onDrawFrame}</li>
 *   <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceChanged}</li>
 * </ul>
 */
public class MyGLRenderer implements GLSurfaceView.Renderer {

    private static final String TAG = "MyGLRenderer";
    private Square   square1, square2, square3, square4;

    private IMUData localIMUData = new IMUData();

    // mMVPMatrix is an abbreviation for "Model View Projection Matrix"
    private final float[] mMVPMatrix = new float[16];
    private final float[] mProjectionMatrix = new float[16];
    private final float[] mViewMatrix = new float[16];
    @Override
    public void onSurfaceCreated(GL10 unused, EGLConfig config) {

        // Set the background frame color
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

        square1 = new Square(
                -.5f, 5f, .5f,
                -.5f, 5f, -.5f,
                .5f, 5f, -.5f,
                .5f, 5f, .5f,
                1f, 0f, 0f, 1f);
        square2 = new Square(
                .5f, -5f, -.5f,
                -.5f, -5f, -.5f,
                -.5f, -5f, .5f,
                .5f, -5f, .5f,
                0f, 1f, 0f, 1f);
        square3 = new Square(
                5f, .5f, -.5f,
                5f, -.5f, -.5f,
                5f, -.5f, .5f,
                5f, .5f, .5f,
                0f, 0f, 1f, 1f);
        square4 = new Square(
                -5f, .5f, -.5f,
                -5f, -.5f, -.5f,
                -5f, -.5f, .5f,
                -5f, .5f, .5f,
                .5f, 0f, .5f, 1f);

        //initialize the sensor listeners
        localIMUData.initSensorListeners();

    }

    @Override
    public void onDrawFrame(GL10 unused) {

        // Draw background color
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

        //get the heading anle for calculations
        float heading = localIMUData.getTheta();

        // Set the camera position (View matrix)
        Matrix.setLookAtM(mViewMatrix, 0,  //result matrix, index to start at
                // position
                0, 0, 0,

                //center of view
                0 + (float) Math.sin(heading), 0 + (float) Math.cos(heading), 0,

                //"up" vector
                0f, 0f, 1f

                );

        //this is my attempt at modifying the matrices to get head tracking to work
        float[] tempMatrix = localIMUData.getRotMat();
        //set rotMat to identity matrix to stop null pointer error
        float[] rotMat = new float[] {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};

        //this should allow the program to work until the rotation matrix is created
        if (tempMatrix != null){
            //I know this is sloppy but it's all I can come up with for right now to pad the matrix
            float[] t = localIMUData.getRotMat();
            float[] i = {t[0],t[1],t[2],0,  t[3],t[4],t[5],0, t[6],t[7],t[8],0,  0,0,0,1};
            //and I know this is bad too but this is for a proof of concept and doesn't need to be good code yet
            rotMat = i;
        }

        float[] adjustedView = new float[16];

        Matrix.multiplyMM(adjustedView, 0, mViewMatrix, 0, rotMat, 0);

        // Calculate the projection and view transformation
        Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, adjustedView, 0);

        // Draw squares
        square1.draw(mMVPMatrix);
        square2.draw(mMVPMatrix);
        square3.draw(mMVPMatrix);
        square4.draw(mMVPMatrix);

    }

    @Override
    public void onSurfaceChanged(GL10 unused, int width, int height) {
        // Adjust the viewport based on geometry changes,
        // such as screen rotation
        GLES20.glViewport(0, 0, width, height);

        float ratio = (float) width / height;

        // this projection matrix is applied to object coordinates
        // in the onDrawFrame() method
        Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);

    }

    /**
     * Utility method for compiling a OpenGL shader.
     *
     * <p><strong>Note:</strong> When developing shaders, use the checkGlError()
     * method to debug shader coding errors.</p>
     *
     * @param type - Vertex or fragment shader type.
     * @param shaderCode - String containing the shader code.
     * @return - Returns an id for the shader.
     */
    public static int loadShader(int type, String shaderCode){

        // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
        // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
        int shader = GLES20.glCreateShader(type);

        // add the source code to the shader and compile it
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);

        return shader;
    }

    /**
    * Utility method for debugging OpenGL calls. Provide the name of the call
    * just after making it:
    *
    * <pre>
    * mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
    * MyGLRenderer.checkGlError("glGetUniformLocation");</pre>
    *
    * If the operation is not successful, the check throws an error.
    *
    * @param glOperation - Name of the OpenGL call to check.
    */
    public static void checkGlError(String glOperation) {
        int error;
        while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
            Log.e(TAG, glOperation + ": glError " + error);
            throw new RuntimeException(glOperation + ": glError " + error);
        }
    }

}

Sensor Listener Class:

package com.example.android.opengl;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;


public class IMUData implements SensorEventListener{
    //create sensor manager
    private static SensorManager sensorManager;

    private final static String TAG = "IMUData";

    //create variables for storing the most recent set of data for the calculations and initialize them to 0
    public float[] locallacc = new float[] {0.0f, 0.0f, 0.0f};
    public float[] acc = new float[] {0.0f, 0.0f, 0.0f};
    public float[] gyro = new float[]{0.0f, 0.0f, 0.0f};
    public float[] mag = new float[] {0.0f, 0.0f, 0.0f};
    public float[] rot = new float[] {0.0f, 0.0f, 0.0f, 0.0f};
    public float[] grav = new float[] {0.0f, 0.0f, 0.0f};
    //these two need to have the size defined before they can be used
    float[] lacc = new float[] {0.0f, 0.0f, 0.0f};
    float[] angle = new float[] {0.0f, 0.0f, 0.0f};
    public float theta = 0.0f;  //this is for the heading (think compass)
    public float[] RMatrix;
    //public ArrayList<Float> l = new ArrayList<>();  // for dynamic sized arrays

    //flags to keep orientation calculation from happening before all the data is collected
    private boolean rot_flag = false;

    @Override
    public void onSensorChanged(SensorEvent event) {
        //on sensor message, check what sensor it is and save data from sensor
        switch (event.sensor.getType()){
            case Sensor.TYPE_LINEAR_ACCELERATION:
                locallacc = event.values;
                //used in position estimates so left here for future compatibility
                //change co-ordinate systems from local to global
                lacc[0] = (float) ((locallacc[0]*Math.cos(theta)) + (locallacc[1]*Math.sin(theta)));
                lacc[1] = (float) ((locallacc[1]*Math.cos(theta)) - (locallacc[0]*Math.sin(theta)));
                lacc[2] = locallacc[2];
                break;
            case Sensor.TYPE_ACCELEROMETER:
                acc = event.values;
                break;
            case Sensor.TYPE_GYROSCOPE:
                gyro = event.values;
                break;
            case Sensor.TYPE_MAGNETIC_FIELD:
                mag = event.values;
                break;
            case Sensor.TYPE_ROTATION_VECTOR:
                rot_flag = true;
                rot = event.values;
                theta = 2 * (float)(Math.atan(rot[0]/rot[1]));
                break;
            case Sensor.TYPE_GRAVITY:
                grav = event.values;
                break;
            default:
                //hopefully will not hit this but hey let's catch all the mess-ups.
                break;
        }

        //compute rotation angle (think compass)
        boolean check = false;
        float RMatrix[] = new float[9];
        //if acceleromater and magnometer data are both not null
        if(rot_flag) {
            //see if the rotation matrix calculation works using data from accelerometer and magnometer
            sensorManager.getRotationMatrixFromVector(RMatrix, rot);
        }
        if (check) {
            //get euler angles
            sensorManager.getOrientation(RMatrix, angle);
            this.RMatrix = RMatrix;
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //do nothing.
    }

    public void initSensorListeners(){
        //setup sensor manager and sensor listeners
        sensorManager=MyGLSurfaceView.getSensorManager();

        //linear acceleration, basically acceleration sans gravity
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
                sensorManager.SENSOR_DELAY_NORMAL);
        //get gravity vector for the up vector
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),
                sensorManager.SENSOR_DELAY_NORMAL);
        //get data for the orientation setup later on
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                sensorManager.SENSOR_DELAY_NORMAL);
        //gyroscope, this has been run through a few filters
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
                sensorManager.SENSOR_DELAY_NORMAL);
        //magnometer, also run through a few filters
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
                sensorManager.SENSOR_DELAY_NORMAL);
        //orientation vector, standard, relies on magnometer and gyro (I think, docs don't say)
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
                sensorManager.SENSOR_DELAY_NORMAL);
    }

    //return functions
    public float[] getLinAcc(){return locallacc;}
    public float[] getAdjLinAcc(){return lacc;}
    public float[] getAcc(){return acc;}
    public float[] getGyro(){return gyro;}
    public float[] getMag(){return mag;}
    public float[] getRot(){return rot;}
    public float[] getAngle(){return angle;}
    public float getTheta(){return theta;}
    public float[] getGravity(){return grav;}
    public float[] getRotMat(){return RMatrix;}
}


Android picasso resize image to screen width


I am using picasso to resize my background image to fill the screen width (not adjust the image height).

The problem is, that even though I set the image width to the same as the screen width, the image does not fill to the horizontal edges, there is a gap. At 800dp the gap is 35dp.

here is my code

ImageView imgBackground = (ImageView) v.findViewById(R.id.imgBackground);

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.morn_blur_bg);
WindowManager wm = (WindowManager) v.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

Point size = new Point();
display.getSize(size);
int displayWidth = size.x;
int height = size.y;
int width = 0;

//Log.d("CP", "Screen width="+displayWidth);
//Log.d("CP", "Image width=" + bMap.getWidth());

if (bMap.getWidth() < displayWidth) {
    width = displayWidth;
} else {
    width = bMap.getWidth();
}

Log.d("CP", "New width=" + width);

Picasso.with(v.getContext())
        .load(R.drawable.morn_blur_bg)
        .resize(width, height)
        .into(imgBackground);

here is my xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    android:id="@+id/layRoot"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

     <!--Background image-->
    <ImageView
        android:id="@+id/imgBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" />

If I hardcode the width to 835dp the image fills the display, but of course this will not work across devices. :-)

cheers


Android Studio Espresso Empty Test Suite


When I run my test method that uses Espresso, it prompts me to choose an emulator, and I pick my existing emulator with my application already started. The emulator subsequently automatically reboots my application, and then displays that that the test suite is empty.

The error

My espresso test case is located in the androidTest folder of the same module as the activity I'm trying to test. I wrote a simple "isDisplayed()" type of a test and right clicked the method and clicked run. I've taken a look at the other questions on Stack Overflow and other resources, but I can't figure out what is causing this problem. The logcat displays nothing and when I tried putting Log.d("debug", "hello hello") in the test method (shown below), nothing shows up in the logcat, nor does anything display when I try putting a System.out.println("hello") in the test method. It seems that although I run the method, none of my code is being run!

Below is some of my build.grade.

apply plugin: 'com.android.application'

android {
   compileSdkVersion 17
   buildToolsVersion "21.1.2"
   defaultConfig {
       applicationId "x"
       minSdkVersion 17
       targetSdkVersion 17
       versionCode 1
       versionName "1.0"

       testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }


    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'LICENSE.txt'
    }
}


configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:22.2.0'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'com.android.support.test:rules:0.3'
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}

Here is the test case that I'm trying to run.

@RunWith(AndroidJUnit4.class)
public class EspressoTest1 extends ActivityInstrumentationTestCase2<P1>{


    private P1 mActivity;

    public EspressoTest1() {
        super(P1.class);
    }

    public void setUp() throws Exception {

        super.setUp();
        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
        mActivity = getActivity();

    }

    public void Happy_test() {

        onView(withId(R.id.Btn)).check(matches(isDisplayed()));

    }
}

Test Configuration

And this is the test run configuration.


Picasso android Target must not be null


I am pretty new to android studio and still learning from video tutorials. I found Picasso and want to use it for my project but when i tried to apply/practice in a listview i dont seem to get it, im having an error that say Target must not be null. Ive tried the solutions around but still nothing. Sorry for my bad english. here is my code please help me.

class MyAdapter extends ArrayAdapter<String> {

Context context;

public MyAdapter(Context context, int row_layout, String[] values) {
    super(context, R.layout.row_layout2, values);
}



@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageHolder holder = null; 
    holder = new ImageHolder();

    LayoutInflater theInflater = LayoutInflater.from(getContext());
    View theView = theInflater.inflate(R.layout.row_layout2, parent, false);
    String tvShow = getItem(position);

    TextView theTextView = (TextView) theView.findViewById(R.id.textView1);

    theTextView.setText(tvShow);

    holder.imageIcon = (ImageView) convertView.findViewById(R.id.imageView1);

    convertView.setTag(holder);

    Picasso.with(this.context).load(getItem(R.drawable.sample4)).into(holder.imageIcon); //ERROR HERE

    return theView;
}

static class ImageHolder
{
    ImageView imageIcon;
}
}

MainActivity

public class MainActivity extends AppCompatActivity {

static class ImageHolder {
    ImageView imageIcon;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String[] favoriteShows = {
            "Hannibal", "Sherlock", "Supernatural"
    };

    //ImageHolder holder = new ImageHolder();

    ListAdapter theAdapter = new MyAdapter(this, R.layout.row_layout, favoriteShows);

    ListView theListView = (ListView) findViewById(R.id.theListView);

    theListView.setAdapter(theAdapter);

    theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            String tvShowPicked= "You selected " +
                    String.valueOf(adapterView.getItemAtPosition(position));

            Toast.makeText(MainActivity.this, tvShowPicked, Toast.LENGTH_SHORT).show();
        }
    });

Ive alse tried to put the Picasso lines in MainActivity to see if anything changes.

 holder.imageIcon = (ImageView) findViewById(R.id.imageView1);

    ImageView imageView = (ImageView) findViewById(R.id.imageView1);

    Picasso.with(this)
            .load(R.drawable.sample4)
            .into(holder.imageIcon);


Taking a picture then check its orientation, then rotate it then save it


I've tried to create an application (with Unity3D) that uses an Intent to take a photo and save it.

My issue is that saving the picture then checking its orientation to rotate it if needed and then saving again, is really long.

I think that's due to the fact that I'm using too much tools.

Do you have some tips to reduce the process time?

Here's my (edited) code, thanks in advance :

package com.falsename.my;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class PhotoPlugin implements myAndroidPlugin 
{
    private boolean canTakePhotos;
    private String mCurrentPhotoPath;
    private static PhotoPlugin instance;
    private myActivity activity;
    private File photoFile;

    static final int REQUEST_IMAGE_CAPTURE = 1;

    private File createImageFile() throws IOException 
    {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = this.activity.getExternalFilesDir(null);
        File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }


    private void dispatchTakePictureIntent(myActivity a) 
    {
        if(canTakePhotos)
        {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // Ensure that there's a camera activity to handle the intent
            if (takePictureIntent.resolveActivity(a.getPackageManager()) != null) {
                // Create the File where the photo should go
                photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    Log.e("my", ex.toString());
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(photoFile));
                    takePictureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
                             ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    a.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                }
            }
        }
    }


    public static void TakePicture()
    {
        instance.dispatchTakePictureIntent(instance.activity);    
    }

    @Override
    public void onActivityCreated(Context c, myActivity a) 
    {
        instance = this;
        this.activity = a;
        canTakePhotos = a.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);        
    }


    @Override
    public void onActivityResume(myActivity a) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onActivityPause(myActivity a) {

    }

    @Override
    public void onActivityNewIntent(myActivity a, Intent intent) 
    {

    }


    @Override
    public void onActivityResult(myActivity a,
        int requestCode, int resultCode, Intent data)
    {    
            if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_IMAGE_CAPTURE)
            {
                a.SendMessage("PhotoListener", "OnPhotoTaken", "");

                PhotoPluginOrientationCheckerParams params = new PhotoPluginOrientationCheckerParams();
                params.activity = a;
                params.path = this.mCurrentPhotoPath;
                params.file = this.photoFile;

                new PhotoPluginOrientationChecker().execute(params);
            }
    }    
}

and :

package com.falsename.my;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class PhotoPluginOrientationChecker extends AsyncTask<PhotoPluginOrientationCheckerParams, Void, Void>
{    
    myActivity a;
    String path; 
    File file;

    @Override
    protected Void doInBackground(PhotoPluginOrientationCheckerParams ... params) {

        a = params[0].activity;
        path = params[0].path;
        file = params[0].file;

        try 
        {
            ExifInterface ei = new ExifInterface(path);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

            switch(orientation) 
            {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    SaveBitmap(RotateBitmap(getBitmapFromUri(a, Uri.fromFile(file)), 90));
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    SaveBitmap(RotateBitmap(getBitmapFromUri(a, Uri.fromFile(file)), 180));
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    SaveBitmap(RotateBitmap(getBitmapFromUri(a, Uri.fromFile(file)), 270));
                    break;
            }
        }
        catch(IOException e)
        {
            Log.e("my", "Photo error");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) 
    {
        a.SendMessage("PhotoListener", "OnPhotoSaved", path);    
    }


    private void SaveBitmap(Bitmap bitmap)
    {
        FileOutputStream out = null;
        try
        {
            out = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
            // PNG is a lossless format, the compression factor (100) is ignored
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        } 
        finally 
        {
            try
            {
                if (out != null) 
                {
                    out.close();
                }
            } 
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static Bitmap RotateBitmap(Bitmap source, float angle)
    {
          Matrix matrix = new Matrix();
          matrix.postRotate(angle);
          return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }

    public Bitmap getBitmapFromUri(myActivity a, Uri imageUri) 
    {
        ContentResolver cr = a.getContentResolver();
        cr.notifyChange(imageUri, null);
        Bitmap bitmap;
        try {
            bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

with :

package com.falsename.my;

import java.io.File;

public class PhotoPluginOrientationCheckerParams 
{
    public myActivity activity;
    public String path;
    public File file;
}


Arabic text in facebook graph api response


hey i'm trying to get a facebook page posts
my problem is a specific post contain english and arabic and english text
the arabic text returned as hex string like this

\u0641\u064a_\u0623\u0628\u0648\u0638\u0628\u064a\   

even if i added "UTF-8" but this didn't do any thing

 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            result = IOUtils.toString(in, "UTF-8");

i tried to parse the response using apache common Hex class but i dont want to split the response and parse the arabic text individually.
and ideas on how i can do this

Note:Even if i tried same request on the browser i get same result only graph explorer show the text correctly


The correct way to create and write to a removable SD card directory on Android 4.4 KitKat and up?


I have spent literally hours now looking for (and trying) many different ways to write some files to my 4.4 Android KitKat's removable SD card after getting countless "eacces permission denied" errors. Seems now that Google has limited access to the filesystem on SD cards you are forced to only be able to write to directories owned by the application (eg: /Android/data/com.mycompany.myapp/files/).

Finally I was able to get something working that creates a directory on the removable SD card that can be written to. However I am curious why in order to gain access to this owned directory on the removable SD card I first had to create a new file object using a path to the external directory?

My implementation:

First I create two globals to house the strings of both the external and removable paths.

MainActivity

public class MainActivity extends ActionBarActivity {
    String externalStorageDirectory;//path to owned external storage files
    String secondaryStorageDirectory ;//path to owned removable storage files

Then I ask the system what the manufacturer specific directories are called and start concatenating absolute paths for both the externalStorage and removableStorage variables. I also create a new File object initialized with the path to the external app owned directory.

onCreate()

externalStorageDirectory = this.getExternalFilesDir(null).toString();//build absolute path to the app owned external directory
File folder = new File(externalStorageDirectory ); //THIS LINE IS CRUCIAL!!
Log.d("DEBUG", " - External Path" + externalStorageDirectory );// "/storage/emulated/0/Android/data/com.mycompany.myapp/files"


String ownedDirectory = "/Android/data/" + this.getPackageName() + "/files/";
secondaryStorageDirectory = System.getenv("SECONDARY_STORAGE").toString() + ownedDirectory;//build absolute path to the app owned removable directory
Log.d("DEBUG", " - Removable Path"+secondaryStorageDirectory );// "/storage/external/Android/data/com.mycompany.myapp/files/"

Finally I was able to write a file to my application's owned removable SD card directory. And more specifically I was using an AsyncTask to download my files and save them, method #1 of this post.

doInBackground()

output = new FileOutputStream(secondaryStorageDirectory + "myawesomefile.mp4");

Then I was able to navigate to the removable SD card directory via adb shell and I could see my file.

Adb shell output:

//internal storage
shell@QTAQZ3:/storage/emulated/0/Android/data/com.mycompany.myapp/files $ ls
s                                                                             <

//removable SD card
shell@QTAQZ3:/storage/external/Android/data/com.mycompany.myapp/files $ ls
ls
myawesomefile.mp4        
                                                                   <

And just to reiterate a little:

File folder = new File(externalStorageDirectory); //THIS LINE IS CRUCIAL!!
File folder = new File(secondaryStorageDirectory ); //THIS LINE DOES NOTHING?

So my questions are:

  • When I create that File object instance, what is happening that makes those directories available?
  • Why is having to call mkdir() or mkdirs() seem to unnecessary in this case as the dirs magically appear when the file object was created?
  • And why am I able to see my app's secondary(removable) directory only after I set the file to the external(non-removable) path?

Admittedly I am relatively new to Android programming, so I'm not even sure if this approach is correct or just a lucky hack? But it seems to work in my app for now.


Unable to Signup as Parseuser, after failed signup call


I am using Parse.com for my android app.

  • I have enabled ParseAnonymousUser

  • I am getting the following error, when test with the following scenario

    ---> Turn off wifi, and try to signup

    ---> Then Turn wifi on, without killing the app, and then try to signup again. I get the the error: "java.lang.IllegalArgumentException: Cannot sign up a user that is already signing up." (error code: -1) ---> If i kill the app, then i successfully signup

Here is my signup code snippet:

        ParseUser user = ParseUser.getCurrentUser();
        user.setUsername(phoneNum);
        user.setPassword(phoneNum);
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.show();
        user.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(ParseException e) {
                if (getActivity() == null) {
                    return;
                }
                mProgressDialog.dismiss();
                handleSignupResponse(e, phoneNum, name);

            }
        });

Please tell me a solution asap. I have been struck here for a day.


Delphi Record audio and save to stream


I am struggling to streaming audio on android. I can stream video using the TCameraComponent and Indy 10, now I'd like to add audio too. If I use TAudioCaptionDevice to record the audio, how can I get the stream to send to the client? The TAudioCaptionDevice class different from the TCameraComponent does not have an event when the buffer is ready, so I can not get the stream.

I've seen a lot of good components as wave audio, but unfortunately it just support Win32 and iOS, however I need to run on Android.

Is there a way to get the stream out of the TAudioCaptionDevice, to send to client? If not, how can I accomplish that?



AppCompat and EditText underline on different API


I'm trying to make underline line color change for EditText (validation, so it must be able to change in runtime). I'm using AppCompat to do it. The problem is that on API >= 21, I see transparent black line (gray overlay), instead of bolded version.

How to make it the same as in API 16?

I used this code to change tint:

    final Drawable originalDrawable = view.getBackground();
    final Drawable wrappedDrawable = DrawableCompat.wrap(originalDrawable);
    DrawableCompat.setTint(wrappedDrawable, Color.RED);
    setBackground(view,wrappedDrawable);

Pic


How to open a local PDF in android?


I need to show a local pdf in my android app, this pdf needs to be included in my app package, I have this but I dont know how to build a File class.

public void loadreglamento(View v){
        //Im supposed to give a path with the file but I really dont know how
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

    }

This code is Ok for me, I dont care If the user see the document in an external viewer/editor.

I also need to know where I have to copy the PDF file.

Thanks in advance.


Android Google Drive API Authentication


I'm having trouble with Google Drive API on my Android app. On my device, a Nexus 4 with Android 5.1.1 it's working fine. On my user's devices, the consent screen I had configured is not showing, instead, just a list selection dialog with the user's e-mail is showing, but it doesn't do anything.

I saw this issue on tree other devices with Android 5.0.1.

I configured the OAuth 2.0 credentials with my production SHA1 key and the consent screen. Like I said, it's working fine on my device.

I'm using the following parameters to compile my app:

  • minSdkVersion=15
  • targeSdKVerion=22
  • compileSdkVersion=22
  • Build Tools: 22.0.1
  • Platform Tools: 23rc3

And these google libs:

  • com.android.support:support-v4:22.2.0
  • com.android.support:appcompat-v7:22.2.0
  • com.android.support:design:22.2.0
  • com.google.android.gms:play-services-ads:7.5.0
  • com.google.android.gms:play-services-drive:7.5.0

Thank you!


SIGSEGV in CallVoidMethod jni


I have a java appliction with some jni native methods. One of them is readFile, and it is called like this:

OutputStream outStream = null;
File file = new File("Alf.txt");

try {
    outStream = new FileOutputStream(file);
    myObject.readFile("TestFile.txt",outStream);
...

in my jni implementation I do :

JNIEXPORT jint JNICALL Java_com_example_mylib_SomeClass_readFile
(JNIEnv *env, jclass, jstring java_string, jobject stream) {


jclass classOutputStream = env->FindClass("java/io/OutputStream");
if (classOutputStream == NULL)
{
      Log::err("classOutputStream == NULL;");
      return -1;
}
jmethodID OutputStream_write_ID = env->GetMethodID(classOutputStream, "write", "([BII)V");
if (OutputStream_write_ID == NULL)
{
   return -1;
}
char* buf = "hello";

env->CallVoidMethod((jobject)stream, OutputStream_write_ID,buf,0,5);

and when I call CallVoidMethod I get

# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f4a85a5e1e1, pid=25597, tid=139958068348672
#
# JRE version: Java(TM) SE Runtime Environment (8.0_25-b17) (build 1.8.0_25-b17)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.25-b02 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.so+0x6ad1e1]  jni_GetArrayLength+0xb1
#
# Failed to write core dump. Core dumps have been disabled. To enable  core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /.../hs_err_pid25597.log

I checked - no variables are == NULL, what do I do wrong?