vendredi 8 mai 2015

KenBurnsView creating smooth custom animation

I'm using the KenBurnsView library in here

But transition is not smooth and I don't know how to use the following code noted on github:

RandomTransitionGenerator generator = new RandomTransitionGenerator(duration, interpolator);
kbv.setTransitionGenerator(generator);

Can anyone help me how to create a smooth transition?

Robolectric throws Resources$NotFoundException when trying to access resource in raw folder

When I try to access a raw resource I receive an android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f060000 error.

The resource is a .bks certificate, used for server validation. It is stored on the res/raw folder.

The most awkward thing is that when I copied the certificate (and the validation architecture) to a fresh project (that I built just to test this), it worked!

I'm using nenick's custom runner, so Robolectric can correctly find the folders for manifest, res and assets. When I go to the intermediates/res/debug folder all the resources are there. I don't have flavours in the project (The project used to have, I removed them. Maybe this is the problem?)

I'm using com.android.tools.build:gradle:1.2.2. buildToolsVersion '22.0.1'. I have a lot of dependencies on the project :(

Also, I'm using testCompile 'org.robolectric:robolectric:3.0-rc2' and testCompile 'org.robolectric:shadows-support-v4:3.0-rc2' The stacktrace:

android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f060000
    at org.robolectric.shadows.ShadowResources.getResName(ShadowResources.java:346)
    at org.robolectric.shadows.ShadowResources.openRawResource(ShadowResources.java:385)
    at android.content.res.Resources.openRawResource(Resources.java)
    at com.xxx.xxx.xxx.ssl.CertificateHelper.loadKeyStoreFromRaw(CertificateHelper.java:145)
    at com.xxx.xxx.xxx.xxx.XXX.createSSLSocketFactory(XXX.java:432)
    at com.xxx.xxx.xxx.xxx.xxx.XXX.<init>(XXX.java:92)
    at com.xxx.xxx.xxx.xxx.xxx.XXX.initiate(XXX.java:73)
    at com.xxx.xxx.xxx.MainApplication.onCreate(MainApplication.java:60)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:131)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:431)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:224)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:168)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

java.lang.RuntimeException: android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f060000
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:228)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:168)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f060000
    at org.robolectric.shadows.ShadowResources.getResName(ShadowResources.java:346)
    at org.robolectric.shadows.ShadowResources.openRawResource(ShadowResources.java:385)
    at android.content.res.Resources.openRawResource(Resources.java)
    at com.xxx.xxx.xxx.xxx.CertificateHelper.loadKeyStoreFromRaw(CertificateHelper.java:145)
    at com.xxx.xxx.xxx.xxx.XXX.createSSLSocketFactory(XXX.java:432)
    at xxx.xxx.xxx.xxx.xxx.xxx.XXX.<init>(TrafficManagerImpl.java:92)
    at xxx.xxx.xxx.xxx.xxx.xxx.XXX.initiate(XXX.java:73)
    at com.xxx.xxx.xxx.MainApplication.onCreate(MainApplication.java:60)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:131)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:431)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:224)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:168)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    ... 1 more

Sorry for the "xxx" on the package/class names, but I don't own the code.

Edit 1 to add the code

The code that is getting executed at the onCreate of the application is:

InputStream is = resources.openRawResource(keystoreId);

The variable keystoreId is a R.raw.keystore.

Does anyone knows what could be causing this?

Edit 2 to provid more info

An extra info: I have a different application ID on the build.gradle of the module and on the AndroidManifest. Even when I changed the project to make them be the same, things didn't work and the bug still existed :(

Clicking on overlapping UI elements

I have a Fragment that takes up half the activity. Behind it, a ListView. The problem is that when the user taps anywhere on the Fragmentthat overlaps with a row on the list view, the row gets clicked and it's onClick method gets called.

A workaround was giving an onClick to the LinearLayout in the Fragment layout XML file, like so :

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.karimnseir.instabeat.IBMenuFragment"
    android:background="@color/material_blue_grey_950"
    android:onClick="doNothing">

Which I don't think is very elegant because I have to add a doNothing method to every activity that uses this fragment

If there isn't a way to stop onClicks from being called on elements BEHIND the fragment, how can I still give it a null onClick without having a dummy method everywhere ?

Thank you

Cannot get facebook video details using Graph API

I'm trying to get video information (source URL, preview URL, title, description) using Facebook Graph API on Android. Everything work fine for friend's videos and some random public videos found on Facebook.

However, it doesn't work for videos uploaded using testing user accounts. These users are not in my friends list.

The HTTP query is:

GET http://ift.tt/1RktfIk}

The API returns:

{ "error": { "message": "Unsupported get request. Please read the Graph API documentation at http://ift.tt/1cZ9288", "type": "GraphMethodException", "code": 100
} }

This happens both when using Facebook SDK for Android and Graph API Explorer (http://ift.tt/jdBOke). This doesn't happen if I use APP Token instead of user access token.

If I use video owner's access token I can see video details but then requests fail for my own videos.

Every tested video is "public". I can watch these videos on Facebook without any problem.

What am I doing wrong?

Get Logo to left in ActionBar

First I have to say that I know this isn't correct anymore to the Google Guidelines. But still I need to know it.

I'm trying to Add the Android Icon in my ActionBar. Logo are not displayed in Actionbar, using AppCompat

This gave my the answer. But my problem now is that the logo is in the middle of the ActionBar. I want it in the left.

Code:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarStyle">@style/MyActionBarLogo</item>
</style>

<style name="MyActionBarLogo" parent="@style/Widget.AppCompat.Light.ActionBar">
    <item name="background">@color/background_material_dark</item>
    <item name="logo">@drawable/icon</item>
    <item name="displayOptions">useLogo|showHome</item>
</style>

Printscreen:

PrintScreen

Anyone an idea? I have the feeling it's something stupid...

EDIT: Added Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
    package="com.ap.brecht.myapplication" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

How to get duration time, average pace, distance in GoogleMaps

I searched for a solution or hint how to get Duration,average pace and distance from GoogleMaps v2 api but without success for now. What I try to do is an App to track run activity and just show at real time relevant info about this run. Can anyone throw me a bone Please?

Kivy: How to avoid overlapping BoxLayout widgets

I have a Kivy app that is comprised of 3 rows. The first row is an ActionBar, the second row is a search field and button, and the last row is some text (split into two columns). My problem is that the last row of text is "overlapping" the 1st and 2nd rows. Here is a screen grab to illustrate the problem:

enter image description here

I used Paint to alter the image to depict what I'm trying to achieve:

enter image description here

I was following along to the suggestions for using nested layouts here, but I couldn't get it to work properly. Here is my main.py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class ShowActionBar(BoxLayout):
    pass

class ShowApp(ShowActionBar):
    pass

class MyTestApp(App):
    def build(self):
        return ShowApp()

if __name__ == "__main__":
    MyTestApp().run()

Here is my kv file:

<ShowActionBar>:
    ActionBar:
        ActionView:
            use_seperator: True
            ActionPrevious:
                title: "Magic Buffet"
                with_previous: False
            ActionOverflow:
                ActionButton:
                    text: "Settings"
            ActionButton:
                text: "Log Out"

<ShowApp>:
    orientation: "vertical"
    BoxLayout:
        orientation: "horizontal"
        height: "35dp"
        size_hint_y: None

        TextInput:
            height: 30
            width: 200
            size_hint_y: None
            size_hint_x: None            
            focus: False
            multiline: False
            hint_text: "What would you like to Eat?"

        Button:
            height: 30
            width: 100
            size_hint_y: None
            size_hint_x: None    
            text: "Search Foods"

    BoxLayout:
        orientation: "horizontal"
        MenuLeftColumn:
        MenuRightColumn:

    # Blank label to fill out the remaining bottom space
    Label:

<MenuLeftColumn@BoxLayout>:
    orientation: "vertical"

    BoxLayout:
        orientation: "horizontal"
        height: 30
        width: 400
        size_hint_y: None
        size_hint_x: None    
        Label:
            text: "Menu Item 1"
            font_size: "20dp"

    # The same "Menu Item 1" widget is repeated multiple
    # times to demonstrate a long list of widgets.
    # I've removed it for brevity

    BoxLayout:
        orientation: "horizontal"
        height: 30
        width: 400
        size_hint_y: None
        size_hint_x: None    
        Label:
            text: "Menu Item 1"
            font_size: "20dp"

<MenuRightColumn@BoxLayout>:
    orientation: "vertical"
    BoxLayout:
        orientation: "horizontal"
        height: 30
        width: 400
        size_hint_y: None
        size_hint_x: None    
        Label:
            text: "Price"
            font_size: "20dp"

What is the correct way to stack widgets (nested or otherwise) so that this overlapping behavior is avoided?

SQLITE database defaultly add some values [on hold]

In my database i have 4 coloumn KEY_id,KEY_NAME, KEY_PH_NO,KEY_DATE this is a bookmark table ,when i add some data that time only it added to book mark ,but my problem is defaultly it hold some data in bookmark table.below mentioned my code,thanks in advance..

table

        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_BOOKMARK + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"+ KEY_PH_NO + " TEXT" +KEY_DATE+"TEXT"+  ")";


        SQLiteDatabase db =myDataBase;

        db.execSQL(CREATE_CONTACTS_TABLE);

set bookmark

public String setBookMark(int ibook,int ichapter,int iversion,int flag) {

    try{

    if(iversion==-1)

        return "";

    int rowid=getRowId(ibook,ichapter,iversion);

    if(rowid==-1)

        return "";

    SQLiteDatabase db =myDataBase;

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String strids=rowid+"";//ibook+"@"+ichapter+"@"+iversion+"@"+rowid;

    String [] sqlSelect = {"0 _id", KEY_NAME,KEY_PH_NO,KEY_ID}; 

    String sqlTables = TABLE_BOOKMARK;

    String strQuery=KEY_NAME+"='" + strids+"'";

    String strOrder=KEY_ID + "  asc";

    String strdate= KEY_DATE+" DESC";


    /*long time= System.currentTimeMillis();

    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 

    String dateString = formatter.format(new Date(time));*/



    Calendar cal=Calendar.getInstance();

    SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy");

    String formattedDate = df.format(cal.getTime());

    qb.setTables(sqlTables);

    Cursor c = qb.query(db, sqlSelect, strQuery, null,null, null, strOrder);

    if(c!=null)
    {

        c.moveToFirst();

        if(c.getCount()>=1)

        {

            String status=c.getString(c.getColumnIndex(KEY_PH_NO));

            if(status.equals("1"))

            {

                if(flag==0)

                    return "Already Available in Favourite";

                else

                {
                    ContentValues values = new ContentValues();

                    values.put(KEY_NAME, strids);

                    values.put(KEY_PH_NO, "0");

                    values.put(KEY_DATE, formattedDate);

                    db.update(sqlTables, values, KEY_ID + " = ?",new String[] { String.valueOf(c.getString(c.getColumnIndex(KEY_ID))) });
                    return "Removed from Favourite";

                }

            }

            else

            {

                ContentValues values = new ContentValues();
                values.put(KEY_NAME, strids);
                values.put(KEY_PH_NO, "1");
                values.put(KEY_DATE, formattedDate);
                db.update(sqlTables, values, KEY_ID + " = ?",new String[] { String.valueOf(c.getString(c.getColumnIndex(KEY_ID))) });
                return "Added to Favourite";
            }
        }
        else
        {
            ContentValues values = new ContentValues();
            values.put(KEY_NAME, strids);
            values.put(KEY_PH_NO, "1");
            values.put(KEY_DATE, formattedDate);
            db.insert(sqlTables, null, values);
            return "Added to bookmark";
        }
    }
    else
    {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, strids);
        values.put(KEY_PH_NO, "1");
        values.put(KEY_DATE, formattedDate);
        db.insert(sqlTables, null, values);
        return "Added to bookmark";
    }
    }
    catch (Exception e) {
        Log.e("setBookMark Exception",e.toString());
    }
    return "";

}

get bookmark

public Cursor getBookMarks() {


    try{


    SQLiteDatabase db =myDataBase;// getReadableDatabase();

    SQLiteQueryBuilder qb1 = new SQLiteQueryBuilder();

    String [] sqlSelect1 = {"0 _id", KEY_NAME,KEY_PH_NO,KEY_ID}; 

    String sqlTables1 = TABLE_BOOKMARK;

    String strQuery1=KEY_PH_NO+"='1'";

    String strOrder1=KEY_ID + " asc";

    qb1.setTables(sqlTables1);

    String strvalues="";

    Cursor curs = qb1.query(db, sqlSelect1, strQuery1, null,null, null, strOrder1);

    if(curs!=null)

    {

        curs.moveToFirst();

        if(curs.getCount()>=1)

        {
            do {
                strvalues+=""+curs.getString(curs.getColumnIndex(KEY_NAME))+",";

             }
 while (curs.moveToNext());

            //curs.close();

            if(strvalues.length()>=1)

            {
                strvalues+="-1";

                String [] sqlSelect = {"0 _id", "TB","Version","Book","Chapter","NKJ"}; 

                String sqlTables = "hindibible";

                SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

                qb.setTables(sqlTables);
                //String query = "SELECT * FROM "+sqlTables+" WHERE ID IN (" + strvalues + ")";

                String query = "ID IN (" + strvalues + ")";

                //Cursor bible = db.rawQuery(query, null);

                Cursor bible = qb.query(db, sqlSelect, query, null,null, null, null);
                bible.moveToFirst();

                return bible;
            }
        }
        else
        {

        }
    }
    else
    {

    }
    }
    catch (Exception e) {
        Log.d("setBookMark",e.toString());
    }
    return null;

}



in aActivity(ListActivity)

private void addBookMark(int pos)

{

    try

    {

        int verse=pos;

        if(lIntVerse!=-1)

            verse=lIntVerse;

        String strret=db.setBookMark(lIntBookId,lIntchapter,verse,0);

        if(strret.length()>2){}

        Toast.makeText(getApplicationContext(), strret, 

Toast.LENGTH_LONG).show();

    }

    catch (Exception e) 

{

        // TODO: handle exception

    }

}


getBookmark()

private void showFav()

{


    try

{

        Cursor cursor=db.getBookMarks();

        gcursor=cursor;

        this.m_adapter = new Bookmark_Adapter(this, cursor,3);

        listview.setAdapter(this.m_adapter);

        listview.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int pos, long arg3)

{ // TODO Auto-generated method stub

                contposition=pos;

                //registerForContextMenu(listview);

                share_verse(pos);

                return false;
            }

        });

    }catch (Exception e)

{

        Log.d("SSSSS","111="+e.toString());
    }
}


ADAPTER CLASS:

book1.setText("AAAA");

        short ibook=cursor.getShort(cursor.getColumnIndex("Book"));


        short ichap=cursor.getShort(cursor.getColumnIndex("Chapter"));

        short ivers=cursor.getShort(cursor.getColumnIndex("Version"));

        try

{

        String strdata=mathstxt[ibook-1]+" "+ichap+"  "+ivers;

        book1.setText(strdata);

Android Facebook version 4.0 open graph post bitmap failing

I have the code below attempting to post an Open Graph story with attached bitmap image. The Bitmap is about 1 Meg in size so is within the Facebook limitation. The Share Dialog is displayed and the post will work but with no image showing! I do have appropriate provider entry in the manifest and I get no reported errors. Any thoughts on what may be wrong?

        // get App Facebook namespace
        final String fbNamespace = gameIdentity.getFbNamespace();

        // Create an object
        ShareOpenGraphObject.Builder object = new     ShareOpenGraphObject.Builder()
                .putString("og:type", fbNamespace + ":board")
                .putString("og:title", params.getString("name"))
                .putString("og:description", params.getString("caption"))
                .putString("og:url", "http://ift.tt/1Rktcwo");


        // if we have an image, add to graph object
        if (image != null) {
            // build Photo object
            SharePhoto photo = new SharePhoto.Builder()
                    .setBitmap(image)
                    .setUserGenerated(true)
                    .build();
            // add to graph object
            object.putPhoto(fbNamespace + ":board", photo);
        }

        // Create an action
        ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
                .setActionType(fbNamespace + ":complete")
                .putObject("board", object.build())
                .build();

        // Create the content
        ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
                .setPreviewPropertyName("board")
                .setAction(action)
                .build();

        // initiate share process
        ShareDialog shareDialog = new ShareDialog(this);
        shareDialog.show(content);

Android/Xamarin is not working on with api 17

Im building a mob app targeting android in Xamarin studio .I made the minimum and target android version is 4.2 jelly bean . The app is working perfectly on my phone samsung duos 4.4.4 and on the emulator 4.4.2 but Im trying to test it on emulator running 4.2.2 ,it is not working and the application stops responding . Im somehow sure it has to do with the SDK and i tried to set the link behavior to : no linking ,linking sdk assemblies and link all but nothing is working . It may also worth mentioning that im using hybrid app (webview + javascript/jQuery) .

Appreciate any ideas?

Regards Ayad

Accelerometer`s equations

I have been going over Accelerometer`s tutorial and some aspects still confusing to me:

  • values[0]: Acceleration minus Gx on the x-axis
  • values[1]: Acceleration minus Gy on the y-axis
  • values[2]: Acceleration minus Gz on the z-axis

The question is: when the device lies flat on a table in its default orientation
it outputs +9,81 instead of -9.81.

If the device lies flat on table Z-axis points down - so the Gz is *9,81*
therefore values[2] shall be ( 0 - Gz) = (0 - 9,81) = -9,81.


The question is Why is that ?
With X and Y axes there is no such confusion.

EditText with "constants"

I want to customize an EditText that there are "constants" like in the picture below, so that I get the minutes and the seconds. (the number interface is irrelevant)

How to implement a draggable ExtendedOverlayItem on OSMDroid?

I'm developing a feature to drag a map overlay (using ExtendedOverlayItem class), using osmdroid and OSMBonusPack.

This question talks about a possible solution:

Unable to implement onTouchEvent (Drag & Drop) with Osmdroid

So, my questions are:

1 - Where do I put that code?

2 - Should I create a new class? extending from which other class?

Additional Similar questions:

How do you implement OverlayItem to be draggable? (Using ItemizedIconOverlays if possible)

confusion between overlay, overlayitem and itemizedoverley

JavaFX ScrollPane on Android - Too

I have just coded a simple example of using a scrolling pane in JavaFX. Just one ScrollPane placed in the Scene, and the ScrollPane holds a Label component with a large text. Using gradle I have uploaded the app on a Nexus 4 android device. As you can see from the video I have uploaded, the scrolling is way too slow. I am sure others have experienced this. Any suggestion of how this can be changed to the native speed scroll is really much appreciated.

Source code of the app can be downloaded from here.

AndroidFX.java

public class AndroidFX extends Application{

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent mySearchListFXML = getFXMLPane("/fxml/ScrollPaneWithLabel.fxml");
        primaryStage.setScene(new Scene(mySearchListFXML));
        primaryStage.setWidth(Screen.getPrimary().getVisualBounds().getWidth()); primaryStage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());     
        primaryStage.show();
    }

    public static Parent getFXMLPane(String url) throws IOException {
        URL location = AndroidFX.class.getResource(url);
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(location);
        Parent pane = fxmlLoader.load();
        return pane;
    }
}

ScrollPaneWithLabel.fxml

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

<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<ScrollPane fx:id="scrollPane" fitToWidth="true" hbarPolicy="NEVER" pannable="true" style="-fx-background: white;" xmlns="http://ift.tt/1cgvoBd" xmlns:fx="http://ift.tt/1cgvoBb">
   <content>
      <Label text="<VERY LARGE TEXT HERE>" wrapText="true" />
   </content>
</ScrollPane>

Which folder will the element receive the params? (Android)

My avd is mdpi and I have an element that is defined in values, values-hdpi, values-large-hdpi, values-xlarge folders. When I run the project, from which folder will the compiler get the element references. Note: this element is not defined in Activity.java.

How to stop while loop after back button is hit

I have tried so many ways of solving my problem, but still no success.I have a method, which returns me a string value and I am using it to update TextView on my screen like this: outCPU.setText(getCpuInfo());

Which would be fine, but I need to update this TextView until back button was pressed.

I guess i have need a while loop which starts after activity has been created and stops after back button was pressed. This loop should be in a new thread, because:- I have to load the activity first and execute the loop in another thread so the executing won't affect main thread and loading of the activity.

As I've already said, I don't know how to do this properly even though i have spent few hours on it.

Could someone show me an example how to get this done? Thanks...!!

Android is ignoring padding inside EditText

could somebody tell my why Android is ignoring padding i added? Have i did something terribly stupid? I was trying to make some custom inputs for texts. But i encountered weird problem with padding inside EditTexts

Emaulator, IDE preview, IDE properties

Code:

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/lightBeige"
    tools:context=".LoginActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="1">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:background="@color/lightBrown"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_weight="0.53"
            android:contentDescription="@string/app_logo"
            android:src="@drawable/logo"
            android:paddingLeft="20dp"
            android:paddingRight="20dp" />


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="10dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:capitalize="characters"
                android:text="@string/login_text"
                android:textSize="40dp"
                android:background="@color/semiGold"
                android:textStyle="bold"
                android:paddingBottom="10dp"
                android:paddingTop="10dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:layout_marginBottom="20dp"
                android:layout_marginTop="20dp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/greyBeige"
                android:orientation="vertical"
                android:padding="20dp"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp">

                <EditText
                    android:id="@+id/login_name"
                    android:background="@drawable/edit_text_cronline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:inputType="text"
                    android:hint="@string/input_login_text"
                    android:paddingTop="15dp"
                    android:paddingBottom="15dp"
                    android:paddingLeft="10dp"
                    android:layout_marginBottom="5dp"
                    android:paddingRight="10dp" />
                <EditText
                    android:id="@+id/login_pass"
                    android:background="@drawable/edit_text_cronline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:inputType="text"
                    android:hint="@string/input_password_text"
                    android:paddingTop="15dp"
                    android:paddingBottom="15dp"
                    android:paddingLeft="10dp"
                    android:layout_marginBottom="5dp"
                    android:paddingRight="10dp" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/button_login_text"
                    android:id="@+id/loginButton"
                    android:background="@drawable/button_cronline"/>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>
</RelativeLayout>

And my custom thingy for inputs:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://ift.tt/nIICcg">

    <!-- main color -->
    <item
        android:bottom="4dp"
        android:left="1.5dp"
        android:right="1.5dp">
        <shape>
            <solid android:color="#FEFEFE" />
        </shape>
    </item>

    <!-- draw another block to cut-off the left and right bars -->
    <item android:bottom="5.0dp">
        <shape>
            <solid android:color="#FEFEFE" />
        </shape>
    </item>

</layer-list>

Android TCP Server limitation

I need to maintain TCP Server in my Android app.

  • In my application I had connected 12 clients.
  • All clients are in active.
  • After some period of time, one or more clients are getting connection time out.

I need to know, how many clients can be connect with my TCP server without connection time out.

Note: My Device has a 2GB RAM.Is the number of clients is various depends upon the RAM Limit ?

ACTION_IMAGE_CAPTURE | Can't get past SAVE/DELETE menu

First of, this is not a duplicate, I've seen similar posts but with no good answers. Now, this is the menu I'm talking about: Tinypic.

This only happens in some devices, in my particular Samsung Galaxy S3 Neo, it does well, and everything that it's supposed to, but on a friend of mines Wiko (portuguese brand, but pretty good), aswell as on the emulator above, it just does nothing when I click on "save". Here is my code if you could take a look:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                      imageFile = new File(
                              Environment
                                      .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), path
                      );


                      Uri tempuri = Uri.fromFile(imageFile);
                      intent.putExtra(MediaStore.EXTRA_OUTPUT, tempuri);
                      intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                      startActivityForResult(intent, 0);

If you need any more details tell me :)

How to add token library to Firebase android library

I have read the Firebase documentation, but Correct me if I'm wrong the way did it.

The Steps That I Understand from the Docs :

  1. download Token library for java http://ift.tt/1InMcWD but I dont know how to download this via android studio gradle
  2. Generete the token using firebas secret
  3. and set as admin to true.

my problem is I don't know how to download the TokenGenerator lib. Please someone help.

I'm using java language developing android app.

Android restore social session with spring framework

I need to restore user session of some social network (f.e twitter or linkedIn) by token data with spring social. When app starts again and take saved token from sharedPref. Is it real? I spent hours, but cannot restore connection. Please help me if can. I will be glad any proposals.

Selecting dates 3 days before now on Android with SQLite

I have a table with events, and want to select all events which happen from three days ago. (The events do belong to categories which is a field in the Article table which has to description etc., but that works).

This is my code:

    public List<Event> findByCategory(long catId, int start, int count) throws Exception {
        String limit = "";
        if (count > 0) limit = start + "," + count;

        SQLiteQueryBuilder _QB = new SQLiteQueryBuilder();
        _QB.setTables("Event e INNER JOIN Article a ON e.articleId=a.id");

        String[] rows = _fields.keySet().toArray(new String[0]);
        for (int i = 0; i < rows.length; i++) {
            rows[i] = "e." + rows[i];
        }
        Cursor cursor = _QB.query(_db, rows, "date(e.startTime) > date('now','-3 days') AND EXISTS(SELECT * FROM CategoryArticleLink WHERE CategoryArticleLink.articleId = a.id AND EXISTS (SELECT * FROM Category WHERE Category.id = CategoryArticleLink.categoryId AND Category.id = '" + catId + "'))", null, null, null, "e.startTime ASC", limit);

        List<Event> list = new ArrayList<>(cursor.getCount());
        if (cursor.moveToFirst()) {
            do {
                Event item = getObject(cursor);
                list.add(item);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return list;
    }

The resulting Query is:

SQLiteQuery: SELECT e.articleId, e.keynote, e.locationId, e.id, e.finishTime, e.startTime, e.languageCode, e.flag, e.lastUpdate FROM Event e INNER JOIN Article a ON e.articleId=a.id WHERE (date(e.startTime) > date('now','-3 days') AND EXISTS(SELECT * FROM CategoryArticleLink WHERE CategoryArticleLink.articleId = a.id AND EXISTS (SELECT * FROM Category WHERE Category.id = CategoryArticleLink.categoryId AND Category.id = '9'))) ORDER BY e.startTime ASC LIMIT 0,8

This returns an empty result set. However, if I take the date selection (date(e.startTime) > date('now','-3 days')) out of the query it returns all records as expected. So I must be doing something small wrong, but I just don't see what.

The field type on database generation is 'DATE', so that should be ok I expect.

Memory leaks in Android handler

I am trying to read data from a serial bluetooth stream in my android application. The data is send to a handler to display it. It works fine for a few minutes and then it stops showing data (The app keeps running however). I think it has to do with memory leaks in my handler but I don't know how to solve it..

This is where I found the code

I will be so happy if someone can help me. Thanks in advance

public class MainActivity extends ActionBarActivity {

    static BluetoothAdapter mBluetoothAdapter = null;
    static Handler mHandler = null;

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

        //Does the device support bluetooth?
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Device does not support Bluetooth",Toast.LENGTH_LONG).show();
        }

        //Turn on Bluetooth if disabled
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }

        //Get the Bluetooth module device
        BluetoothDevice mDevice = null;
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if(device.getName().equals("HC-06")) {
                    mDevice = device;
                }
            }
        }
        if(mDevice == null){
            Toast.makeText(this,"Device not found",Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(this,"connected to " + mDevice.getName(),Toast.LENGTH_LONG).show();

            ConnectThread mConnectThread = new ConnectThread(mDevice);
            mConnectThread.start();

            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    byte[] writeBuf = (byte[]) msg.obj;
                    int begin = (int)msg.arg1;
                    int end = (int)msg.arg2;
                    switch(msg.what) {
                        case 1:
                            String writeMessage = new String(writeBuf);
                            writeMessage = writeMessage.substring(begin, end);

                            ScrollView scrollView1 = (ScrollView) findViewById(R.id.scroll);
                            TextView textView1 = (TextView) findViewById(R.id.statusText);
                            textView1.append(writeMessage + "\n");
                            scrollView1.fullScroll(View.FOCUS_DOWN);

                            break;
                    }
                }
            };
    }
}

RecyclerView data are multiple modified/displayed

I've a small problem with my RecyclerView. It's well filled by my adapter with some TextViews, an ImageView and some buttons. When there's an OnClick-Event on one of the buttons it modifies a TextView - so far so good but when I'm scrolling some items further another RecyclerView-item is also modified and has the value of the originally modified one.

I tried already to move the setOnClickListener into my ViewHolder but the result was the same.

May be you can help me.

public class MyAdapter extends RecyclerView.Adapter {

// some vars .... and a constructor

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.recyclerview_item, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
    // ...

    viewHolder.myTextView.setText("clear");
    viewHolder.myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewHolder.myTextView.setText("modified");
        }
    });

    // ...
}

@Override
  public int getItemCount() {
    return mProducts.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView productMultibuy;
    private Button productAddToShoppingList;

    // ...
    public ViewHolder(View itemView) {
        super(itemView);

        myTextView = (TextView) itemView.findViewById(R.id.my_textview);
        myButton = (Button) itemView.findViewById(R.id.my_button);

        // ...


        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });


        itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return false;
            }
        });

    }
 }

}

Fragment is Not saving any data, Starting as fresh one when loaded every time

My intention in writing that question is I've a fragment and I've loaded a listview with some data and I went to another fragment, now when i come back to that fragment listview is not loaded, means again its fresh start.

Another Problem: I've a fragment, I've instantiated it and there is a View(say Linear Layout) in it, I've added two children to it. I've loaded another fragment and came back. again same problem. fragment started again with no children .... Please Help

Code for second problem named Another Problem:

Fragment.class

package view;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

import adapters.PlayListLoadingAdapterForSpeakers;
import amiTechnologies.products.multizoneplayer.R;
import interfaces.MessageFromMainActivityToFrgmentMultizone;
import interfaces.MessageFromSpeakerDetectorToFragmentMultizoning;
import model.Globals;
import model.PlayListModelSaved;
import utilities.SpeakerInfo;
import utilities.Track;

/**
 * Created by admin on 5/6/2015.
 */
public class Fragment extends Fragment {

    ImageView loadPlayLists;
    PlayListModelSaved playListModelSaved = PlayListModelSaved.getInstance();
    PlayListLoadingAdapterForSpeakers adapterForSpeakers;
    ArrayList<Track> playlistContents = new ArrayList<Track>();
    ListView tracksListViewForSpeakers;
    LinearLayout parentOfDockedPlayers;
    ArrayList<String> myZoneNames;
    ArrayList<String> myIpAddress;


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_multi_zoning, container, false);
        loadPlayLists = (ImageView) view.findViewById(R.id.loadPlayList);
        parentOfDockedPlayers = (LinearLayout) view.findViewById(R.id.parentOfMediaPlayer);


        getZonesAndIps();
        addZones();

        tracksListViewForSpeakers = (ListView) view.findViewById(R.id.loadedPlayList);
        adapterForSpeakers = new PlayListLoadingAdapterForSpeakers(getActivity(), R.layout.row_playlistcontent, playlistContents);
        tracksListViewForSpeakers.setAdapter(adapterForSpeakers);

        loadPlayLists.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] playlists = new String[playListModelSaved.getPlayLists().size()];
                playlists = playListModelSaved.getPlayLists().toArray(playlists);
                if (playlists.length > 0) {
                    AlertDialog.Builder selectPlayList = new AlertDialog.Builder(getActivity());
                    selectPlayList.setTitle("Select from PlayLists");
                    selectPlayList.setItems(playlists, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int playlist) {
                            tracksListViewForSpeakers.setVisibility(View.VISIBLE);
                            loadPlayLists.setVisibility(View.GONE);
                            loadPlayistContents(playlist);

//                            saveToPlaylist(playlist, audioAdapter.albumsStatesList);
                        }
                    });

                    selectPlayList.create().show();

                } else {
                    Toast.makeText(getActivity(), "There are no PlayLists...", Toast.LENGTH_SHORT).show();
//                    AddPlayList();

                }
            }
        });

        return view;
    }


    public void getZonesAndIps(){
            myZoneNames = new ArrayList<String>();
            for(String value:Globals.zoneMappingTable.values()){
            myZoneNames.add(value);
        }
            myIpAddress= new ArrayList<String>();
            for(String key:Globals.zoneMappingTable.keySet()){
             myIpAddress.add(key);
        }
}


    private void addZones() {
        int count = parentOfDockedPlayers.getChildCount();
        int k;
        if(count>=0){
           k= count;
        }else{
            k=0;
        }
        int i = Globals.zoneMappingTable.size();
        if(i<=0){
            Toast.makeText(getActivity(),"There are no WIFI Speakers detected",Toast.LENGTH_SHORT).show();
        }
        else{
            for(int j=0;j<i;j++){
                SingleZonePlayerView singleZonePlayerView = new SingleZonePlayerView(getActivity());
                singleZonePlayerView.setSpeakerName(myZoneNames.get(j));
                singleZonePlayerView.setSpeakerIp(myIpAddress.get(j));
//                singleZonePlayerView.setMessageFromSingleZonePlayerViewToMainActivity(mainActivity);
                singleZonePlayerView.setPosition(k);

                parentOfDockedPlayers.addView(singleZonePlayerView);
            }
        }
    }

//    @Override
    public void allAvailableSpeakersDetected(ArrayList<SpeakerInfo> availableSpeakers) {
        int count = parentOfDockedPlayers.getChildCount();
        int j;
        if(count>=0){
            j= count;
        }else{
            j=0;
        }

        int size = availableSpeakers.size();
        if (size <= 0) {
            getToast("There are no WIFI Speakers detected");
        } else {

            for (int i = 0; i < size; i++,j++) {
                SingleZonePlayerView singleZonePlayerView = new SingleZonePlayerView(getActivity());
                singleZonePlayerView.setSpeakerName(availableSpeakers.get(i).getSpeakerName());
                singleZonePlayerView.setSpeakerIp(availableSpeakers.get(i).getSpeakerIp());
                singleZonePlayerView.setPosition(j);

                parentOfDockedPlayers.addView(singleZonePlayerView);
            }
        }
    }


        private void loadPlayistContents ( int playlist){
            ArrayList<String> playListTitles = playListModelSaved.getPlayLists();
            String fileName = playListTitles.get(playlist);

            if (playlistContents.size() > 0)
                playlistContents.clear();

            playlistContents.addAll(playListModelSaved.getSavedPlayListsContent(fileName));
            if (playlistContents.size() == 0) {
                Toast.makeText(getActivity(), "Empty PlayList", Toast.LENGTH_SHORT).show();
                tracksListViewForSpeakers.setVisibility(View.GONE);
                loadPlayLists.setVisibility(View.VISIBLE);
            }

            adapterForSpeakers.notifyDataSetChanged();

        }

    public void getToast(String a){
        Toast.makeText(getActivity(),a,Toast.LENGTH_SHORT).show();
    }

//    @Override
    public void sendData(ArrayList<SpeakerInfo> availableSpeakers,Context context) {
       /* int count=-1;
        if(parentOfDockedPlayers!=null){
        count = parentOfDockedPlayers.getChildCount();
        }*/

        int j=0;
        /*if(count>=0){
            j= count;
        }else{
            j=0;
        }*/
        int size = availableSpeakers.size();
        if (size <= 0) {
            getToast("There are no WIFI Speakers detected");
        } else {

            for (int i = 0; i < size; i++,j++) {
                SingleZonePlayerView singleZonePlayerView = new SingleZonePlayerView(context);
                singleZonePlayerView.setSpeakerName(availableSpeakers.get(i).getSpeakerName());
                singleZonePlayerView.setSpeakerIp(availableSpeakers.get(i).getSpeakerIp());
                singleZonePlayerView.setPosition(j);

                parentOfDockedPlayers.addView(singleZonePlayerView);
            }
        }
    }
}

showDialog in button Listview adapter

i have a listView like THIS

enter image description here

i want when i press the delete. it show a dialog like this image

enter image description here

so when i press YES. it will remove from list.

here's my code..

public class customadapter extends BaseAdapter{ 

ArrayList<HashMap<String, String>> oslist;
Context context;
private Button btnDelete;
private Button btnEdit;
AlertDialog.Builder alertDialogBuilder;

public customadapter(ArrayList<HashMap<String, String>> oslist,Context context) {  
    System.out.println("skdjfhksdfjskfjhsdkjfh");
    this.context = context;
    this.oslist = oslist;

}

@Override
public int getCount() {
    // TODO Auto-generated method stub      
    return oslist.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return oslist.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    System.out.println("oslist oslist = "+oslist);
    System.out.println("oslist 1 = "+oslist);
    System.out.println("oslist size = "+oslist.size());
    System.out.println("oslist oslist = "+oslist.getClass());
    System.out.println("position = "+position);
    System.out.println("convertView = "+convertView);
    System.out.println("parent = "+parent);

    System.out.println("position =  "+position);





    LayoutInflater lif = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = lif.inflate(R.layout.listitem, null);

    TextView id = (TextView) convertView.findViewById(R.id.varId);  
    TextView noNota = (TextView) convertView.findViewById(R.id.varNoNota);
    TextView senderName = (TextView) convertView.findViewById(R.id.varSenderName);
    TextView totalAmount = (TextView) convertView.findViewById(R.id.varTotalAmount);

    id.setText(oslist.get(position).get("id"));
    noNota.setText(oslist.get(position).get("noNota"));
    senderName.setText(oslist.get(position).get("senderName"));
    totalAmount.setText(oslist.get(position).get("totalAmount"));   

    Button btnEdit = (Button) convertView.findViewById(R.id.btnEdit);
    Button btnDelete = (Button) convertView.findViewById(R.id.btnDelete);
    btnEdit.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(context, "Edit ditekan!", Toast.LENGTH_LONG).show();
            //I want show YES NO dialog here.           
        }
    });

    btnDelete.setOnClickListener(new OnClickListener() {                
        @Override
        public void onClick(View v) {
            //I want show YES NO dialog here
        }
    });   

    return convertView;
}

}

how can i do to create a dialog like that..i tried this code

final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.custom);
                dialog.setTitle("Title...");

                // set the custom dialog components - text, image and button
                TextView text = (TextView) dialog.findViewById(R.id.text);
                text.setText("Android custom dialog example!");
                ImageView image = (ImageView) dialog.findViewById(R.id.image);
                image.setImageResource(R.drawable.ic_launcher); //line 115

                Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                dialog.show();

but itsnt success.

i got this error

enter image description here

Google Map returning nullpointerexception Google Maps Android V2

I have a google map in a fragment in my application. Funny thing is that the map loads, but the logcat displays a NullPointerException, and I only noticed it when tried to update the camera on the map so that it could automatically zoom in on the marker. Only then the map will crash. Otherwise, the map loads fine in the fragment but with no marker (even though I am adding one using my current gps location).

EDITED*


I understand that its crashing because the googleMap is null, but I don't understand why it's returning null. The map renders and well I've done this before and it usually crashes at that point. Doesn't render.


Here is the logcat error

05-08 01:30:33.143  30130-30130/com.example.javed_000.famjam E/mapApp﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
05-08 01:30:33.152  30130-30130/com.example.javed_000.famjam E/MapFragment﹕ lat = 10.7270913 and Long = -61.5544451
05-08 01:30:33.155  30130-30130/com.example.javed_000.famjam D/AndroidRuntime﹕ Shutting down VM
05-08 01:30:33.156  30130-30130/com.example.javed_000.famjam E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.javed_000.famjam, PID: 30130
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
            at com.example.javed_000.famjam.MapFragment.getLocation(MapFragment.java:60)
            at com.example.javed_000.famjam.MapFragment.onCreateView(MapFragment.java:33)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:488)
            at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
            at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:555)
            at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:514)
            at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:495)
            at com.example.javed_000.famjam.SlidingTabLayout$TabClickListener.onClick(SlidingTabLayout.java:283)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

This is my layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment
    android:id="@+id/mapView"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</RelativeLayout>

Here is my code snippet from the Map Fragment

private void createMapView(){
    try {
        if(googleMap == null){
            SupportMapFragment smf = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapView);
            googleMap = smf.getMap();

            if(googleMap == null) {
                Toast.makeText(getActivity().getBaseContext(),
                        "Error creating map", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (NullPointerException exception){
        Log.e("mapApp", exception.toString());
    }
}

private void getLocation(){
    gps = new GPSTracker(this.getActivity());
    if(gps.CanGetLocation()){
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        Log.e("MapFragment","lat = " + latitude + " and Long = " + longitude);
        addMarker(latitude,longitude);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude), 12));
    } else {
        gps.showSettingsAlert();
    }
}

private void addMarker(double lat, double lng){
    if(googleMap != null){
        googleMap.addMarker(new MarkerOptions()
                        .position(new LatLng(lat, lng))
                        .title("Marker")
                        .draggable(true)
        );
    }
}

Background image dimension for Navigation Drawer header

Basically I liked the background used by Mr. Jonathan Lee for Navigation Drawer header back ground in google official link http://ift.tt/1KMmGtB

So, I wanted to reproduce something similar inspired by that. I believe I need to make similar design in photoshop and set as background. But the question is, what should be the dimensions and pixels so that it matches different kind of devices?

Th above link has guideline for icons and margins, but haven't seen any dimension mentioned for that background.

Anybody has any idea or link that can help?

Eclipse: how to pass parameters do ADB when deploying apk by clicking in "Run" button

I'd like to pass "allow downgrade flag" to adb to bypass INSTALL_FAILED_VERSION_DOWNGRADE error.

I didn't find anything in "Run Configurations".

Smack 4.1 Disbale Auto Receipts

I have just switch to Smack 4.1 from depreciated asmack. Smack 4.1 is automatically sending receipts with wrong id attached which is causing exception in my case.

Smack 4.1 is attaching 2 different id's with receipt

Here is the chat message received

RECV (0): <message from='***' to='***' xml:lang='en' id='65' kind='0' type='chat'><body>vhh</body><request xmlns='urn:xmpp:receipts'/></message>

Here is the received receipt generated by Smack 4.1 in response of chat message

SENT (0): <message to='***' id='roZ7C-32' type='chat'><received xmlns='urn:xmpp:receipts' id='65'/></message>

Smack 4.1 is attaching 2 different ids with Received Receipt id='roZ7C-32' and id='65'

My Question ares :

  1. How can I make these 2 ids same
  2. How can I disable the receipts so that I can generate my custom recipts

How to show a tables rows when an item is clicked Ina listView?

So I am working on an android app, which works with SQLite. I have a table with grade information(_id, category, itemNumber, description, grade, date). From my MainActivity, when I press a button, it takes me to gradeListActivity. This activity has a listView, which shows all the row's category(i.e. Exam, Exam, Homework, Quiz, Lab, Exam. Note I entered in my table three exams, a homework, a quiz and a lab). Upto this point works. Now when I click on an item in the ListView, it takes me to GradeDetailActivity, this is suppose to show all the other colums of the category I selected in the previous activity. My question is how can I achieve that?

SSIM between different image resolutions

I need to compare the quality of streaming between Linux desktop server and an Android client. So I have two images one from Linux server and the other one from Android client and they have different resolution.

My question is how to calculate SSIM between these two images (I do not need CODE just a direction to the solution). I already have SSIM code in c++ but it will compare between similar resolutions.

THANKS

Facebook Android SDK AppEvents not recognizing users on Insights Dashboard

How are you?

We are integrating our App with AppEvents. To do so we are following this guide.

We are first trying to register simple default events after user logs in and interact with the App (ie AppEventsConstants.EVENT_NAME_ADDED_TO_CART). As far as we could see, data is being posted ok (App Id and logged in user Access Token seems to be ok) and we get no errors on the app.

When we enter to Events section on Insights the data we sent is there but the info about the user isn't being processeed. For example, only gender and country filters with "Unknown" return results.

We are using SDK v3.23.1.

Thanks in advance!

Sync Gradle always stops with error

For backward compatibility problem, I need com.google.android:support-v4:r13, but Sync Gradle always comes up with an error:

Error:Could not find com.google.android:support-v4:r13.
Required by:GA:app:unspecified
GA:app:unspecified > com.fizz-buzz:fb-android-dagger:1.0.3

I have in dependencies:

dependencies {
compile files('libs/support-v4-r13.jar')
compile 'com.google.android:support-v4:r13'

and I even have it my libs folder enter image description here

I did an 'Add as library' on it, cleaned the project, but nothing works. What am I doing wrong?

How to point specific to ip in android tablet?

I am accessing my local server by using DNS. For this I have made changes into my etc/hosts of my PC. However I am not able to access it through my andoid devices. Is there any way to do it. Please suggest the method. I have also installed windows server 2012. So please guide me for either way.

get DriveFolder google drive

Please help, I am trying to find out whether there is a folder on the server the following method

I initialize and connect

mGoogleApiClient = new GoogleApiClient.Builder(AMain.this)
.addApi(Fitness.CONFIG_API)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(AMain.this)
.addOnConnectionFailedListener(AMain.this)
.build();

mGoogleApiClient.connect();

connection is established

@Override
public void onConnected(Bundle connectionHint) {
    DriveFolder appFolder = Drive.DriveApi.getAppFolder(mGoogleApiClient);
    DriveFolder myFldr = search(appFolder, "AMain");
}

continue trying to find a folder

private static DriveFolder search(DriveFolder appFolder, String folder) {
    Query query = new Query.Builder().addFilter(Filters.eq(SearchableField.TITLE, folder)).build();
    MetadataBuffer metadataBuffer = appFolder.queryChildren(mGoogleApiClient, query).await().getMetadataBuffer();
    if(metadataBuffer != null&&metadataBuffer.getCount()>0) {
        Log.v("ME","Found "+metadataBuffer.getCount()+" existing folders");
        Metadata metadata = metadataBuffer.get(0);
        if (metadata != null && metadata.isFolder()) {
            Log.v("ME","Returning existing folder");
            return Drive.DriveApi.getFolder(mGoogleApiClient, metadata.getDriveId());
        }else{
            Log.v("ME","Returning created folder even though we found meta data");
            return appFolder.createFolder(mGoogleApiClient, new MetadataChangeSet.Builder().setTitle(folder).build()).await().getDriveFolder();
        }
    }else{
        Log.v("ME","Returning created folder");
        return appFolder.createFolder(mGoogleApiClient, new MetadataChangeSet.Builder().setTitle(folder).build()).await().getDriveFolder();
    }
}

but on the second line getting an error

05-08 17:06:19.261  16538-16538/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: ru.moore.aisuchettehniki, PID: 16538
    java.lang.NullPointerException: Attempt to invoke interface method 'com.google.android.gms.common.api.PendingResult com.google.android.gms.drive.DriveFolder.queryChildren(com.google.android.gms.common.api.GoogleApiClient, com.google.android.gms.drive.query.Query)' on a null object reference
            at ru.moore.aisuchettehniki.AMain.search(AMain.java:147)
            at ru.moore.aisuchettehniki.AMain.onConnected(AMain.java:142)
            at com.google.android.gms.common.internal.zzl.zzj(Unknown Source)
            at com.google.android.gms.common.api.zzd.zzie(Unknown Source)
            at com.google.android.gms.common.api.zzd.zzc(Unknown Source)
            at com.google.android.gms.common.api.zzd$6.onConnected(Unknown Source)
            at com.google.android.gms.common.internal.zzl.zzj(Unknown Source)
            at com.google.android.gms.common.internal.zzl.zzfe(Unknown Source)
            at com.google.android.gms.common.internal.zzk$zzf.zzje(Unknown Source)
            at com.google.android.gms.common.internal.zzk$zza.zzc(Unknown Source)
            at com.google.android.gms.common.internal.zzk$zza.zzi(Unknown Source)
            at com.google.android.gms.common.internal.zzk$zzc.zzjg(Unknown Source)
            at com.google.android.gms.common.internal.zzk$zzb.handleMessage(Unknown Source)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:211)
            at android.app.ActivityThread.main(ActivityThread.java:5321)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)

How can I add a Spinner to RecyclerView

I have followed a tutorial to a navigation drawer to my app, and this works well.

The pattern involves filling the first position of the recyclerview with a header that contains an image and some text views. This is all great, but now I want to add a spinner in there too but am having trouble understanding how to set this up.

The problem is when I create dataAdapter, i get a "cannot resolve constructor". I think it is due to not correctly supplying a Context?

ArrayAdapter<String> dataAdapter =new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);

At this point I am in the ViewHolder class within the Recycler Adapter so "this" isn't an activity. I get that you can use parent.this or activityname.this but this doesn't seem right either (and doesn't work!).

How can I get round the "cannot resolve constructor" error?

Here is the whole onBindViewHolder within my recycler adapter.

@Override
    public void onBindViewHolder(navigationDrawerAdapter.ViewHolder holder, int position) {
        if(holder.HolderID ==1) {                         
            holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
            holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
        }
        else{
            holder.imageProfile.setImageResource(profile);
            holder.textName.setText(name);
            holder.textEmail.setText(email);


            List<String> list = new ArrayList<String>();
            list.add("TEST");

            ArrayAdapter<String> dataAdapter =new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);

dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            holder.siteSpinner = (Spinner) findViewById(R.id.siteSpinner);

            holder.siteSpinner.setAdapter(dataAdapter);


        }
    }

Alternatively, is this the right approach? I wonder if creating a "header" in position one is a good way to go? Could an alternative be to create a linear layout for my navigation drawer which has the spinner and recyclerview one after the other?

calling invalidateOptionsMenu() causes SearchView to stop working

I am working with a DrawerLayout and I am using invalidateOptionsMenu() whenever it is opened or closed. The trouble is that after opening and closing the DrawerLayout the SearchView stops working.

Class1:

private DrawerLayout DrawerLayout;
private ListView DrawerList;
private ActionBarDrawerToggle DrawerToggle;
private CharSequence DrawerTitle;
private CharSequence Title;
.....

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
        R.drawable.menu, R.string.app_name, R.string.hello) {
    public void onDrawerClosed(View view) {
        getActionBar().setTitle(Title);
        invalidateOptionsMenu(); 
        // onPrepareOptionsMenu()
    }

    public void onDrawerOpened(View drawerView) {
        getActionBar().setTitle(DrawerTitle);
        invalidateOptionsMenu(); 
        // onPrepareOptionsMenu()
    }
};

mDrawerLayout.setDrawerListener(DrawerToggle);

SearchView defined Class2:

@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    getActivity().invalidateOptionsMenu();
    // onPrepareOptionsMenu()
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.actionbar, menu);
    searchView = (SearchView) menu.findItem(R.id.search).getActionView();
}

Neither class defines onPrepareOptionsMenu()

Specifically this is what stops working:

@Override
public boolean onQueryTextChange(String newText) {
   adapter.getFilter().filter(newText);
    return false;
}

Where adapter is the adapter for a ListView and getFilter goes to a baseadapter class which implements filterable.

view website running on local machine via android

I have a webservice in c# ,I want to access it via my android device through adhoc , I am able to get it in emulator using 10.0.2.2; but can't see on android device, Kindly suggest me any method to access that.

This is online webservice on w3school i am able to access it via my android device

  private final String NAMESPACE = "http://ift.tt/19UVeq5";
  private final String URL =     "http://ift.tt/16d0ByF";
  private final String SOAP_ACTION = "http://ift.tt/19UVc1e";
 private final String METHOD_NAME = "CelsiusToFahrenheit"; 

This is url of my local webservice http://localhost:63693/Notif.asmx unable to access via android phone , though in emultor it is working http://ift.tt/1IV4UFJ

slf4j library not working correctly

I am using the sardine library to put a file onto a WebDav server. I have sardine-5.4.jar in my libs folder. When I run the project I get in the logcat:

05-07 16:31:52.576: W/System.err(25875): SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
05-07 16:31:52.576: W/System.err(25875): SLF4J: See http://ift.tt/19pvuRr for further details.

So I follow the link and download slf4j-simple.jar, and add it to my project and get this;

[2015-05-07 16:34:14 - Dex Loader] Unable to execute dex: Multiple dex files define Lorg/slf4j/ILoggerFactory;
[2015-05-07 16:34:14 - IncabAndroid] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lorg/slf4j/ILoggerFactory;

Please could someone show me how to correctly implement the use of Sardine.

I am only trying to do this chuck of code;

Sardine sardine = SardineFactory.begin("username", "password");

byte[] data;
try {
    byte[] bFile = new byte[(int) myExternalFile2.length()];
    //convert file into array of bytes
    FileInputStream fileInputStream=null;
    fileInputStream = new FileInputStream(myExternalFile2);
    fileInputStream.read(bFile);
    fileInputStream.close();
    //data = FileUtils.readFileToByteArray(myExternalFile2);
    sardine.put("http://ift.tt/1KlX8Tv"+sdDirList[0].toString(), bFile);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I have in my libs;

android-support-v4.jar
core-3.2.0.jar
fluent-hc-4.4.1.jar
httpclient-4.4.1.jar
httpcore-4.4.1.jar
httpmime-4.4.1.jar
jackrabbit-webdav-2.2.6-with-dependencies.jar
jcifs-1.3.18.jar
nlog4j-1.2.25.jar
sardine-5.4.jar

Call ActionBar-PullToRefresh.SetRefreshComplete from WebviewClient declared in another class

I have implemented Chris Banes ActionBar-PullToRefresh which is working, however when I refresh a page for a second time the load bar gets stuck on.

I have found I need to use the following line in order to stop it:

mPullToRefreshLayout.setRefreshComplete();

The problem is my WebViewClient is not created in the Fragment I'm using, but is instead in its own class in use by multiple fragments. Putting That line in the onPageFinished of my WebViewClient does not work as it does not know the mPullToRefreshLayout exists.

I was wondering if there is any way of making this call work?

Many thanks.

Value

I am sending json from servlet to android application , and the following exception occurs : -

 org.json.JSONException: Value <html><head><title>Apache of type java.lang.String cannot be converted to JSONObject

Following is my servlet code , please correct me if anything is wrong here :-

public class LoginCheck extends HttpServlet {

  protected void processRequest(HttpServletRequest request,  HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");
    PrintWriter out = response.getWriter();


    JSONObject obj1 = new JSONObject();

    long uname =Long.parseLong(request.getParameter("mobile"));
    String pwd = request.getParameter("pass");

    try  {
    Connection con = new MyConnection().connect();
    PreparedStatement ps = con.prepareStatement("select * from bmt_user  where mobile_num=? and password=?");
    ps.setLong(1,uname);
    ps.setString(2,pwd);

     ResultSet rs=ps.executeQuery();

        if(rs.next())
       {
            obj1.accumulate("login","Success");
            out.println(obj1.toString());

       }

        else
        {
            obj1.accumulate("login","Fail");
            out.println(obj1.toString());
        }
       out.write(obj1.toString());     
    }catch(Exception e){out.println(e.toString());}
  }


  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
     processRequest(request, response);
   }

   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
     processRequest(request, response);
  }

 }

Plus , when i assign the values to uname and pwd directly , without using request.getParameter() , the servlet runs just fine and returns json i.e

long uname = 48372984;
String pwd = "fabcd"

output -

{"login":"Fail"}

Cannot assign variable value to a string from extra.getString();

New to android, I'm currently trying to send a string value from one activity to another. I have looked through several threads like How to use putExtra() and getExtra() for string data for an answer, but I cannot get it to work.

The string I want to send is:

public void golf(View view)  {
    Intent intent = new Intent(SearchSport.this, EventList.class);
    intent.putExtra("Type", "golf");
    startActivity(intent);

and my receiver looks like

String type;

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

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if ( extras != null)
        type = extras.getString("type");

    if (type == "golf"){
        TextView eventName      = (TextView) findViewById(R.id.EOName);
        TextView eventTime      = (TextView) findViewById(R.id.EOTime);
        TextView eventLocation  = (TextView) findViewById(R.id.EOLocation);

        DatabaseOperations dop = new DatabaseOperations(ctx);
        Cursor CR = dop.getInformation(1);
        CR.moveToFirst();

        eventName.setText(CR.getString(1));
        eventTime.setText(CR.getString(7) + " " + CR.getString(8) + ". " + CR.getString(9) + " kl. " + CR.getString(10) + ":" + CR.getString(11));
        eventLocation.setText(CR.getString(4));}

    else {Toast toast = Toast.makeText(this, "Error in Type.", Toast.LENGTH_LONG);
                toast.show();}

I have no Idea what's wrong here.

Beginner in Android Studio

Hi I have recently moved from VB onto Android studio for a new challenge and I'm currently teaching myself and learning where everything is. This might be bit of a simple question but when I create a new project then attempt to drag a widget onto the device e.g. Medium text it will display it on the relative layout and display it when debugging but will not display it on the static phone before debugging. Being a person from VB I'm simply use to dragging e.g. a label onto the form and instantly see it on the form ready for editing and moving it into position before debugging.

Thanks Hadleigh

Change tab indicator color in actionbar

I know this question was asked many times before, but I tried all solutions and nothing is working. So I've decided to follow official documentation: http://ift.tt/18bHaHW

I've made file themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
        parent="@android:style/Theme.Holo.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabs</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
        parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/actionbar_background</item>
    </style>

    <!-- ActionBar tabs styles -->
    <style name="MyActionBarTabs"
        parent="@android:style/Widget.Holo.ActionBar.TabView">
        <!-- tab indicator -->
        <item name="android:background">@drawable/actionbar_tab_indicator</item>
    </style>
</resources>

actionbar_background is just simple shape with solid fill and it's working.
However indicator is still blue:
actionbar_tab_indicator - this is file generated from http://ift.tt/1cN4rFd I've also copy-pasted generated images to drawable folder. First issue was 9-patch files were somehow wrong, but I've managed to manually fix them.

I'm setting theme in AndroidManifest.xml: android:theme="@style/CustomActionBarTheme"

I've also tried solutions for changing color programatically, but it doesn't work as intended. Instead of being small rectangle it's stretched to fit whole tab.

Any solution (programatically or in xml) working in latest android studio will be great. But it must look just like the orginal tab, but with other color - in my case red.

Regards

How to use the token obtained from GoogleAuthUtil with Web API 2 default template project

My intent is to authenticate using Google and once authenticated access my resource server (written in Web API 2).

I am able to get the authentication token from Google for the ClientID that I have created in Google's developer console. Here is the code that does it (courtesy: http://ift.tt/1F7hdwa):

private class RetrieveIdTokenTask extends AsyncTask<String, Void, String>  {
    protected String doInBackground(String... params) {
        String account = params[0];
        String homeServerClient = "276706532100-mygoogleclient.apps.googleusercontent.com";
        try {
            String scope = "audience:server:client_id:" + homeServerClient;
            final String token = GoogleAuthUtil.getToken(LoginActivity.this, account, scope);
            return token;
        } catch (GooglePlayServicesAvailabilityException playEx) {
            // In this case you could prompt the user to upgrade.
        } catch (UserRecoverableAuthException userAuthEx) {
            // This should not occur for ID tokens.
        } catch (IOException transientEx) {
            // You could retry in this case.
        } catch (GoogleAuthException authEx) {
            // General auth error.
        }
        return null;
    }

    protected void onPostExecute(String result){
        Log.d("Token", result);
    }
}



@Override
public void onConnected(Bundle bundle) {
    // get the email address
    Person currentPerson = Plus.PeopleApi
            .getCurrentPerson(mGoogleApiClient);
    String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
    new RetrieveIdTokenTask().execute(email);

}

So far so good, but here is the issue:

Once I got the token I used it in fiddler to send it to the ValuesController. The ValuesController in default template has [Authorize] attribute and I was thinking that following should authorize the request:

  1. Uncommenting following lines and adding the missing details in Startup.Auth.cs.

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "276706532100-mygoogleclient.apps.googleusercontent.com",
            ClientSecret = "nbQjjRnivx1hjmQnkuBEbhbj"
        });
    
    
  2. Sending the token in HTTP request as "authorization" header

But it didn't work and I keep on getting 401 (Unauthorized). Here is how my fiddler request looks like:

**URL :** 
http://localhost:60864/api/values/

**Header section:**
User-Agent: Fiddler
authorization: bearer eyJhbGc...REMOVED FOR BREVITY..iOiJSUzI1NiIsIzuhlgIE-ZC5mlmyNnpXEOP2qplbYCmw
content-type: application/json
Host: localhost:60864

Any idea, what is it that I am missing? I am getting a feeling that either I am so close and missing one last little step, or, I have got it all wrong :)

Help!

java.lang.IllegalStateException: RecyclerView has no LayoutManager

I am getting below exception-

Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
            at android.support.v7.widget.RecyclerView.generateLayoutParams(RecyclerView.java:2820)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:757)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at com.peoplecloud.app.guggu.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:75)
            at android.app.Fragment.performCreateView(Fragment.java:1700)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:866)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
            at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1142)
            at android.app.Activity.onCreateView(Activity.java:4803)

I have added the following code,however i am still getting this exception-

 LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mDrawerList.setLayoutManager(layoutManager);

If I remove the content inside recycler view then there is no exception.

Below is detailed code-

xml

<android.support.v7.widget.RecyclerView android:id="@+id/drawerList"
    xmlns:android="http://ift.tt/nIICcg" android:layout_width="match_parent"
    android:clickable="true" android:scrollbars="vertical"

    android:layout_height="match_parent" android:background="@color/myDrawerBackground" >
    <RelativeLayout
        android:id="@+id/drawer_Linearlayout"
        android:layout_width="340dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        >
        <ImageView
            android:id="@+id/backgroundView"
            android:layout_width="match_parent"
            android:layout_height="340dp"
            android:layout_alignParentTop="true"/>
        <ImageView
            android:layout_width="135dp"
            android:layout_height="135dp"

            android:layout_marginTop="40dp"
            android:layout_gravity="center_horizontal"
            android:layout_centerHorizontal="true"
            android:id="@+id/circleView"

            />
        <ImageView
            android:id="@+id/faceboolUserProfilePicture"
            android:layout_height="130dp"
            android:layout_width="130dp"


            android:layout_marginTop="20dp"
            android:layout_gravity="center_horizontal"
            android:layout_centerHorizontal="true"
            android:visibility="gone"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_gravity="center_horizontal"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/circleView"
            android:textSize="30dp"
            android:id="@+id/userName"/>
        <ListView android:id="@+id/left_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:paddingTop="20dp"
            android:layout_below="@+id/userName"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="20dp"
            android:background="@drawable/list_bg"/>
    </RelativeLayout>
    </android.support.v7.widget.RecyclerView>

NavigationDrawerFragment.java

public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private NavigationDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mActionBarDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private RecyclerView mDrawerList;
    private View mFragmentContainerView;

    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_DRAWER for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
        mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDrawerList.setLayoutManager(layoutManager);
        mDrawerList.setHasFixedSize(true);

        final List<NavigationItem> navigationItems = getMenu();
        NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
        adapter.setNavigationDrawerCallbacks(this);
        mDrawerList.setAdapter(adapter);
        selectItem(mCurrentSelectedPosition);
        return view;
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    public ActionBarDrawerToggle getActionBarDrawerToggle() {
        return mActionBarDrawerToggle;
    }

    public DrawerLayout getDrawerLayout() {
        return mDrawerLayout;
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        selectItem(position);
    }

    public List<NavigationItem> getMenu() {
        List<NavigationItem> items = new ArrayList<NavigationItem>();
        items.add(new NavigationItem("item 1", getResources().getDrawable(R.drawable.ic_menu_check)));
        items.add(new NavigationItem("item 2", getResources().getDrawable(R.drawable.ic_menu_check)));
        items.add(new NavigationItem("item 3", getResources().getDrawable(R.drawable.ic_menu_check)));
        return items;
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     * @param toolbar      The Toolbar of the activity.
     */
    public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));

        mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) return;

                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) return;
                if (!mUserLearnedDrawer) {
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }
                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
        // per the navigation drawer design guidelines.
        if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
            mDrawerLayout.openDrawer(mFragmentContainerView);
        }

        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mActionBarDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
    }

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
        ((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
    }

    public void openDrawer() {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    public void closeDrawer() {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mActionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

}

Image slide not working good when viewpager and imageview in the same xml

I am doing a slide view , and by mistake I have added the pageview and ViewPager in same xml and that caused problems , when I tried to fix it the slide stoped working , so I need help to make the slide working.( In this tutorials 1 and 2 explained the viewpage should be in another xml but honestly I didnt understand why .

This is SingleViewActivity.java

public class SingleViewActivity extends Activity {
    private ImageView image1;
    ViewPager viewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_view);
//
        slide mCustomPagerAdapter = new slide(this);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPager.setAdapter(mCustomPagerAdapter);
}}

and this is slide.java

public class slide extends PagerAdapter{
    Context mContext;
    LayoutInflater mLayoutInflater;

    public slide(Context context) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mThumbIds.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = mLayoutInflater.inflate(R.layout.activity_main, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.SingleView);
        imageView.setImageResource(mThumbIds[position]);

        container.addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
    public Integer[] mThumbIds =
        { 
                R.drawable.sample2, 
                R.drawable.sample2,
                R.drawable.sample2,
                R.drawable.sample2,
                R.drawable.sample2,
                R.drawable.sample2,
                R.drawable.sample2,
                R.drawable.sample2
         }; 
}

Single view.xml

<ImageView android:id="@+id/SingleView" 
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_below="@id/edittextm"/>

 <android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

As I understand view pager should be in another xml , please note that I want the images to slide in SingleViewactivity.