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!

using of long touch and multi thread programming

I have a problem in using of long touch and multi thread programming.

I have 2 button: up and down. Each of these buttons have OnTouchListener event habdler . When I touch down in each of them, a thread will run inside them in the while(HelperClass.Universal_IsTouch == true) and in every 1000 milisec run again until tuouch up raised and "HelperClass.Universal_IsTouch" make false in touch up and it exit from the while .

in the while loop a thrad run and call another class method for sending data via run another thread via socket programming . So then when up button (or down) touched down long time , data should be send to server until touched up raised.

Its working but after many sending up and down when I touch long up (or down) its sended data related to other routin instead main routin ?

this is my UP routin code :

//////////// up 
            btn_UP_var.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {

                    IntruptedAllThread();

                    // TODO Auto-generated method s tub
                    if (arg1.getAction() == MotionEvent.ACTION_DOWN)
                    {
                        HelperClass.Universal_IsTouch = true;

                    } else if (arg1.getAction() == MotionEvent.ACTION_UP) {

                        HelperClass.Universal_IsTouch = false;

                    }

                    //Send a simple Move (once)
                    if (chkbx_AutoMove_var.isChecked()) {
                        Img_Stop_var.setImageResource(R.drawable.arrow_stop_play);
                        Is_UP_buttonTouched = 1;
                        HelperClass.Is_Stop_Button_Disable = false;

                    } else {
                        HelperClass.Is_Stop_Button_Disable = true;

                        thread_UP = new Thread(new Runnable() {

                            @Override
                            public void run() {
                                while (HelperClass.Universal_IsTouch == true) {

                                    Cursor ListHoist = mDbHelper.GetallSelectedHoistData();
                                    //mDbHelper.close();
                                    for (ListHoist.moveToFirst(); !ListHoist.isAfterLast(); ListHoist.moveToNext()) {
                                        String IP = ListHoist.getString(ListHoist.getColumnIndex("HoistIP"));
                                        int PK_hoist = ListHoist.getInt(ListHoist.getColumnIndex("PK_hoist"));

                                        HelperClass.SendDataToMICRO(mDbHelper, PK_hoist, IP, HelperClass.Selector_Move_Stop,
                                                HelperClass.MoveDesition_Up, HelperClass.inutile, HelperClass.inutile,
                                                HelperClass.inutile);
                                    }
                                    ListHoist.close();

                                    try {
                                        Thread.sleep(1000);
                                    }
                                    catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                        IntruptedAllThread();

                                    }
                                }
                                // thread_UP.interrupt();
                                IntruptedAllThread();

                            }
                        });
                        thread_UP.start();
                    }

                    return true;
                }
            });

and this is my Down Code :

 //////////// Down 
            btn_Down_var.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    // TODO Auto-generated method stub

                    IntruptedAllThread();

                    if (arg1.getAction() == MotionEvent.ACTION_DOWN)
                    {
                        HelperClass.Universal_IsTouch = true;
                        //txt_MovementValue_var.setText("1");

                    } else if (arg1.getAction() == MotionEvent.ACTION_UP)
                    {
                        HelperClass.Universal_IsTouch = false;

                        //txt_MovementValue_var.setText("0");
                    }

                    //Send a simple Move (once)
                    if (chkbx_AutoMove_var.isChecked()) {
                        Img_Stop_var.setImageResource(R.drawable.arrow_stop_play);
                        Is_UP_buttonTouched = 0;
                        HelperClass.Is_Stop_Button_Disable = false;

                    } else {
                        HelperClass.Is_Stop_Button_Disable = true;
                        thread_Down = new Thread(new Runnable() {

                            @Override
                            public void run() {
                                while (HelperClass.Universal_IsTouch == true) {

                                    Cursor ListHoist = mDbHelper.GetallSelectedHoistData();
                                    for (ListHoist.moveToFirst(); !ListHoist.isAfterLast(); ListHoist.moveToNext()) {
                                        String IP = ListHoist.getString(ListHoist.getColumnIndex("HoistIP"));
                                        int PK_hoist = ListHoist.getInt(ListHoist.getColumnIndex("PK_hoist"));

                                        HelperClass.SendDataToMICRO(mDbHelper, PK_hoist, IP, HelperClass.Selector_Move_Stop,
                                                HelperClass.MoveDesition_Down, HelperClass.inutile, HelperClass.inutile,
                                                HelperClass.inutile);
                                    }
                                    ListHoist.close();

                                    try {
                                        Thread.sleep(1000);
                                    }
                                    catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                        IntruptedAllThread();

                                    }
                                }
                                //thread_Down.interrupt();
                                IntruptedAllThread();

                            }
                        });
                        thread_Down.start();
                    }

                    return true;
                }
            });

this is IntruptedAllThread()

    public void IntruptedAllThread() {
    if (thread_UP != null) {
        thread_UP.interrupt();
        thread_UP = null;
    }
    if (thread_Down != null) {
        thread_Down.interrupt();
        thread_Down = null;
    }
}

and this is my thread to send data socket :

//This get each hoist data and change it to 
//Int array to send to micro 
public static void SendDataToMICRO(dbAdapter mDbHelper, int HoistID, final String Server_IP, int firstByte_KindType, int secoundByte_KindofMove,
                                   int ValueOfMove, int valueOfsetting, int MaxOrMinValue) {
    //        mDbHelper = new dbAdapter(G.context);
    //        mDbHelper.createDatabase();
    //        mDbHelper.open();
    Server_Port = mDbHelper.GetPortNumber();
    //mDbHelper.close();

    final String Concatinate_values = firstByte_KindType + Spliter + secoundByte_KindofMove +
            Spliter + ValueOfMove + Spliter + valueOfsetting + Spliter + MaxOrMinValue;

    //Sent Routin
    ////‌Connect To server

    Thread thread = null;

    thread = new Thread(new Runnable() {

        @Override
        public void run() {

            DataOutputStream outputStream = null;
            BufferedReader inputStream = null;
            Socket socket;
            socket = new Socket();

            try {

                socket.connect(new InetSocketAddress(Server_IP, Server_Port), 10);

            }
            catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
                Thread.currentThread().interrupt();
            }

            ////Make Read Line
            try {
                outputStream = new DataOutputStream(socket.getOutputStream());

                inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            }
            catch (IOException e1) {
                //Finished Socket

                ShutDown(socket);
            }

            if (outputStream == null) {
                //
                ShutDown(socket);
                Thread.currentThread().interrupt();
                return;
            }

            //Write Message
            try {
                String message = Concatinate_values + "\n";

                outputStream.write(message.getBytes());
                outputStream.flush();

                ShutDown(socket);
                Thread.currentThread().interrupt();
                return;

            }
            catch (IOException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();

            }

            try {
                if (socket != null) {
                    socket.close();

                }
            }
            catch (IOException e) {
                e.printStackTrace();
                ShutDown(socket);
                Thread.currentThread().interrupt();
                return;
            }
            Thread.currentThread().interrupt();
        }
    });

    thread.start();

}

enter image description here

result

enter image description here

Getting empty profile pic when trynig to get it in bigger size android

I am trying to get all user's profile pictures in Facebook using Graph API. Ans I came across a weird problem, when I am asking somthing like this:

http://ift.tt/wljqS4" + d.get(i) + "/picture?width=100&height=100";

It reutrn an empty profile for half of the images, but when I decreas the width and height all is ok again. Someone have an idea what causes it to happen?

I want to get bigger images for better resolution.

And when I type the URL in chrom it says it correct and displaing the images in the given size.

Enter both answers after every 2 questions are shown

How do I display every 2nd question together with the previous question without having to answer every 1st question? Means that user can only answer both questions when they are shown together. Also, how do I make such that user can only answer 2 questions when every 2 questions are shown? I'm not sure how to do it. Please help me. Thanks:)

@Override
    public void onClick(View view) 
    {
        if(view.getId()==R.id.enter){

            try{
                stopPlaying();
            }catch(Exception e){
            }
            questionNumber++; 


            String answerContent = answerTxt.getText().toString();
            if(firstQuestion == true){
                buttonCounter = 1;
                firstQuestion = false;
                replayBtn.setEnabled(true);
                chooseQuestion();
            }           
            else if(!answerContent.endsWith("?")){
                int enteredAnswer = Integer.parseInt(answerContent.substring(2));
                int exScore = getScore();
                if(enteredAnswer==ans[QnNum]){
                    buttonCounter = 1;
                    replayBtn.setEnabled(true);
                    scoreTxt.setText("Score: "+(exScore+1));
                    response.setImageResource(R.drawable.tick);
                    response.setVisibility(View.VISIBLE);
                }
                else{
                    setHighScore();
                    buttonCounter = 1;
                    replayBtn.setEnabled(true);
                    if (exScore==0){
                        scoreTxt.setText("Score: 0");
                    }
                    else {
                        scoreTxt.setText("Score: "+(exScore-1));
                    }
                    response.setImageResource(R.drawable.cross);
                    response.setVisibility(View.VISIBLE);
                }

                chooseQuestion();
            }
        }

        else if(view.getId()==R.id.imageButton1){

            if(buttonCounter==1)
            {
                replayBtn.setEnabled(false);
              Log.d("ins", "called");
            }
            buttonCounter=0;


            MediaPlayer qn = MediaPlayer.create(this, QnsList[QnNum]);

            pauseTimer = true;
            qn.start();
            qn.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer qn) {
                    qn.stop();
                    qn.reset();
                    qn.release();
                    qn = null;
                    pauseTimer = false;
                }
            });


            if (leftTimeInMillisecondsGlobal == 0) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                setTimer(originalTimerTimeInMilliSeconds);
            } else {
                if (countDownTimer != null) {
                    countDownTimer.cancel();

                }
                setTimer(leftTimeInMillisecondsGlobal);
            }


            startTimer();

            try{
                stopPlaying();
            }catch(Exception e){
            }
            qn.start();
        }

        else if(view.getId()==R.id.clear){
            answerTxt.setText("= ?");
        }
        else {
            response.setVisibility(View.INVISIBLE);
            int enteredNum = Integer.parseInt(view.getTag().toString());
            if(answerTxt.getText().toString().endsWith("?"))
                answerTxt.setText("= "+enteredNum);
            else
                answerTxt.append(""+enteredNum);
        }
    }

    private void stopPlaying() {
        if (qn != null) {
            qn.stop();
            qn.release();
            qn = null;}
    }

    private void setRandomSequence() {
        arrayList = new LinkedList<Integer>();
        for(int s =0; s<arrayOfNumbers.length;s++)
         arrayList.add(s);

        Collections.shuffle(arrayList);
        System.out.println(arrayList);
        }

    private void setTimer(long timeLeft) {

        totalTimeCountInMilliseconds = timeLeft;

        timeBlinkInMilliseconds = 20 * 1000;
    }

    private void startTimer() {
        countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {

            @Override
            public void onTick(long leftTimeInMilliseconds) {
                long seconds = leftTimeInMilliseconds / 1000;

                if (pauseTimer == true) {
                    leftTimeInMillisecondsGlobal = leftTimeInMilliseconds;
                    countDownTimer.cancel();
                } else {

                    leftTimeInMillisecondsGlobal = leftTimeInMilliseconds;
                }

                if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
                    textViewShowTime.setTextAppearance(getApplicationContext(),
                            R.style.blinkText);


                    if (blink) {
                        textViewShowTime.setVisibility(View.VISIBLE);
                    } else {
                        textViewShowTime.setVisibility(View.INVISIBLE);
                    }


                    blink = !blink; 
                }


                textViewShowTime.setText(String.format("%02d", seconds / 60)
                        + ":" + String.format("%02d", seconds % 60));


            }


            @Override
            public void onFinish() {
                Log.i("check", "check if enter onFinish() method");
                setResults();
                saveScore();
                Log.i("check", "check if passes through");
            }




        }.start();}

    private int getScore(){
        String scoreStr = scoreTxt.getText().toString();
        return Integer.parseInt(scoreStr.substring(scoreStr.lastIndexOf(" ")+1));
    }

    private void chooseQuestion(){
        answerTxt.setText("= ?");
        QnNum = random.nextInt(QnsList.length);

    final int DELAY_MS = 1000;


        question.setText("Qn "+(questionNumber));

        pauseTimer = true;

        qn = MediaPlayer.create(this, QnsList[QnNum]);
        qn.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer qn) {
            qn.stop();
            qn.reset();
            qn.release();
            qn = null;
            pauseTimer = false;
        }
    });

        if (leftTimeInMillisecondsGlobal == 0) {
            if (countDownTimer != null) {
                countDownTimer.cancel();
            }
            setTimer(originalTimerTimeInMilliSeconds);
        } else {
            if (countDownTimer != null) {
                countDownTimer.cancel();
            }
            setTimer(leftTimeInMillisecondsGlobal);
        }

        startTimer();

        qn.start();}

Android app development with remote database

I am new to android development. I would like to create an app that would store data in a remote database and i should be able to retrieve it. Which would the appropriate server and database for this application?

Videoview measure to fit a layout with exactly ratio

I use Mediaplayer in android to play video online and display this on a videoview. The videoview is put in a RelativeLayout with a fixed size.

The problem is the size (width and height of video) is not fit the relativelayout, so I need to resize video to fit inside relativelayout with exactly ratio of video, but it's seem like doesn't work, my code here:

***Code to create a videoview:

    ...
        MyVideoView mVideoView = new MyVideoView(mContext);
                mVideoView.requestFocus();

                RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                mVideoView.setLayoutParams(p);

                return mVideoView;
}

*** Code to get ratio when video is started playing

    @Override
        public void onPrepared(MediaPlayer mediaPlayer) {

            mWebview.removeView(mProgressWheel);
            mediaPlayer.start();

    //        int w = mediaPlayer.getVideoWidth();
    //        int h = mediaPlayer.getVideoHeight();
            int w = mVideoView.getWidth();
            int h = mVideoView.getHeight();

            ((MyVideoView) mVideoView).setDimention(w, h);

        }

*** A short of My custom video view class:

public class MyVideoView extends VideoView{
    ...
 private ElementObject elm;
private int aW;
        private int aH;
        int additional = 0;
        float ratio = 1f;
private void caculateRatio(int w, int h){

            if(w > h) ratio = (float)w/h;
            else if(h > w) ratio = (float)h/w;
        }

    public void setDimention(int w, int h){
                this.aW = w;
                this.aH = h;
                setIsPlaying(true);

                caculateRatio(w, h);
                calculateAdditional(w, h);
            }
     public void calculateAdditional(int w, int h){
                if(w >= elm.frame.getW() && h < elm.frame.getH()) {
                    additional = elm.frame.getH() - h;
                    measure(w + (int) (additional * ratio), elm.frame.getH());
                }else if(w < elm.frame.getW() && h >= elm.frame.getH()) {
                    additional = elm.frame.getW() - w;
                    measure(elm.frame.getW(), h + (int) (additional * ratio));
                }else if(w < elm.frame.getW() && h < elm.frame.getH()){

                    int wR = elm.frame.getW() - w;
                    int hR = elm.frame.getH() - h;

                    if(wR > hR){
                        additional = wR;
                        measure(elm.frame.getW(), h + (int) (additional * ratio));
                    }else {
                        additional = hR;
                        measure(w + (int) (additional * ratio), elm.frame.getH());
                    }
                }
                else
                    measure(w, h);


            }

@Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            //super.setMeasuredDimension(1000,1000);
            setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
        }

}

I found that the override function onMeasure(int, int) is called multiple time before the video started playing, so that I removed onMeasure(int, int) function and call: setMeasuredDimension(int, int) in side function: public void calculateAdditional(int w, int h){...} instead of using measure(int, int), but it also not affect anything. What can I do to resize the video to fit exactly relativelayout with exact ratio.

Also try to change layoutparams whey creating videoview to FILL_PARENT or MATCH_PARENT, but keep wrong.

(Android-intent) How do I fix the string R.id.chooser so that it is referenced by the java file

I was working on the excercise in the book Head first in to android development and did the exercise as precisely the book specified, but typing R.id.chooser says chooser symbol cannot be resoled even though i declared it in strings XML. This is weird... anyone have suggestions to fix this?

java file:

package com.hfad.messenger;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;`enter code here`
import android.content.Intent;
import android.widget.EditText;

public class CreateMessageActivity extends Activity {

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

    //Call onSendMessage() when the button is clicked
    public void onSendMessage(View view) {
        EditText messageView = (EditText)findViewById(R.id.message);
        String messageText = messageView.getText().toString();
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/pain");
        intent.putExtra(Intent.EXTRA_TEXT, messageText);
        String chooserTitle = getString(R.string.chooser);
        Intent chosenIntent = Intent.createChooser(intent, chooserTitle);
        startActivity(chosenIntent);
    }
}

xml file:

<resources>
    <string name="app_name">Messenger</string>
    <string name="send">Send Message</string>
    <String name="chooser">Send Message...</String>
    <string name="action_settings">Settings</string>
    <string name="title_activity_receive_message">ReceiveMessageActivity</string>
</resources>

Open full Image from gridview in new Activity

I tried to make general gridview and categorical gridview , from categorical gridview try to open clicked image in new activity .

THE PROBLEM IS WHEN click item in categorical gridview it doesn't open the new Activity

second gridview "categorical ":

     holder.tv = (TextView) row.findViewById(R.id.textView1);
        holder.img = (ImageView) row.findViewById(R.id.imageView1);

        holder.tv.setText(Bresult[position]);
        holder.img.setImageResource(BimageId[position]);

        if (row == null) {
            row = new ImageView(Bcontext);
        }
        row.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Bcontext, BActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (position==0){
                    intent.putExtra("imageID", position);
                    Bcontext.startActivity(intent);
                }
                Toast.makeText(Bcontext, "You Clicked " + Bresult[position], Toast.LENGTH_LONG).show();

            }
        });

        return row;
    }
}

And this the New Activity should image appear there :

    Intent intent = getIntent();
    BCustomAdapter imageAdapter = new BirthCustomAdapter(this);
    Bundle bdl = getIntent().getExtras();
    int index = bdl.getInt("imageID");
    ImageView image = (ImageView) findViewById(R.id.img_view);
    image.setImageResource(index);
}

How can I get special links from text in Android

I am having a problem getting the information of linked text in text message.
I was able to read sms messages by accessing content://sms/inbox and then access proper (in this case, body) column. But body contains plain text of the message, no information about the link.
For instance, if I have a text message like: call me HERE, which HERE is internally linked to phone number, is there anyway to find that HERE is internally linked and also the link for that? In other words, how can I get a information like call me <a href="tel:12345">HERE</a>

Scroll TabHost Up and Down Android - Java

I have a tabhost that contains a list view, and then above the tabhost I have a relative layout. And what I am trying to do is when I scroll the list view also scroll the tabhost and relative layout up/ down.

Currently when I scroll down, the first row disappears then the 2nd and so on...

But instead what I want is when I scroll down, first the relative layout disappears, then the tabhost and then the first row and so on...

Currently it is just a basic set up with a relative layout, then tabhost with a basic list view inside it. So how could I make it scroll down?

Thanks for the help in advance.

How to remove app title from toolbar?

I can't figure out how to remove my title. I've use the code below in my MainActivity but after I add that line my app crashes.

getSupportActionBar().setDisplayShowTitleEnabled(false);

Here is how my MainActivity looks

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

getType() returning incorrect mime type

In my app I provide functionality to choose an image from one of the content providers. One of the available providers is obviously Google Photos. During my testing I have found if:

  • I select Google Photos as the content provider
  • The collection of images has 1+ png images
  • A png image is chosen

the reported mime type is "image/jpeg" rather than "image/png".

I believe I am using the standard way of deriving the mime type:

String mime_type = getContentResolver().getType(image_uri);

I am sending the chosen image to a server which requires the image to be jpeg. I would like to be able to detect an invalid file type on the device rather than wait for an error response from the server.

I guess I could load the file into a bitmap and then write it out in jpeg format but I'd rather either prevent the content provider from offering png's as available to choose from, or have some way of correctly determining the mime type - given that I apparently can't believe what getType is telling me.

I have experimented with different variations of:

intent.setType("image/*");

but have not been able to suppress png's from being made available by the Photos app.

Any suggestions?

Augmented reality 3D reconstruction

I want to develop an android augmented reality application, in which app should have a function to reconstruct a destructed objects(ex : buildings/statues) as shown in the following video link https://www.youtube.com/watch?v=WOVjISxlhpU

I have gone through metaio, wikitude and vuforia sites each has some difficulties it self. and at Last i found vuforia has a feature call Smart Terrain where it is used for 3D animation and game development , the issue is only limited tutorials available to develop a customized application. With that above link i found armedia.it and hyperspaces.inglobetechnologies.com those too have limited tutorials with the code.

Please let me know if any other SDK available their to fulfill my app feature share if there any useful tutorial to do such for the above sdk's

Thanks in advance

What kind of variable to declare in this "draggable popup" code?

I am inserting the following lines (from pskink post 3-2-14) into my popup Android activity file. This is being placed in the onCreate in an already working project. Android Studio wants me to declare the following 3 as either local variable, a parameter or a field. The 3 are: mPopup, mCurrentX and mCurrentY. If I just do the trial-and-error method, trying one at a time, that might work, eh? Or any ideas about how to tell which to use?

a) If I select 'local', AS changes mPopup to 'PopupWindow'. b) If I select 'parameter, AS asks about refactoring.

final View cv = new View(this); setContentView(cv);

TextView tv = new TextView(this);
tv.setBackgroundColor(0xffeeeeee);
tv.setTextColor(0xff000000);
tv.setTextSize(24);
tv.setText("click me\nthen drag me");
tv.setPadding(8, 8, 8, 8);
mPopup = new PopupWindow(tv, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
OnTouchListener otl = new OnTouchListener() {
    private float mDx;
    private float mDy;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            mDx = mCurrentX - event.getRawX();
            mDy = mCurrentY - event.getRawY();
        } else
        if (action == MotionEvent.ACTION_MOVE) {
            mCurrentX = (int) (event.getRawX() + mDx);
            mCurrentY = (int) (event.getRawY() + mDy);
            mPopup.update(mCurrentX, mCurrentY, -1, -1);
        }
        return true;
    }
};
tv.setOnTouchListener(otl);

mCurrentX = 20;
mCurrentY = 50;
cv.post(new Runnable() {
    @Override
    public void run() {
        mPopup.showAtLocation(cv, Gravity.NO_GRAVITY, mCurrentX, mCurrentY);
    }
});

How yo access shared file

In my andorid app, i want to access only those file which is shared with me either by web(drive.google.com) or app. I am using google drive api to access shared file but i am not able to access any file or folder shared with me . My code is given below .

public class QueryFilesSharedWithMeActivity extends BaseDemoActivity {

private ListView mResultsListView;
private ResultsAdapter mResultsAdapter;

@Override
protected void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.activity_listfiles);
    mResultsListView = (ListView) findViewById(R.id.listViewResults);
    mResultsAdapter = new ResultsAdapter(this);
    mResultsListView.setAdapter(mResultsAdapter);
}

/**
 * Clears the result buffer to avoid memory leaks as soon as the activity is no longer
 * visible by the user.
 */
@Override
protected void onStop() {
    super.onStop();
    mResultsAdapter.clear();
}

@Override
public void onConnected(Bundle connectionHint) {
    super.onConnected(connectionHint);
    Query query = new Query.Builder()
            .addFilter(Filters.sharedWithMe())
            .build();
    Drive.DriveApi.query(getGoogleApiClient(), query)
            .setResultCallback(metadataCallback);
}

final private ResultCallback<DriveApi.MetadataBufferResult> metadataCallback =
        new ResultCallback<DriveApi.MetadataBufferResult>() {
            @Override
            public void onResult(DriveApi.MetadataBufferResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Problem while retrieving results");
                    return;
                }
                mResultsAdapter.clear();
                mResultsAdapter.append(result.getMetadataBuffer());
            }
        };

}

Note* Can we filter a file or folder shared with me with a specific folder name?

android AmazingListView : how to update header

I used amazing list view in my code. It does well. Now I am trying to update header from list item. But I failed to get the header id from another list item ie from getAmazingView method. How to get the header id and update my header

Module dependency leads to Error:Gradle: Execution failed for task ':app:preDexDebug' in Android Studio

I tried to add a module to an Android project and make the main module dependent on it and I got this error:

Error:Gradle: Execution failed for task ':app:preDexDebug'. com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_40\bin\java.exe'' finished with non-zero exit value 1

I have a project with the main module app and added a module mylib and app depends on mylib.

Android Studio 1.2.2.

settings.gradle:

include ':app', ':mylib'

build.gradle from app:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    compileOptions {
        sourceCompatibility org.gradle.api.JavaVersion.VERSION_1_8
        targetCompatibility org.gradle.api.JavaVersion.VERSION_1_8
    }

...

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':mylib')
}

build.gradle from mylib:

apply plugin: 'java'

sourceCompatibility = org.gradle.api.JavaVersion.VERSION_1_8
targetCompatibility = org.gradle.api.JavaVersion.VERSION_1_8

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
}

The JAVA_HOME variable:

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_40

The problem starts when I add line compile project(':mylib') to build.gradle, sometimes when I rebuild the project, but always when I try to run it. The VERSION_1_8 statements don't solve the problem.

What can be wrong? Any help will be very much appreciated.