Blog

  • How to fix java.lang.VerifyError in Android for ADT-22

    How to fix java.lang.VerifyError in Android for ADT-22

    I had one problem when migrated to ADT-22.

    I’ve renamed “lib” dir to “libs” and project compiled.
    And when I run project on Android device the “java.lang.VerifyError” error crashes my app.
    In the LogCat I saw that some of classes were rejected by Verifier: “Verifier rejected class …..”

    And I found solution.

    There problem in two checkboxes in project properties. Lets look the screenshots.

    This screenshot show properties before fix:

    And this screenshot after fixing:

    To fix it you need put ticks near:
    – Android Private Libraries
    – Android X.X.X

    Hope it help you

  • How to setAlpha for View in Android 2.3 (API-10) and lower

    How to setAlpha for View in Android 2.3 (API-10) and lower

    As you can see there existing setAlpha() method in API-11. Using this method you can change Alpha for View.

    What we gonna do in API-10 and lower to change View Alpha?

    I’ve got one solution. The solution is AlphaAnimation

    Please take a look my code:

    package com.hrupin.samples.alpha;
    
    import com.hrupin.samples.halfopacitywidgets.R;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.animation.AlphaAnimation;
    import android.widget.Button;
    
    public class MainActivity extends Activity {
    
    	private Button buttonWithAlpha;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		buttonWithAlpha = (Button)findViewById(R.id.buttonWithOpacity);
    
    		setAlphaForView(buttonWithAlpha, 0.5f);
    	}
    
    	private void setAlphaForView(View v, float alpha) {
    		AlphaAnimation animation = new AlphaAnimation(alpha, alpha);
    		animation.setDuration(0); 
    		animation.setFillAfter(true); 
    		v.startAnimation(animation);
    	}
    }

    In this way you can simply change alpha for your view in Android API-10 and lower.

    Download it from github
  • How to change Android SDK path in Android Studio for Mac

    How to change Android SDK path in Android Studio for Mac

    Today I want to change default Android SDK path in Android Studio. To change default path to Android SDK you need do the next steps. I describe it via screenshots.

    1. Open Android Studio.

    2. Configure Android Studio.

    3. Click Project Defaults.

    4. Cofigure Android SDK path. Click to enlarge. Go to SDKs -> Android SDK

    5. Cofigure Android SDK path. Go to Project -> Project SDK

    Enjoy

  • How to fix “Can not perform this action after onSaveInstanceState” on Android Fragments

    How to fix “Can not perform this action after onSaveInstanceState” on Android Fragments

    Recent I’ve this bug on my project.
    This bug comes when app awake from sleep.
    I’ve spent a lot of time to fix it. And finally I got the solution.

    My project is Activity with Fragments.
    The error text is:
    java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3113)
    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3062)
    at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3035)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1268)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:4945)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
    at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1327)
    at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1338)
    at android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:501)
    at android.support.v4.app.DialogFragment.dismissInternal(DialogFragment.java:180)
    at android.support.v4.app.DialogFragment.dismiss(DialogFragment.java:155)
    at

    To fix it you need save instance of your Fragments. To do this you need just override onSaveInstanceState method for your Fragment.

    @Override
    public void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	outState.putString(BundleKeys.MESSAGE, message);
    }

    Also you need restore fragment state in onCreateView of onActivityCreated methods

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	if (savedInstanceState != null) {
    			if (!savedInstanceState.isEmpty()) {
    			Loger.i(TAG, "!savedInstanceState.isEmpty()");
    			if (message == null) {
    				message = new Gson().fromJson(savedInstanceState.getString(BundleKeys.MESSAGE), Message.class);
    			}
    		}
    	}
    }

    Hope it help you.

  • Eclipse ADT Rev 22 doesn’t generate R.java

    Eclipse ADT Rev 22 doesn’t generate R.java

    I had this problem when updated to ADT-22 on Eclipse.

    To fix it you need download NEW additional component from google. This is “Android SDK Build-tools”.

    Open Your SDK Manager and download it.

    Restart Eclipse

  • How to create filter for ListView items in Android. Part-2. List with custom adapter.

    How to create filter for ListView items in Android. Part-2. List with custom adapter.

    As you can see in my previous post about ListView filtering in Android (How to create filter for ListView items in Android.) creating a filter is pretty simple if you’re have a list with Strings.

    Here I show you how to create a filter for your custom adapter with complex objects. Here the screenshot of the sample application:

    Here is an updated version of this (How to create filter for ListView items in Android.) application.

    In the list of countries you also can see the population and area of the country.

    Please look at Country class:

    package com.hrupin.sample.filterlist;
    
    public class Country {
    
        private String name;
        private int area;
        private int population;
    
        public Country(String name, int population, int area) {
            this.name = name;
            this.area = area;
            this.population = population;
        }
        
        public int getArea() {
            return area;
        }
        
        public String getName() {
            return name;
        }
        
        public int getPopulation() {
            return population;
        }
        
        @Override
        public String toString() {
            return this.name;
        }
    
    }

    Note: Take a look at toString() method. This is main thing. This is method used while filtering.

    Adapter for Countries list. Here is nothing new:

    package com.hrupin.sample.filterlist;
    
    import java.util.List;
    
    import android.app.Activity;
    import android.content.Context;
    import android.text.Html;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;
    
    public class CountryListAdapter extends ArrayAdapter<Country> {
        private LayoutInflater vi;
        private static int mResource = R.layout.item_list;
    
        public CountryListAdapter(Activity activity, final List<Country> items) {
            super(activity, mResource, items);
            vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
    
        public static class ViewHolder {
            private TextView textViewItemCountryName;
            private TextView textViewItemCountryArea;
            private TextView textViewItemCountryPopulation;
    
            public ViewHolder(View v) {
                this.textViewItemCountryName = (TextView) v.findViewById(R.id.textViewItemCountryName);
                this.textViewItemCountryArea = (TextView) v.findViewById(R.id.textViewItemCountryArea);
                this.textViewItemCountryPopulation = (TextView) v.findViewById(R.id.textViewItemCountryPopulation);
            }
        }
    
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = vi.inflate(mResource, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
    
            final Country item = getItem(position);
            if (item != null) {
                holder.textViewItemCountryName.setText(Html.fromHtml(item.getName()));
                holder.textViewItemCountryArea.setText(Html.fromHtml("area = " + item.getArea() + " sq.km"));
                holder.textViewItemCountryPopulation.setText(Html.fromHtml("population = " + item.getPopulation()));
    
            }
            return convertView;
        }
    }

    And Activity. Take a look at TextWatcher:

    package com.hrupin.sample.filterlist;
    
    import java.util.List;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.ArrayAdapter;
    import android.widget.EditText;
    import android.widget.ListView;
    
    public class FilterListSampleActivity extends Activity implements TextWatcher {
        
        private static List<Country> countries = Storage.getItems();
        private EditText editTextFilter;
        private ListView listViewCountries;
        private CountryListAdapter adapter;
        
        
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            adapter = new CountryListAdapter(this, countries);
            
            editTextFilter = (EditText)findViewById(R.id.editTextFilter);
            editTextFilter.addTextChangedListener(this);
            
            listViewCountries = (ListView)findViewById(R.id.listViewCountries);
            listViewCountries.setAdapter(adapter);
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s);
        }
    
        @Override
        public void afterTextChanged(Editable s) {}
        
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
    }

    That’s all.

    Download it from github
  • How to remove specific OverlayItem from MapView ItemizedOverlay in Android.

    How to remove specific OverlayItem from MapView ItemizedOverlay in Android.

    This functionality is very needed if you have a lot of items and you need to delete one of them.

    For example: deleting one ATM from ATM’s overlay if user made some action on map.

    It can be implemented by creating remove(int) method in your ItemizedOverlay class.
    Here is MyItemizedOverlay

    package com.hrupin.sample.mappinremoving;
    
    import java.util.ArrayList;
    
    import android.graphics.drawable.Drawable;
    
    import com.google.android.maps.ItemizedOverlay;
    import com.google.android.maps.OverlayItem;
    
    public class MyItemizedOverlay extends ItemizedOverlay {
    
        private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    
        public MyItemizedOverlay(Drawable defaultMarker) {
            super(defaultMarker);
        }
    
        public void addOverlay(OverlayItem overlay) {
            mOverlays.add(overlay);
            populate();
        }
    
        @Override
        protected OverlayItem createItem(int i) {
            return mOverlays.get(i);
        }
    
        @Override
        public int size() {
            return mOverlays.size();
        }
    
        public void remove(int position) {
            mOverlays.remove(position);
            populate();
        }
    
    }
    

    !!!Important. You need to call populate() after item deleting.

    Here is a screenshot of sample Android application:

    This application delete map pin with MAX Latitude. Also you can specify your own criteria

    Here is Activity code. Take a look in onClick method:

    package com.hrupin.sample.mappinremoving;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapView;
    import com.google.android.maps.Overlay;
    import com.google.android.maps.OverlayItem;
    
    import android.graphics.drawable.Drawable;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class StartActivity extends MapActivity implements OnClickListener {
        private static final String TAG = StartActivity.class.getSimpleName();
        private MapView mapView;
        private List<Overlay> mapOverlays;
        private Drawable defaultItemDrawable;
        private MyItemizedOverlay itemizedOverlay;
        private Button buttonRemovePin;
        private static List<MapDataItem> sampleData = new ArrayList<MapDataItem>();
    
        static {
            sampleData.add(new MapDataItem(24.003990, 49.837071));
            sampleData.add(new MapDataItem(36.173357, -85.869141));
            sampleData.add(new MapDataItem(38.822591, -25.664062));
            sampleData.add(new MapDataItem(40.979898, -2.109375));
            sampleData.add(new MapDataItem(43.834527, 21.09375));
            sampleData.add(new MapDataItem(46.316584, 55.898438));
            sampleData.add(new MapDataItem(49.15297, 85.078125));
            sampleData.add(new MapDataItem(50.064192, 117.421875));
            sampleData.add(new MapDataItem(-19.311143, 130.78125));
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            mapView = (MapView) findViewById(R.id.mapView);
            mapView.setBuiltInZoomControls(true);
    
            buttonRemovePin = (Button) findViewById(R.id.buttonRemoveMapPin);
            buttonRemovePin.setOnClickListener(this);
    
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            mapOverlays = mapView.getOverlays();
            mapOverlays.clear();
            mapView.postInvalidate();
            mapView.removeAllViews();
            defaultItemDrawable = this.getResources().getDrawable(R.drawable.default_marker);
            defaultItemDrawable.setBounds(-defaultItemDrawable.getIntrinsicWidth() / 2, -defaultItemDrawable.getIntrinsicHeight(), defaultItemDrawable.getIntrinsicWidth() / 2, 0);
            itemizedOverlay = new MyItemizedOverlay(defaultItemDrawable);
    
            for (int i = 0; i < sampleData.size(); i++) {
                int latitude = (int) (sampleData.get(i).getLatitude() * 1E6);
                int longitude = (int) (sampleData.get(i).getLongitude() * 1E6);
                GeoPoint point = new GeoPoint(latitude, longitude);
                OverlayItem overlayitem = new OverlayItem(point, "Title " + i, "Snippet " + i);
                itemizedOverlay.addOverlay(overlayitem);
            }
            mapOverlays.add(itemizedOverlay);
    
        }
    
        @Override
        protected boolean isRouteDisplayed() {
            // TODO Auto-generated method stub
            return false;
        }
    
        @Override
        public void onClick(View v) {
            List<Overlay> overlays = mapView.getOverlays();
            Log.i(TAG, "Overlays count = " + overlays.size());
            MyItemizedOverlay overlay = (MyItemizedOverlay) overlays.get(0);
            Log.i(TAG, "Item count = " + overlay.size());
            if (overlay.size() > 0) {
                int itemPositionWithMaxLatitude = 0;
                for (int i = 0; i < overlay.size(); i++) {
                    if(overlay.getItem(itemPositionWithMaxLatitude).getPoint().getLatitudeE6() < overlay.getItem(i).getPoint().getLatitudeE6()){
                        itemPositionWithMaxLatitude = i;
                    }
                }
                overlay.remove(itemPositionWithMaxLatitude);
                mapView.invalidate();
            }
    
        }
    }
    

    Don’t forget to handle all exceptions 🙂

    That’s all.

    Download it from github
  • How to create filter for ListView items in Android.

    How to create filter for ListView items in Android.

    Please. have a look at screenshot.

    Here I want to show you how to create filter for ListView items. In this post my ListView contains simple strings.
    As you see there the EditText on the screen. User can type text in this EditText and ListView will filter using user’s text in EditText.

    This code works very fast.

    Please have a look source code:

    package com.hrupin.sample.filterlist;
    
    import java.util.List;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.ArrayAdapter;
    import android.widget.EditText;
    import android.widget.ListView;
    
    public class FilterListSampleActivity extends Activity implements TextWatcher {
        
        private static List<String> countries = Storage.getCountries();
        private EditText editTextFilter;
        private ListView listViewCountries;
        private ArrayAdapter<String> adapter;
        
        
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
            
            editTextFilter = (EditText)findViewById(R.id.editTextFilter);
            editTextFilter.addTextChangedListener(this);
            
            listViewCountries = (ListView)findViewById(R.id.listViewCountries);
            listViewCountries.setAdapter(adapter);
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s);
        }
    
        @Override
        public void afterTextChanged(Editable s) {}
        
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
    }

    All functionality goes around TextChangedListener which added in EditText.

    In the next post (How to create filter for ListView items in Android. Part-2. List with custom adapter.) I’ll show you how to create filter for ListView with custom adapter and complex objects in it.

    That’s all.
    Here you can download the source code of sample Android project

    Download it from github
  • How to create custom groupIndicator for ExpandableListView group

    How to create custom groupIndicator for ExpandableListView group

    Here is tutorial How to create custon groupIndicator for ExpandableListView in Andriod.
    Here is screenshot:

    To do it you need:

    1. Create 9-patch images for normal and expanded state
    2. Create selector with this 9-patch images

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_expanded="true" android:drawable="@drawable/group_indicator_expanded" />
        <item android:drawable="@drawable/group_indicator" />
    </selector>

    3. Set this selector as groupIndicator for ExpandableListView

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <ExpandableListView
            android:id="@+id/expandableListView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:groupIndicator="@drawable/group_indicator_selector" >
        </ExpandableListView>
    </LinearLayout>

    That’s all.

    Here you can download the source code of sample Android project

    Download it from github
  • How to get sound effect when button clicked in Android or playing with SoundPool

    How to get sound effect when button clicked in Android or playing with SoundPool

    Here I want to share you a simple code.

    If you need to get sound effect for button click or some other event in your Android application you find what you need.

    Below you can download source code of this sample Android project

    Android SDK provide SoundPool class for it. Lets see how it works.
    I’ve created simple application for you. Below you can see screenshot. It is just button which can fire sound effect when it clicked.

    Here is sourcecode of Android activity:

    package com.hrupin.sample.soundeffects;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class SoundEffectsInAndroidActivity extends Activity implements OnClickListener {
        private Button button;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            // init Effects class
            Effects.getInstance().init(this);
            button = (Button)findViewById(R.id.button1);
            button.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            Effects.getInstance().playSound(Effects.SOUND_1);
        }
    }

    I’ve created Effects class as wrapper for SoundPool.
    Here is sourcecode:

    package com.hrupin.sample.soundeffects;
    
    import java.util.HashMap;
    
    import android.content.Context;
    import android.media.AudioManager;
    import android.media.SoundPool;
    import android.util.Log;
    import android.widget.Toast;
    
    public class Effects {
    
        private static final String TAG = Effects.class.toString();
    
        private static final Effects INSTANCE = new Effects();
    
        // Sound ID can't be 0 (zero)
        public static final int SOUND_1 = 1;
    
        private Effects() {
    
        }
    
        public static Effects getInstance() {
            return INSTANCE;
        }
    
        private SoundPool soundPool;
        private HashMap<Integer, Integer> soundPoolMap;
        int priority = 1;
        int no_loop = 0;
        private int volume;
        float normal_playback_rate = 1f;
    
        private Context context;
    
        public void init(Context context) {
            this.context = context;
            soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
            soundPoolMap = new HashMap<Integer, Integer>();
            soundPoolMap.put(SOUND_1, soundPool.load(context, R.raw.sound_1, 1));
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            volume = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
        }
    
        public void playSound(int soundId) {
            Log.i(TAG, "!!!!!!!!!!!!!! playSound_1 !!!!!!!!!!");
            soundPool.play(soundId, volume, volume, priority, no_loop, normal_playback_rate);
            Toast.makeText(context, "Now you can hear sound effect!", Toast.LENGTH_LONG).show();
        }
    }
    

    Notice, that SOUND_1 constant can’t be 0 (zero).
    That’s all for this sample.
    Please, write comment if you have some questions. Also you can download the full sourcecode.

    Here you can download the source code of simple Android project.

    Download it from github