Affichage des articles dont le libellé est Active questions tagged android - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged android - Stack Overflow. Afficher tous les articles

samedi 27 juin 2015

Creating Vertical ScrollView inside ViewPager

I am trying to add a scrollView inside my ViewPager so I can scroll left and right as well as down if the page becomes full. As of now, I am dynamically adding views to my ViewPager:

Fragment Page in ViewPager:

ScrollView is not being inserted since i must remove the parent view.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    mainView = View.inflate(getActivity(), R.layout.fragment_profile_personal_records, null);
    LinearLayout mainLayout = (LinearLayout) mainView.findViewById(R.id.layoutPR);
    ScrollView scrollView = new ScrollView(getActivity());
    scrollView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    for(int i = 0; i < 3; i++){
        LinearLayout rowLayout = (LinearLayout) mainView.inflate(getActivity(), R.layout.row_personal_records, null);
        mainLayout.addView(rowLayout);
    }
    scrollView.addView(mainLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    return scrollView;
}

XML for Fragment:`

    <LinearLayout
    xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutPR"
    android:orientation="vertical"
    tools:context="test.test.test.fragment">
</LinearLayout>

Container that contains viewPager:

   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_below="@id/mainLayout">

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/vpPager"
        android:scrollbars="vertical">

        <android.support.v4.view.PagerTabStrip
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/pagerHeader"
            android:layout_gravity="top"
            android:paddingBottom="5dp"
            android:textColor="#000000"
            android:paddingTop="5dp">
        </android.support.v4.view.PagerTabStrip>

    </android.support.v4.view.ViewPager>

</LinearLayout>

I have looked on the internet for answers but haven't come across anything that will insert a vertical scrollbar inside a viewPager that the view inside is created dynamically/programitcally and without xml

Crosswalk 14 - orientation is not changing

In my app build on crosswalk 14 and ionic there is no orientation change. if You rotate device - no change. My congif.xml file

<?xml version='1.0' encoding='utf-8'?>
<widget id="pl.polskieszlaki.PolskieSzlaki" android-versionCode="6" version="2.0.1"  android-installLocation="preferExternal" xmlns="http://ift.tt/18Fk3Vk" xmlns:cdv="http://ift.tt/1cHnIYX">
    <name>Polskie Szlaki</name>
    <description>Flagowa aplikacja portalu PolskieSzlaki.pl. Znajdziesz tutaj opisy tysięcy atrakcji z całej Polski
    </description>
    <author email="biuro@polskieszlaki.pl" href="http://ift.tt/1Il40m5">Łukasz Piernikarczyk</author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" version="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <preference name="SplashScreen" value="screen"/>
    <preference name="SplashScreenDelay" value="3000"/>
    <preference name="android-minSdkVersion" value="17"/>
    <preference name="android-targetSdkVersion" value="19"/>
    <preference name="xwalkVersion" value="14" />
    <preference name="Orientation" value="default" />
    <platform name="android">
        <icon src="resources\android\icon\drawable-ldpi-icon.png" density="ldpi"/>
        <icon src="resources\android\icon\drawable-mdpi-icon.png" density="mdpi"/>
        <icon src="resources\android\icon\drawable-hdpi-icon.png" density="hdpi"/>
        <icon src="resources\android\icon\drawable-xhdpi-icon.png" density="xhdpi"/>
        <icon src="resources\android\icon\drawable-xxhdpi-icon.png" density="xxhdpi"/>
        <icon src="resources\android\icon\drawable-xxxhdpi-icon.png" density="xxxhdpi"/>
        <splash src="resources\android\splash\drawable-land-ldpi-screen.png" density="land-ldpi"/>
        <splash src="resources\android\splash\drawable-land-mdpi-screen.png" density="land-mdpi"/>
        <splash src="resources\android\splash\drawable-land-hdpi-screen.png" density="land-hdpi"/>
        <splash src="resources\android\splash\drawable-land-xhdpi-screen.png" density="land-xhdpi"/>
        <splash src="resources\android\splash\drawable-land-xxhdpi-screen.png" density="land-xxhdpi"/>
        <splash src="resources\android\splash\drawable-land-xxxhdpi-screen.png" density="land-xxxhdpi"/>
        <splash src="resources\android\splash\drawable-port-ldpi-screen.png" density="port-ldpi"/>
        <splash src="resources\android\splash\drawable-port-mdpi-screen.png" density="port-mdpi"/>
        <splash src="resources\android\splash\drawable-port-hdpi-screen.png" density="port-hdpi"/>
        <splash src="resources\android\splash\drawable-port-xhdpi-screen.png" density="port-xhdpi"/>
        <splash src="resources\android\splash\drawable-port-xxhdpi-screen.png" density="port-xxhdpi"/>
        <splash src="resources\android\splash\drawable-port-xxxhdpi-screen.png" density="port-xxxhdpi"/>
    </platform>
    <icon src="resources\android\icon\drawable-xhdpi-icon.png"/>
</widget>

And AndroidManifest.xml

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:installLocation="preferExternal" android:versionCode="6" android:versionName="2.0.1" package="pl.polskieszlaki.PolskieSzlaki" xmlns:android="http://ift.tt/nIICcg">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyBINjjNZBV2_yrk_L6vJfmLYshvzdXMBO4" />
        <activity android:name="com.keyes.youtube.OpenYouTubePlayerActivity" android:screenOrientation="landscape" />
    </application>
    <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:glEsVersion="0x00020000" android:required="true" />
</manifest>

Without crosswalk everything works great.

My codrova plugins:

com.bunkerpalace.cordova.YoutubeVideoPlayer 1.0.1 "CordovaYoutubeVideoPlayer"
com.google.playservices 19.0.0 "Google Play Services for Android"
cordova-plugin-crosswalk-webview 1.2.0 "Crosswalk WebView Engine"
cordova-plugin-google-analytics 0.7.2 "Google Universal Analytics Plugin"
cordova-plugin-splashscreen 2.1.0 "Splashscreen"
cordova-plugin-whitelist 1.0.0 "Whitelist"
nl.x-services.plugins.socialsharing 4.3.19-dev "SocialSharing"
nl.x-services.plugins.toast 2.1.1 "Toast"
org.apache.cordova.dialogs 0.3.0 "Notification"
org.apache.cordova.geolocation 0.3.12 "Geolocation"
org.apache.cordova.globalization 0.3.4 "Globalization"
org.apache.cordova.inappbrowser 0.6.0 "InAppBrowser"
org.apache.cordova.network-information 0.2.15 "Network Information"
org.pushandplay.cordova.apprate 1.1.7 "AppRate"
plugin.google.maps 1.2.5 "phonegap-googlemaps-plugin"
plugin.http.request 1.0.4 "phonegap-http-request"

App crashes on orientation change after I change my listview in same activity

My app starts in the MainActivity and uses a loader and custom adapter to populate my listview with the users' favourites. The data will persist over the orientation change.

But then if the user performs a search the listview in the MainActivity is repopulated with the new data. That works fine. But now, an orientation change crashes my app.

I'm also confused whether I have to explicitly save my instance before an orientation change or if Android does it for me. And if I have to do it explicitly would it be better to just perform the database query again instead?

package must.beunique.recipebook;

import java.io.File;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.CursorAdapter;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
import android.widget.SearchView;
import android.util.Log;

public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private CursorAdapter dataAdapter;
    private String query = null;

    private static final String DATABASE_PATH = "/data/data/must.beunique.recipebook/databases/RECIPES";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.w("DEBUG", "MainActivity - onCreate()");
        super.onCreate(savedInstanceState);

        setContentView(R.layout.query_results);     



            File database = this.getDatabasePath(DATABASE_PATH);
            if (database.exists()) {    


                // Get the intent, verify the action and get the query
                Intent intent = getIntent();
                Bundle extras = intent.getExtras();

                // search query in intent
                if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
                    query = intent.getStringExtra(SearchManager.QUERY);
                }         
                // browse all...
                else if(extras!=null){
                    if(extras.containsKey("browse")){
                        query = "";
                    }
                }                                           

                Log.w("DEBUG", "starting adapter");
                int[] to = new int[] { R.id.text1 };
                String[] columns = new String[]{ "name" };
                dataAdapter = new CustomAdapter(this, R.layout.text_view, null, columns, to, Adapter.NO_SELECTION);
                ListView listView = (ListView) findViewById(android.R.id.list);
                listView.setAdapter(dataAdapter);

                Log.w("DEBUG", "listView.setAdapter(dataAdapter)");
                listView.setOnItemClickListener(new OnItemClickListener()
                {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View view,
                            int position, long id) {
                        Intent intent = new Intent(getBaseContext(), Recipe.class);
                        intent.putExtra("must.beunique.recipebook._id", (int)id);
                        startActivity(intent);
                    }   
                }       );
                Log.w("DEBUG", "end adapter");
                getSupportLoaderManager().initLoader(0, null, this);

            }
            else{
                new SyncRecipes(this).execute(); 
            } 

        Log.w("DEBUG", "end onCreate()");
    }

    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        Log.w("DEBUG", "onCreateLoader()");
        if(query==""){
            // empty search, return all
            return new CursorLoader(this, Uri.parse("content://must.beunique.recipebook.data/"+DataProvider.BRW), null, null, null, null);          
        }
        else if(query == null){
            return new CursorLoader(this, Uri.parse("content://must.beunique.recipebook.data/"+DataProvider.FAV), null, null, null, null);
        }
        else{
            // term search, return relevant
            return new CursorLoader(this, Uri.parse("content://must.beunique.recipebook.data/"+DataProvider.TRM+"/"+query), null, null, null, null);
        }
    }

    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        Log.w("DEBUG", "onLoadFinished()");
        dataAdapter.swapCursor(cursor);
    }

    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        dataAdapter.swapCursor(null);
    }

    protected void onDestroy(Bundle savedInstanceState) {
        super.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle InstanceState) {
        super.onSaveInstanceState(InstanceState);
        InstanceState.putString("query", query);
        dataAdapter.swapCursor(null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
         // Associate searchable configuration with the SearchView
        SearchManager searchManager =
               (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
        Log.w("DEBUG", "end - onCreateOptionsMenu()");
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        Log.w("DEBUG", "onPrepareOptionsMenu()");
            menu.findItem(R.id.favourite).setVisible(false);
            menu.findItem(R.id.favourite).setEnabled(false);
            menu.findItem(android.R.id.home).setVisible(true);
            menu.findItem(android.R.id.home).setEnabled(true);
        Log.w("DEBUG", "end - onPrepareOptionsMenu()");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case android.R.id.home:            
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);            
                return true; 
            case R.id.search:
                onSearchRequested();
                return true;
            case R.id.browse:
                Intent bintent = new Intent(this, MainActivity.class);
                bintent.putExtra("browse", true);
                startActivity(bintent);;
                return true;            
            case R.id.sync:
                new SyncRecipes(this).execute();
                return true;
            case R.id.rebuild:
                Boolean Qdeleted = this.deleteDatabase(DATABASE_PATH);
                new SyncRecipes(this).execute();
                return true;                                
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

I can't interpret the logcat

06-27 22:15:52.421: W/DEBUG(29310): MainActivity - onCreate()
06-27 22:15:52.531: D/AbsListView(29310): Get MotionRecognitionManager
06-27 22:15:52.551: W/DEBUG(29310): starting adapter
06-27 22:15:52.556: W/DEBUG(29310): listView.setAdapter(dataAdapter)
06-27 22:15:52.556: W/DEBUG(29310): end adapter
06-27 22:15:52.561: W/DEBUG(29310): onCreateLoader()
06-27 22:15:52.566: W/DEBUG(29310): end onCreate()
06-27 22:15:52.691: D/libEGL(29310): loaded /system/lib/egl/libEGL_mali.so
06-27 22:15:52.696: D/libEGL(29310): loaded /system/lib/egl/libGLESv1_CM_mali.so
06-27 22:15:52.701: D/libEGL(29310): loaded /system/lib/egl/libGLESv2_mali.so
06-27 22:15:52.706: E/(29310): Device driver API match
06-27 22:15:52.706: E/(29310): Device driver API version: 23
06-27 22:15:52.706: E/(29310): User space API version: 23 
06-27 22:15:52.706: E/(29310): mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Fri Mar 21 13:52:50 KST 2014 
06-27 22:15:52.771: D/OpenGLRenderer(29310): Enabling debug mode 0
06-27 22:15:52.781: W/DEBUG(29310): onCreateOptionsMenu()
06-27 22:15:52.816: W/DEBUG(29310): end - onCreateOptionsMenu()
06-27 22:15:52.816: W/DEBUG(29310): onPrepareOptionsMenu()
06-27 22:15:52.816: W/DEBUG(29310): end - onPrepareOptionsMenu()
06-27 22:15:52.856: W/DEBUG(29310): onLoadFinished()
06-27 22:15:52.856: W/DEBUG(29310): end - onLoadFinished()
06-27 22:15:56.846: D/AbsListView(29310): Get MotionRecognitionManager
06-27 22:15:58.281: D/AbsListView(29310): onDetachedFromWindow
06-27 22:15:58.291: W/DEBUG(29310): MainActivity - onCreate()
06-27 22:15:58.346: D/AbsListView(29310): Get MotionRecognitionManager
06-27 22:15:58.351: W/DEBUG(29310): starting adapter
06-27 22:15:58.351: W/DEBUG(29310): listView.setAdapter(dataAdapter)
06-27 22:15:58.351: W/DEBUG(29310): end adapter
06-27 22:15:58.351: W/DEBUG(29310): onCreateLoader()
06-27 22:15:58.351: W/DEBUG(29310): end onCreate()
06-27 22:15:58.486: W/DEBUG(29310): onCreateOptionsMenu()
06-27 22:15:58.516: W/DEBUG(29310): end - onCreateOptionsMenu()
06-27 22:15:58.516: W/DEBUG(29310): onPrepareOptionsMenu()
06-27 22:15:58.516: W/DEBUG(29310): end - onPrepareOptionsMenu()
06-27 22:15:58.746: W/DEBUG(29310): onLoadFinished()
06-27 22:15:58.746: W/DEBUG(29310): end - onLoadFinished()
06-27 22:15:58.981: W/DEBUG(29310): onSaveInstanceState()
06-27 22:16:00.846: W/DEBUG(29310): onSaveInstanceState()
06-27 22:16:00.856: D/AbsListView(29310): onDetachedFromWindow
06-27 22:16:01.101: W/DEBUG(29310): MainActivity - onCreate()
06-27 22:16:01.166: D/AbsListView(29310): Get MotionRecognitionManager
06-27 22:16:01.171: W/DEBUG(29310): starting adapter
06-27 22:16:01.171: W/DEBUG(29310): listView.setAdapter(dataAdapter)
06-27 22:16:01.171: W/DEBUG(29310): end adapter
06-27 22:16:01.171: W/DEBUG(29310): end onCreate()
06-27 22:16:01.171: W/DEBUG(29310): onLoadFinished()
06-27 22:16:01.171: W/DEBUG(29310): end - onLoadFinished()
06-27 22:16:01.221: D/AndroidRuntime(29310): Shutting down VM
06-27 22:16:01.221: W/dalvikvm(29310): threadid=1: thread exiting with uncaught exception (group=0x418b4c08)
06-27 22:16:01.231: E/AndroidRuntime(29310): FATAL EXCEPTION: main
06-27 22:16:01.231: E/AndroidRuntime(29310): Process: must.beunique.recipebook, PID: 29310
06-27 22:16:01.231: E/AndroidRuntime(29310): android.view.InflateException: Binary XML file line #31: Error inflating class <unknown>
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.LayoutInflater.createView(LayoutInflater.java:626)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at com.android.internal.widget.ActionBarContextView.initClose(ActionBarContextView.java:330)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at com.android.internal.widget.ActionBarContextView.onConfigurationChanged(ActionBarContextView.java:185)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.View.dispatchConfigurationChanged(View.java:8599)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.ViewGroup.dispatchConfigurationChanged(ViewGroup.java:1105)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.ViewGroup.dispatchConfigurationChanged(ViewGroup.java:1110)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.ViewGroup.dispatchConfigurationChanged(ViewGroup.java:1110)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.ViewGroup.dispatchConfigurationChanged(ViewGroup.java:1110)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.ViewRootImpl.updateConfiguration(ViewRootImpl.java:3441)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3612)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.os.Handler.dispatchMessage(Handler.java:102)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.os.Looper.loop(Looper.java:146)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.app.ActivityThread.main(ActivityThread.java:5593)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at java.lang.reflect.Method.invokeNative(Native Method)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at java.lang.reflect.Method.invoke(Method.java:515)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at dalvik.system.NativeStart.main(Native Method)
06-27 22:16:01.231: E/AndroidRuntime(29310): Caused by: java.lang.reflect.InvocationTargetException
06-27 22:16:01.231: E/AndroidRuntime(29310):    at java.lang.reflect.Constructor.constructNative(Native Method)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.view.LayoutInflater.createView(LayoutInflater.java:600)
06-27 22:16:01.231: E/AndroidRuntime(29310):    ... 23 more
06-27 22:16:01.231: E/AndroidRuntime(29310): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=24; index=27
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.content.res.StringBlock.get(StringBlock.java:65)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.content.res.XmlBlock$Parser.getPooledString(XmlBlock.java:459)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.content.res.TypedArray.loadStringValueAt(TypedArray.java:721)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.content.res.TypedArray.getString(TypedArray.java:125)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.widget.TextView.<init>(TextView.java:1509)
06-27 22:16:01.231: E/AndroidRuntime(29310):    at android.widget.TextView.<init>(TextView.java:908)
06-27 22:16:01.231: E/AndroidRuntime(29310):    ... 26 more

LAYOUT XML's

query_results.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    style = "@style/Activity"
>   
    <ListView 
        android:id="@android:id/list"
        style = "@style/ListView"       
    />          

</LinearLayout>

text_view.xml

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

    <TextView 
         style = "@style/Item"
         android:id="@+id/text1"
         android:hint="@string/no_recipes" 
         android:maxLines="1"    /> 

</LinearLayout>

Is it possible to change the color/style of a single day in an Android calendar view?

I have seen a few other questions but they are either old or unanswered.

Add event to Week view library

I'm using this library : http://ift.tt/1rtrYBv And I want that when I click on an empty space, an event will show up on the calendar, but it doesnt..The event is added to events variable. but you cant see it in the calendar
here is my code:

      List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();


   mWeekView.setEmptyViewClickListener(new WeekView.EmptyViewClickListener() {
            @Override
            public void onEmptyViewClicked(Calendar calendar) {

                Calendar cal2 = (Calendar) calendar.clone();
                cal2.add(Calendar.HOUR, 1);
                WeekViewEvent event = new WeekViewEvent(1,"Hello", calendar, cal2);
                event.setColor(getActivity().getResources().getColor(R.color.event_color_01));
                events.add(event);

                events.add(event);
                onMonthChange(2015,5);
            }
        });


 @Override
    public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) {
    return events;
}

Getting back object from child activiy in Android

I have a main_activity that starts a child Activity via Intent.

I know about methods getStringExtra(string), or getBooleanExtra(string) etc. that we call in onActivityResult; But they all return a primitive data... How can I get an object from a user-defined class from the child activity?

Thanks, and this is my first question here! :) kinda too late...

OnItemSelect Spinner Duplicating a Record in Android

strong text

Can any one tell me Why my Record is duplicating on per item selected in Android Spinner..

OnCreate() method

path_spinner = (Spinner) findViewById(R.id.spinner_path);
        path_spinner.post(new Runnable() {
            @Override
            public void run() {

                path_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                        if (path_spinner.getSelectedItemPosition() > 0) {
                            getitemno = path_spinner.getSelectedItemPosition();
                            getposition = getitemno;

                            new AlgoApiNetCheck().execute();

                            if (path_spinner!=null && path_spinner.getSelectedItemPosition()==0)
                            {
                                new AlgoApiNetCheck().execute();
                            }

                            Log.d("Item Position", String.valueOf(getitemno));
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }
        });

Async Class OnPostMethod

 if (!check) {
            adapter = new ArrayAdapter<String>(MapLocationActivity.this,
                    android.R.layout.simple_spinner_item, get_path);
            Log.d("Counter", get_path.toString());
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            path_spinner.setAdapter(adapter);
        }

How to prevent My Spinner to stop a Duplicating My Record

Toolbar back arrow show as black color on 4.x devices

I have used Toolbar and used design library.The toolbar navigation icon and back arrow icon display as white on Android 5.0 device.But on Android 4.x devices it display as black color icons.How to diaplay the icons as white color on both Android 5.0 and Android 4.x devices.

MainActivity.java

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

    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);


    final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

    upArrow.setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_ATOP);

    toolbar.setNavigationIcon(upArrow);

    setSupportActionBar(toolbar);

    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,toolbar, R.string.app_name, R.string.app_name){

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            fab1.setVisibility(View.VISIBLE);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            fab1.setVisibility(View.GONE);
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState(); /* if comment this line white color applied,but only arrow displayed,not display nav icon(three line icon)*/
}


@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:titleTextAppearance="@style/AppTheme.Toolbar.Title"
    app:elevation="@dimen/cardview_default_elevation"
    app:borderWidth="0dp"
    >

values\styles.xml

<style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <!-- Set proper title size -->
        <item name="android:textSize">@dimen/abc_text_size_title_material_toolbar</item>
        <!-- Set title color -->
        <item name="android:textColor">@color/toolbar_title</item>
</style>

values-v21\styles.xml

<style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <!-- Set proper title size -->
        <item name="android:textSize">@dimen/abc_text_size_title_material_toolbar</item>
        <!-- Set title color -->
        <item name="android:textColor">@color/toolbar_title</item>
</style>

Proper use cases for Android ActivityManager.isUserAMonkey()?

I was looking at the new APIs introduced in Android 2.2. While looking at the ActivityManager class I came across the following method:

public static boolean isUserAMonkey()

Used to determine whether the user making this call is subject to teleportations.

Returns whether the user making this call is a monkey.

How and when should this be used?

Saving state of `EditText` visibility

I have couple of editTexts that are set to VISIBLE and INVISIBLE by a button click. I tried saving the state of visibility or invisibility using a Boolean and setting it to True when it became VISIBLE and setting it to False when it was INVISIBLE. I don't know why but it didn't save the state. Can someone show me an example or steer me the right way to save the state of the editText's visibility. I'm an android newbie, any help would be appreciated, thanks.

public void Visible() { ////this button click will make the editext visible, if it is invisible
if(e1.getVisibility() == View.INVISIBLE){
    e1.setVisibility(View.VISIBLE);
} else if(e2.getVisibility() == View.INVISIBLE){
    e2.setVisibility(View.VISIBLE);
 }
 }
 public void invisible(){ //this button click will make the editext invisible, if it is visible
if(e2.getVisibility() == View.VISIBLE)
{
    e2.setVisibility(View.INVISIBLE);
}
else if(e1.getVisibility() == View.VISIBLE){
    e1.setVisibility(View.INVISIBLE);
}
 }

How to draw path between my location to destination from input

I am doing a project which use the google map. My app is about drawing a path from the location of the user from the entered destination. Here is my code.

MapsActivity.java

public class MapsActivity extends FragmentActivity {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.
AutoCompleteTextView atvPlaces;
PlacesTask placesTask;
ParserTask parserTask;
Polyline line;
Context context;
LatLng una;
LatLng pangalawa;

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

    context = MapsActivity.this;
    Button btn = (Button) findViewById(R.id.Btype);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.Btype:
                    String urlTopass = makeURL(una.latitude,
                            una.longitude, pangalawa.latitude,
                            pangalawa.longitude);
                    new connectAsyncTask(urlTopass).execute();
                    break;

                default:
                    break;
            }
        }
    });

    final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
    }

    atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
    atvPlaces.setThreshold(1);
    atvPlaces.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            atvPlaces.showDropDown();
            return false;
        }
    });
    atvPlaces.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            placesTask = new PlacesTask();
            placesTask.execute(s.toString());
        }
        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    setUpMapIfNeeded();
}
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        iStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while( ( line = br.readLine()) != null){
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}
private class PlacesTask extends AsyncTask<String, Void, String>{
    @Override
    protected String doInBackground(String... place) {
        String data = "";
        String key = "key=AIzaSyCob51WvrkV9qAv6hiu4x0ku6tOC1_yzXI";
        String input="";
        try {
            input = "input=" + URLEncoder.encode(place[0], "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String types = "types=geocode";
        String sensor = "sensor=false";
        String parameters = input+"&"+types+"&"+sensor+"&"+key;
        String output = "json";
        String url = "http://ift.tt/1pwejJv"+output+"?"+parameters;
        try{
            data = downloadUrl(url);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        parserTask = new ParserTask();
        parserTask.execute(result);
    }
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>> {
    JSONObject jObject;
    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) {
        List<HashMap<String, String>> places = null;
        PlaceJSONParser placeJsonParser = new PlaceJSONParser();
        try {
            jObject = new JSONObject(jsonData[0]);
            // Getting the parsed data as a List construct
            places = placeJsonParser.parse(jObject);
        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }
        return places;
    }
    protected void onPostExecute(List<HashMap<String, String>> result) {
        String[] from = new String[]{"description"};
        int[] to = new int[]{android.R.id.text1};
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
        atvPlaces.setAdapter(adapter);
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}
public void onSearch(View view){
    String location = atvPlaces.getText().toString();

    List<Address> addressList = null;

    if(location != null || location.equals("")) {

        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        LatLng pangalawa = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(pangalawa).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(pangalawa));
    }
}
public void changeType(View view){
    if(mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL){
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    }
    else{
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }
}
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener(){
    public void onMyLocationChange(Location location){
        LatLng una = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions().position(una));
        if(mMap != null){
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(una, 16.0f));
        }
    }
};
private void setUpMap() {
    mMap.setOnMyLocationChangeListener(myLocationChangeListener);
    mMap.setMyLocationEnabled(true);
}

public void driverDetails(){
    Intent detailsIntent = new Intent(getApplicationContext(),MainActivity.class);
    detailsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(detailsIntent);
}
private void buildAlertMessageNoGps(){
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    driverDetails();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}
private class connectAsyncTask extends AsyncTask<Void, Void, String> {
    private ProgressDialog progressDialog;
    String url;

    connectAsyncTask(String urlPass) {
        url = urlPass;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog.hide();
        if (result != null) {
            drawPath(result);
        }
    }
}

public String makeURL(double sourcelat, double sourcelog, double destlat,
                      double destlog) {
    StringBuilder urlString = new StringBuilder();
    urlString.append("http://ift.tt/1exuaot");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString(sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(destlat));
    urlString.append(",");
    urlString.append(Double.toString(destlog));
    urlString.append("&sensor=false&mode=driving&alternatives=true");
    return urlString.toString();
}

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    // constructor
    public JSONParser() {
    }

    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

public void drawPath(String result) {
    if (line != null) {
        mMap.clear();
    }
    mMap.addMarker(new MarkerOptions().position(pangalawa).icon(
            BitmapDescriptorFactory.fromResource(R.drawable.b)));
    mMap.addMarker(new MarkerOptions().position(una).icon(
            BitmapDescriptorFactory.fromResource(R.drawable.b)));
    try {
        // Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes
                .getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
        List<LatLng> list = decodePoly(encodedString);

        for (int z = 0; z < list.size() - 1; z++) {
            LatLng src = list.get(z);
            LatLng dest = list.get(z + 1);
            line = mMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude, dest.longitude))
                    .width(5).color(Color.BLUE).geodesic(true));
        }

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

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}
}

Am I doing the right thing? or not? When i click the button of the drawing of path the application stopped. I don't know how i will get get the lat and long of the inputted destination to autocomplete textview and the user location. I just only need to draw path from the current location of the user and from the location that inputted by the user.

Canvas and android button

so maybe my problem will be so obvious but I've tried many trials and any of them were succesfull. So I'm writing simple program to generate fractal on canvas. But I need to add some button on this same layer and I have a problem because I can only add them on RelativeLayout and there are being hidden by canvas. How to solve it? If nedd I can paste my code.

DrawView.java

package com.example.rafa.fractalsgenerator;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {

protected Paint paint = new Paint();

public DrawView(Context context) {
    super(context);
}

@Override
public void onDraw(Canvas canvas) {}  //this public method will be changed       in other class
 }

The next one:

MainActivity.java

package com.example.rafa.fractalsgenerator;

import android.app.Activity;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;


public class MainActivity extends Activity implements View.OnClickListener {

BarnsleyFern fern;
Button button;

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

    fern = new BarnsleyFern(this);
    fern.setBackgroundColor(Color.WHITE);
    button = (Button) findViewById(R.id.button);

    setContentView(fern);

  }

  @Override
  public void onClick(View v) {
  }
 }

The last java file:

BarnsleyFern.java

package com.example.rafa.fractalsgenerator;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;

public class BarnsleyFern extends DrawView {

private double x,y,newx,newy; //coordinates of point of iteration
private double xe,ye; //screen coordinates
private  double rand; //generated number from [0;1) to choose corect  iteration equation
private final int Nmax = 180000; //number of iteration

public BarnsleyFern(Context context) {
    super(context);
}

@Override
public void onDraw(Canvas canvas) {

    paint.setColor(Color.argb(127, 255, 0, 255));

    x =0;
    y= 0;  //beginning values

    for (int i = 0; i < Nmax; i++) {

        rand = Math.random();

        if (rand < 0.01) {
            x = 0;
            y = 0.16 * y;
        }
        else if (rand < 0.84) {
            newx = (0.85 * x) + (0.04 * y);
            newy = (-0.04 * x) + (0.85 * y) + 1.6;
            x = newx;
            y = newy;
        }
        else if (rand < 0.92) {
            newx = (0.2 * x) - (0.26 * y);
            newy = (0.23 * x) + (0.22 * y) + 1.6;
            x = newx;
            y = newy;
        }
        else {
            newx = (-0.15 * x) + (0.28 * y);
            newy = (0.26 * x) + (0.24 * y) + 0.44;
            x = newx;
            y = newy;
        }
        xe = (float) (70*x + 300);
        ye = (float) (70*y +55);
        canvas.drawCircle((float) xe, (float) ye,1,paint); //cast needed cause, drawCircle(float,x float y...)
    }

   }

  }

And the xml file:

<RelativeLayout
android:id="@+id/mainView"
xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Color" />
  </RelativeLayout>

GridView of Items in an InputMethod Android

I have a standard ime working fine with regular keyboard xml files and a regular KeyboardView.

I would now like to add a button that switches to a GridView of images.

How would I get a GridView to pop-up in the keyboard area?

How can I get a location point on a country depend on Android phone configuration

I'm develop a android app with Google Map. In app start, if user don't turn on Location Service (can't get user current location, right ?),

I want my map zoom to current user's country base on configuration of phone . How can I do that ?

How to set height ImageView Android like Pinterest before load Image from URL?

I try to create app like pinteres. I use this library AndroidStaggeredGrid. But i have get problem when set height ImageView Android in adapter grid, before load from url.

  public View getView(final int position, View convertView, ViewGroup parent)
    {
        View vi = convertView;
        final ViewHolder holder;
        Integer item = (Integer) getItem(position);
        if (convertView == null)
        {
            vi = inflater.from(activity).inflate(R.layout.pin_item_news, null,
                    true);
            holder = new ViewHolder();


            holder.viewFlipper = (ImageView) vi
                    .findViewById(R.id.viewFlipper);

            vi.setTag(holder);
        } else
        {
            holder = (ViewHolder) vi.getTag();
        }

        HashMap<String, String> news = new HashMap<String, String>();
        news = dataNews.get(position);
        HashMap<String, String[]> news_article_image = new HashMap<String, String[]>();
        news_article_image = dataNewsArticleImages.get(position);
        // set data


        String var_news_article_image_width = news_article_image
                .get(Variabel.KEY_NEWSARTICLEIMAGEWIDTH);
        String var_news_article_image_height = news_article_image
                .get(Variabel.KEY_NEWSARTICLEIMAGEHEIGHT);


            holder.viewFlipper.measure(0, 0);
            int height = holder.viewFlipper.getMeasuredHeight();
            int widht = holder.viewFlipper.getMeasuredWidth();

            String int_width_thumbnail_news = var_news_article_image_width;
            String int_height_thumbnail_news = var_news_article_image_height;

            imageLoader.displayImage(
                    var_news_article_images[0],
                    holder.viewFlipper, options, new SimpleImageLoadingListener() {

                        @Override
                        public void onLoadingStarted(String imageUri,
                                                     View view) {
                        }

                        @Override
                        public void onLoadingFailed(String imageUri,
                                                    View view, FailReason failReason) {
                        }

                        @Override
                        public void onLoadingComplete(String imageUri,
                                                      View view, Bitmap loadedImage) {


                        }
                    }, new ImageLoadingProgressListener() {

                        @Override
                        public void onProgressUpdate(String imageUri,
                                                     View view, int current, int total) {
                        }
                    });


return vi;
}

This is Key WIdth and Height Image from URL

String var_news_article_image_width = news_article_image
                    .get(Variabel.KEY_NEWSARTICLEIMAGEWIDTH);
            String var_news_article_image_height = news_article_image
                    .get(Variabel.KEY_NEWSARTICLEIMAGEHEIGHT);

.. so how to this work ?

How to add media controls to MediaCodec and MediaExtractor

I have an android app which takes in an mp4 files and plays it using mediacodec and mediaextractor. I would like to add media controls to it. I am not sure whether its possible or not. Can someone point me to some examples or ways to do it ?

ionic apps do not run in 4.x android platforms

After upgrading Nodejs and all other modules I can not run Ionic build apps in 4.x version of androids

it shows that application successful lunched but there is no any app installation on emulator or attached device. the same thing is in cordova

ionic info:

Cordova CLI: 5.1.1
Ionic Version: 1.0.0
Ionic CLI Version: 1.5.5
Ionic App Lib Version: 0.2.2
OS: Windows 7 SP1
Node Version: v0.12.5 

Npm version
{ menu: '1.0.0',
  npm: '2.11.2',
  http_parser: '2.3',
  modules: '14',
  node: '0.12.5',
  openssl: '1.0.1o',
  uv: '1.6.1',
  v8: '3.28.71.19',
  zlib: '1.2.8' }

update [28/06/2015] I tied several days but there is no success. I tried so many ways but the default Android target: android-22

Creating Cordova project for the Android platform:
        Path: platforms\android
        Package: io.cordova.hellocordova
        Name: HelloCordova
        Activity: MainActivity
        Android target: android-22

I have manipulated by config.xml but there is no success to run in 4.0.1, 4.1.2 and etc.

C:\Users\>adb install  android-debug.apk
2513 KB/s (2321618 bytes in 0.902s)
        pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_FAILED_OLDER_SDK]
rm failed for -f, No such file or directory

more details are posted in http://ift.tt/1Jfa5Pu

Android ListView doesnot refresh by Filter

In my application I have three fragment with ViewPager. one of this fragments i have simple Arraylist as ListView from phones contact list and i'm trying to filter that after typing into edittext. but doesn't refresh until softkeyboard is visible and I must have to hide keyboard to refresh list view by filtered strings.

For example:

filter listview by "a":

adapter.getFilter().filter("a");

My adapter implements from Filterable

public class AdapterContacts extends BaseAdapter implements Filterable {
    private LayoutInflater inflater;
    private Context context;
    private List<ContactLists> categoryArrayList;
    private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
    private NameFilter filter;

    public AdapterContacts(ArrayList<ContactLists> array) {
        categoryArrayList = array;
    }

    public AdapterContacts(Context context, List<ContactLists> array) {
        this.context = context;
        inflater = LayoutInflater.from(this.context);
        categoryArrayList = array;
        originalList.addAll(array);
    }

    @Override
    public int getCount() {
        return categoryArrayList.size();
    }

    @Override
    public ContactLists getItem(int position) {
        return categoryArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ...
    }

    private static class UI extends HelperUI {
        ...
    }

    private class ViewHolder {
        private UI UI;

        public ViewHolder(View view) {
            UI = new UI(view);
        }

        public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
        ...
    }

    @Override
    public Filter getFilter() {
        if (filter == null) {
            filter = new NameFilter();
        }
        return filter;
    }

    private class NameFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            constraint = constraint.toString().toLowerCase();
            FilterResults result = new FilterResults();
            if (constraint != null && constraint.toString().length() > 0) {
                ArrayList<ContactLists> filteredItems = new ArrayList<ContactLists>();
                int l = originalList.size();
                for (int i = 0 ; i < l; i++) {
                    ContactLists nameList = originalList.get(i);
                    if (nameList.getContact_name().toString().contains(constraint)) {
                        filteredItems.add(nameList);
                    }
                }
                result.count = filteredItems.size();
                result.values = filteredItems;
            } else {
                synchronized (this) {
                    result.values = originalList;
                    result.count = originalList.size();
                }
            }
            return result;
        }


        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            ArrayList<ContactLists> temp = (ArrayList<ContactLists>) results.values;
            categoryArrayList.clear();
            categoryArrayList.addAll(temp);
            notifyDataSetChanged();
            temp.clear();
            notifyDataSetInvalidated();
        }
    }
}

softkeyboard status status in Manifest for ActivityMain. this class have view pager with three fragment:

    <activity android:name=".Activities.ActivityBootstrap" android:windowSoftInputMode="adjustPan"  android:screenOrientation="portrait"/>

Fragment is not shown on Activity

In my App,One Activity has to include three fragments, one of them always remains on Activity but the other two have to change places. But fragments are not shown on an activity.

I have read somewhere here that I should change LinearLayout to FragmentLayout but it did not work.

public class MainActivity extends ActionBarActivity {

private final Fragment_1to6 f1to6 = new Fragment_1to6();
private final Fragment_7to12 f7to12 = new Fragment_7to12();

private FragmentManager mFragmentManager;
private FrameLayout mButtonsLayout, mLayout1to6;
private FrameLayout mLayout7to12;

private static final int MATCH_PARENT = LinearLayout.LayoutParams.MATCH_PARENT;
private static final int WRAP_CONTENT = LinearLayout.LayoutParams.WRAP_CONTENT;

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


    mButtonsLayout = (FrameLayout) findViewById(R.id.fragment_buttons);
    mLayout1to6 = (FrameLayout) findViewById(R.id.fragment_1to6);
    mLayout7to12 = (FrameLayout) findViewById(R.id.fragment_7to12);

    mFragmentManager = getFragmentManager();
    final FragmentTransaction ft = mFragmentManager.beginTransaction();

    ft.add(R.id.fragment_buttons, new buttonsFragment());
    ft.add(R.id.fragment_1to6, f1to6);

    ft.addToBackStack("fragment_buttons");
    ft.addToBackStack("fragment_1to6");

    ft.commit();

    mFragmentManager
            .addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
                public void onBackStackChanged() {
                    setLayout();
                }
            });


    mFragmentManager.executePendingTransactions();


}

private void setLayout() {

    // Determine whether the Fragment has been added
    if (!f7to12.isAdded()) {

        mButtonsLayout.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 1f));
        mLayout1to6.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 6f));
    } else {

        mButtonsLayout.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 1f));
        // Make the TitleLayout take 6/13 of the layout's width
        mLayout1to6.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 6f));

        // Make the QuoteLayout take 6/13's of the layout's width
        mLayout7to12.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 6f));
    }


}

how can i solve that ?

The correct way to create and write to an owned external SD card directory on Android 4.4 KitKat and up?

I have spent literally hours now looking for (and trying) many different ways to write some files to my 4.4 Android KitKat's external SD card. Now that Google has limited access to the filesystem on SD cards it seems you are forced to only be able to write to directories owned by the application (eg: /Android/data/com.mycompany.myapp/files/).

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

first I create two globals to house the strings of both the internal and external paths.

MainActivity

public class MainActivity extends ActionBarActivity {
    String internalStorageDirectory;
    String externalStorageDirectory;

Then I ask the system where the directories are and start building absolute paths for both the internal and external variables followed by creating a new file for internalStorage.

onCreate()

internalStorageDirectory = this.getExternalFilesDir(null).toString();
File folderInt = new File(internalStorageDirectory); //THIS LINE IS CRUCIAL!!
Log.d("DEBUG", " - Internal Path" + internalStorageDirectory);// "/storage/emulated/0/Android/data/com.mycompany.httpreq2/files"


String ownedDirectory = "/Android/data/" + this.getPackageName();
externalStorageDirectory = System.getenv("SECONDARY_STORAGE").toString() + ownedDirectory + "/files//";
Log.d("DEBUG", " - External Path"+externalStorageDirectory);// "/storage/external/Android/data/com.mycompany.httpreq2/files//"

Finally I am able to save a file that I downloaded earlier from an AsyncTask.

doInBackground()

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

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

adb shell output:

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

So I guess my question is, why do I need to create a file for internal storage first:

File folderInt = new File(internalStorageDirectory); //THIS LINE IS CRUCIAL!!

before I can write to the external directory? Am I even doing this correctly?

Thanks for any insight into this, Cheers!