Thursday, May 10, 2018

Change background of custom drawable

1.listbox_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/listbg">
    <shape android:shape="rectangle" >
        <stroke
            android:width="2dip"
            android:color="#ffffff" />
        <solid android:color="#0000"/>
    </shape>
</item>
</layer-list>


2.MainActivity.java

Drawable tempDrawable = getResources().getDrawable(R.drawable.listbox_bg);
LayerDrawable bubble = (LayerDrawable) tempDrawable;
GradientDrawable solidColor = (GradientDrawable) bubble.findDrawableByLayerId(R.id.listbg);
solidColor.setColor(Color.parseColor(colorCode));

ListView custom item with RadioButton

Creating ListView that has RadioButton in ListView custom item.

Here are the key ideas
  • when a RadioButton is checked we must call notifyDataSetChanged(), so that all views get updated.
  • when a RadioButton is checked we must set a selectedPosition, to keep track of which RadioButton is selected
  • Views are recycled inside ListViews. Therefore, their absolute position changes in the ListView. Therefore, inside ListAdapter#getView(), we must call setTag() on each RadioButton. This allows us to determine the current position of the RadioButton in the list when the RadioButton is clicked.
  • RadioButton#setChecked() must be updated inside getView() for new or pre-existing Views.

1.row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ll_parent">

    <RadioButton
        android:id="@+id/radio"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:clickable="false"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:clickable="false"/>
</LinearLayout>

To make RadioButton works correctly when click, you need to set android:clickable="false" to child elements.

2.activity_list_view_custom_item_with_radio_button.xml

<?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" >

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:choiceMode="singleChoice"/>

</LinearLayout>

3.ListViewCustomItemWithRadioButtonActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.ArrayList;

public class ListViewCustomItemWithRadioButtonActivity extends AppCompatActivity {

    private int selected_pos = -1;

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

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

        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0 ; i < 50; i++){
            arrayList.add("Item : " + (i + 1));
        }

        MyAdapter arrayAdapter = new MyAdapter(arrayList);
        listView.setAdapter(arrayAdapter);
    }

    private class MyAdapter extends BaseAdapter {

        private ArrayList< String>arrayList;

        private MyAdapter(ArrayList< String>arrayList){
            this.arrayList = arrayList;
        }

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

        @Override
        public Object getItem(int position) {
            return arrayList.get(position);
        }

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

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null){
                view = View.inflate(ListViewCustomItemWithRadioButtonActivity.this, R.layout.row, null);
            }
            final LinearLayout ll_parent = (LinearLayout) view.findViewById(R.id.ll_parent);
            final RadioButton radioButton = (RadioButton) view.findViewById(R.id.radio);
            radioButton.setText(arrayList.get(position));
            radioButton.setChecked(position == selected_pos);
            radioButton.setTag(position);
            ll_parent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selected_pos = (Integer) v.findViewById(R.id.radio).getTag();
                    notifyDataSetChanged();
                }
            });
            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText("Position : ".concat(String.valueOf(position)));

            return view;
        }
    }
}

Friday, June 16, 2017

Save List<Object> to SharedPreferences

You can use GSON to convert Object -> JSON(.toJSON) and JSON -> Object(.fromJSON).

1.build.gradle

dependencies {
    ...
    compile 'com.google.code.gson:gson:2.7'
}

2.MainActivity.java

public class Main2Activity extends AppCompatActivity {

    private final String PREFS_TAG = "APP_PRE";
    private final String PRODUCT_TAG = "APP_DATA";

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

    private List<MatchItem> getDataFromSharedPreferences(){
        Gson gson = new Gson();
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
        String jsonPreferences = sharedPref.getString(PRODUCT_TAG, "[]");

        Type type = new TypeToken<List<MatchItem>>() {}.getType();
        return gson.fromJson(jsonPreferences, type);
    }

    private void setDataFromSharedPreferences(List<MatchItem> list){
        Gson gson = new Gson();
        String jsonString = gson.toJson(list);

        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

        editor.putString(PRODUCT_TAG, jsonString).apply();
        editor.commit();
    }
}

Wednesday, May 24, 2017

3D-flip Animation



1. FlipListener.java

import android.animation.ValueAnimator;
import android.view.View;


public class FlipListener implements ValueAnimator.AnimatorUpdateListener {

    private final View mFrontView;
    private final View mBackView;
    private boolean mFlipped;

    public FlipListener(final View front, final View back) {
        this.mFrontView = front;
        this.mBackView = back;
        this.mBackView.setVisibility(View.GONE);
    }

    @Override
    public void onAnimationUpdate(final ValueAnimator animation) {
        final float value = animation.getAnimatedFraction();
        final float scaleValue = 0.625f + (1.5f * (value - 0.5f) * (value - 0.5f));

        if(value <= 0.5f){
            this.mFrontView.setRotationY(180 * value);
            this.mFrontView.setScaleX(scaleValue);
            this.mFrontView.setScaleY(scaleValue);
            if(mFlipped){
                setStateFlipped(false);
            }
        } else {
            this.mBackView.setRotationY(-180 * (1f- value));
            this.mBackView.setScaleX(scaleValue);
            this.mBackView.setScaleY(scaleValue);
            if(!mFlipped){
                setStateFlipped(true);
            }
        }
    }

    private void setStateFlipped(boolean flipped) {
        mFlipped = flipped;
        this.mFrontView.setVisibility(flipped ? View.GONE : View.VISIBLE);
        this.mBackView.setVisibility(flipped ? View.VISIBLE : View.GONE);
    }
}

2. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="50dp"
    android:paddingRight="50dp"
    android:background="#45a39c">


    <RelativeLayout
        android:id="@+id/icon_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/icon_back"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/card_back" />

        <ImageView
            android:id="@+id/icon_front"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/card_front" />

    </RelativeLayout>
</LinearLayout>

3. MianActivity.java

import android.animation.ValueAnimator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.ream.inex.test.FlipListener;

public class MainActivity extends Activity implements View.OnClickListener{

    ValueAnimator mFlipAnimator;
    private boolean is_front = true;

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

        RelativeLayout icon_container = (RelativeLayout) findViewById(R.id.icon_container);
        ImageView icon_front = (ImageView) findViewById(R.id.icon_front);
        ImageView icon_back = (ImageView) findViewById(R.id.icon_back);

        mFlipAnimator = ValueAnimator.ofFloat(0f, 1f);
        mFlipAnimator.addUpdateListener(new FlipListener(icon_front, icon_back));

        icon_container.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (is_front) {
            mFlipAnimator.start();
        } else {
            mFlipAnimator.reverse();
        }
        is_front =! is_front;
    }

}

Get the height of soft keyboard of device


I. AdjustResize and AdjustPan

You can get the height of soft keyboard that use windowSoftInputMode="adjustResize|adjustPan"   by Viewtree Observer and global layout listener, just try below mentioned steps
    1. Get the root view of your layout
    2. Get the Viewtree observer for this root, and add a global layout listener on top of this.
Now whenever soft keyboard is displayed android will re-size your screen and you will receive call on your listener. That's it only thing you now need to do is calculate difference between height which your root view has after re-size and original size. If difference is more then 150 consider this as a keyboard has been inflated.

In Activity class :
final LinearLayout ll_main = (LinearLayout) findViewById(R.id.ll_main);
final Window mRootWindow = getWindow();
        ll_main.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
            public void onGlobalLayout(){
                int screenHeight = ll_main.getRootView().getHeight();
                Rect r = new Rect();
                View view = mRootWindow.getDecorView();
                view.getWindowVisibleDisplayFrame(r);

                int keyBoardHeight = screenHeight - r.bottom;
            }
        });

II. AdjustNothing

If you want to get the height of soft keyboard that use windowSoftInputMode="adjustNothing"

1. popupwindow.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popuplayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="horizontal"/>

2. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activitylayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

        <TextView
      android:id="@+id/info_label"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textColor="@android:color/black"
            android:textSize="16dp"
            android:text="@string/info">

        </TextView>

        <EditText
      android:id="@+id/input_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            >
        </EditText>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:orientation="horizontal">

            <TextView
          android:id="@+id/height_label"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:textColor="@android:color/black"
                android:textSize="16dp"
                android:text="@string/height">

            </TextView>

            <TextView
          android:id="@+id/height_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@android:color/black"
                android:textSize="16dp"
                android:text="0">

            </TextView>

        </LinearLayout>

    </LinearLayout>

    <View 
  android:id="@+id/keyboard"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentBottom="true"
        android:background="#0000ff"/>
</RelativeLayout>


3. KeyboardHeightObserver.java

public interface KeyboardHeightObserver {

    /** 
     * Called when the keyboard height has changed, 0 means keyboard is closed,
     * >= 1 means keyboard is opened.
     * 
     * @param height        The height of the keyboard in pixels
     * @param orientation   The orientation either: Configuration.ORIENTATION_PORTRAIT or 
     *                      Configuration.ORIENTATION_LANDSCAPE
     */
    void onKeyboardHeightChanged(int height, int orientation);
}

4. KeyboardHeightProvider.java

/**
 * The keyboard height provider, this class uses a PopupWindow
 * to calculate the window height when the floating keyboard is opened and closed. 
 */
public class KeyboardHeightProvider extends PopupWindow {

    /** The tag for logging purposes */
    private final static String TAG = "sample_KeyboardHeightProvider";

    /** The keyboard height observer */
    private KeyboardHeightObserver observer;

    /** The cached landscape height of the keyboard */
    private int keyboardLandscapeHeight;

    /** The cached portrait height of the keyboard */
    private int keyboardPortraitHeight;

    /** The view that is used to calculate the keyboard height */
    private View popupView;

    /** The parent view */
    private View parentView;

    /** The root activity_main that uses this KeyboardHeightProvider */
    private Activity activity;

    /** 
     * Construct a new KeyboardHeightProvider
     * 
     * @param activity The parent activity_main
     */
    public KeyboardHeightProvider(Activity activity) {
  super(activity);
        this.activity = activity;

        LayoutInflater inflator = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        this.popupView = inflator.inflate(R.layout.popupwindow, null, false);
        setContentView(popupView);

        setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_RESIZE | LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

        parentView = activity.findViewById(android.R.id.content);

        setWidth(0);
        setHeight(LayoutParams.MATCH_PARENT);

        popupView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {
                    if (popupView != null) {
                        handleOnGlobalLayout();
                    }
                }
            });
    }

    /**
     * Start the KeyboardHeightProvider, this must be called after the onResume of the Activity.
     * PopupWindows are not allowed to be registered before the onResume has finished
     * of the Activity.
     */
    public void start() {

        if (!isShowing() && parentView.getWindowToken() != null) {
            setBackgroundDrawable(new ColorDrawable(0));
            showAtLocation(parentView, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    /**
     * Close the keyboard height provider, 
     * this provider will not be used anymore.
     */
    public void close() {
        this.observer = null;
        dismiss();
    }

    /** 
     * Set the keyboard height observer to this provider. The 
     * observer will be notified when the keyboard height has changed. 
     * For example when the keyboard is opened or closed.
     * 
     * @param observer The observer to be added to this provider.
     */
    public void setKeyboardHeightObserver(KeyboardHeightObserver observer) {
        this.observer = observer;
    }
   
    /**
     * Get the screen orientation
     *
     * @return the screen orientation
     */
    private int getScreenOrientation() {
        return activity.getResources().getConfiguration().orientation;
    }

    /**
     * Popup window itself is as big as the window of the Activity. 
     * The keyboard can then be calculated by extracting the popup view bottom 
     * from the activity_main window height.
     */
    private void handleOnGlobalLayout() {

        Point screenSize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(screenSize);

        Rect rect = new Rect();
        popupView.getWindowVisibleDisplayFrame(rect);

        // REMIND, you may like to change this using the fullscreen size of the phone
        // and also using the status bar and navigation bar heights of the phone to calculate
        // the keyboard height. But this worked fine on a Nexus.
        int orientation = getScreenOrientation();
        int keyboardHeight = screenSize.y - rect.bottom;
        
        if (keyboardHeight == 0) {
            notifyKeyboardHeightChanged(0, orientation);
        }
        else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            this.keyboardPortraitHeight = keyboardHeight; 
            notifyKeyboardHeightChanged(keyboardPortraitHeight, orientation);
        } 
        else {
            this.keyboardLandscapeHeight = keyboardHeight; 
            notifyKeyboardHeightChanged(keyboardLandscapeHeight, orientation);
        }
    }

    /**
     *
     */
    private void notifyKeyboardHeightChanged(int height, int orientation) {
        if (observer != null) {
            observer.onKeyboardHeightChanged(height, orientation);
        }
    }
}

5. MainActivity.java

/**
 * MainActivity that initialises the keyboardheight 
 * provider and observer. 
 */
public final class MainActivity extends AppCompatActivity implements KeyboardHeightObserver {

    /** Tag for logging */
    private final static String TAG = "sample_MainActivity";

    /** The keyboard height provider */
    private KeyboardHeightProvider keyboardHeightProvider;

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        keyboardHeightProvider = new KeyboardHeightProvider(this);

        // make sure to start the keyboard height provider after the onResume
        // of this activity_main. This is because a popup window must be initialised
        // and attached to the activity_main root view.
        View view = findViewById(R.id.activitylayout);
        view.post(new Runnable() {
                public void run() {
                    keyboardHeightProvider.start();
                }
            });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onPause() {
        super.onPause();
        keyboardHeightProvider.setKeyboardHeightObserver(null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onResume() {
        super.onResume();
        keyboardHeightProvider.setKeyboardHeightObserver(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        keyboardHeightProvider.close();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {

        String or = orientation == Configuration.ORIENTATION_PORTRAIT ? "portrait" : "landscape";
        Log.i(TAG, "onKeyboardHeightChanged in pixels: " + height + " " + or);

        TextView tv = (TextView)findViewById(R.id.height_text);
        tv.setText(Integer.toString(height) + " " + or);

        // color the keyboard height view, this will stay when you close the keyboard
        View view = findViewById(R.id.keyboard);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)view .getLayoutParams();
        params.height = height;
    }
}

Wednesday, May 17, 2017

Volley with HTTPS


1.Add volley to build.gradle dependencies

    dependencies {
        ...
        compile 'com.android.volley:volley:1.0.0'
    }

2.Add new android resource directory (raw)

     Under res, add android resource directory named raw, and then add test.bks to raw directory.

3.Add internet permission to AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET"/>

4.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#5d9767"
    android:gravity="center"
    android:fillViewport="true"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</ScrollView>

5.MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * @ Created by Huo Chhunleng on 17/Mar/2017.
 */

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;
    private Map<String, String> params = new HashMap<String, String>();

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

        mTextView = (TextView) findViewById(R.id.textView);

        String url = "https://feeds.citibikenyc.com/stations/stations.json";

        HurlStack hurlStack = new HurlStack() {
            @Override
            protected HttpURLConnection createConnection(URL url) throws IOException {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
                try {
                    httpsURLConnection.setSSLSocketFactory(getSSLSocketFactory());
                    httpsURLConnection.setHostnameVerifier(getHostnameVerifier());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return httpsURLConnection;
            }
        };

        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new JSONObject(params), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    mTextView.setText(response.toString(5));
                } catch (JSONException e) {
                    mTextView.setText(e.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextView.setText(error.toString());
            }
        });

        final RequestQueue requestQueue = Volley.newRequestQueue(this, hurlStack);

        requestQueue.add(jsonObjectRequest);
    }

    // Let's assume your server app is hosting inside a server machine
    // which has a server certificate in which "Issued to" is "localhost",for example.
    // Then, inside verify method you can verify "localhost".
    // If not, you can temporarily return true
    private HostnameVerifier getHostnameVerifier() {
        return new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                //return true; // verify always returns true, which could cause insecure network traffic due to trusting TLS/SSL server certificates for wrong hostnames
                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("localhost", session);
            }
        };
    }

    private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
        final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
        return new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return originalTrustManager.getAcceptedIssuers();
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        try {
                            if (certs != null && certs.length > 0){
                                certs[0].checkValidity();
                            } else {
                                originalTrustManager.checkClientTrusted(certs, authType);
                            }
                        } catch (CertificateException e) {
                            Log.w("checkClientTrusted", e.toString());
                        }
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        try {
                            if (certs != null && certs.length > 0){
                                certs[0].checkValidity();
                            } else {
                                originalTrustManager.checkServerTrusted(certs, authType);
                            }
                        } catch (CertificateException e) {
                            Log.w("checkServerTrusted", e.toString());
                        }
                    }
                }
        };
    }

    private SSLSocketFactory getSSLSocketFactory()
            throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = getResources().openRawResource(R.raw.test); // this cert file stored in \app\src\main\res\raw folder path

        Certificate ca = cf.generateCertificate(caInput);
        caInput.close();

        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, wrappedTrustManagers, null);

        return sslContext.getSocketFactory();
    }
}

Download preject here.

RadioGroup in ListView

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.user.test.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center"
        android:text="Cloud Survey"
        android:textSize="18sp"
        android:textColor="#000"/>

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

2.layout_group.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="16sp"
        android:textColor="#353535"/>

    <LinearLayout
        android:id="@+id/ll_questions"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:orientation="vertical"/>
</LinearLayout>

3.layout_question.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_question_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:textColor="#000"/>
    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/radio_button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Bad"/>
        <RadioButton
            android:id="@+id/radio_button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Good"/>
        <RadioButton
            android:id="@+id/radio_button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Better"/>
        <RadioButton
            android:id="@+id/radio_button4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Best"/>
    </RadioGroup>

</LinearLayout>

4.GroupItem.java

public class GroupItem {
    private String group_id;
    private String group_name;
    private List<QuestionItem> LIST_QUESTION;

    public String getGroup_id() {
        return group_id;
    }

    public void setGroup_id(String group_id) {
        this.group_id = group_id;
    }

    public String getGroup_name() {
        return group_name;
    }

    public void setGroup_name(String group_name) {
        this.group_name = group_name;
    }

    public List<QuestionItem> getLIST_QUESTION() {
        return LIST_QUESTION;
    }

    public void setLIST_QUESTION(List<QuestionItem> LIST_QUESTION) {
        this.LIST_QUESTION = LIST_QUESTION;
    }
}

5.QuestionItem.java

/**
 * Create by User on 16/May/2017.
 */

public class QuestionItem {
    private String question_id;
    private String question_name;
    private int answer = -1; //-1 means not yet answer

    public String getQuestionId() {
        return question_id;
    }

    public void setQuestionId(String question_id) {
        this.question_id = question_id;
    }

    public String getQuestionName() {
        return question_name;
    }

    public void setQuestionName(String question_name) {
        this.question_name = question_name;
    }

    public int getAnswer() {
        return answer;
    }

    public void setAnswer(int answer) {
        this.answer = answer;
    }
}

6.QuestionAdapter.java

public class QuestionAdapter extends BaseAdapter{

    private Context context;
    private List<GroupItem> LIST_GROUP;
    public QuestionAdapter(Context context, List<GroupItem> LIST_GROUP){
        this.context = context;
        this.LIST_GROUP = LIST_GROUP;
    }

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

    @Override
    public Object getItem(int position) {
        return LIST_GROUP.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null){
            convertView = inflater.inflate(R.layout.layout_group, parent, false);
        }
        GroupItem groupItem = LIST_GROUP.get(position);
        TextView tv_group = (TextView) convertView.findViewById(R.id.tv_group);
        tv_group.setText(groupItem.getGroup_name());
        LinearLayout ll_questions = (LinearLayout) convertView.findViewById(R.id.ll_questions);

        ll_questions.removeAllViews();
        for (int i = 0; i<groupItem.getLIST_QUESTION().size(); i++){

            final QuestionItem questionItem = groupItem.getLIST_QUESTION().get(i);
            LayoutInflater inflater1 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View question_view = inflater1.inflate(R.layout.layout_question, null);
            TextView tv_question_name = (TextView) question_view.findViewById(R.id.tv_question_name);
            tv_question_name.setText(questionItem.getQuestionName());

            RadioGroup radioGroup = (RadioGroup) question_view.findViewById(R.id.radio_group);
            if (questionItem.getAnswer() == -1){
                radioGroup.clearCheck();
            }else {
                ((RadioButton)radioGroup.getChildAt(questionItem.getAnswer())).setChecked(true);
            }

            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    switch (checkedId){
                        case R.id.radio_button1 :
                            questionItem.setAnswer(0);
                            break;
                        case R.id.radio_button2 :
                            questionItem.setAnswer(1);
                            break;
                        case R.id.radio_button3 :
                            questionItem.setAnswer(2);
                            break;
                        case R.id.radio_button4 :
                            questionItem.setAnswer(3);
                            break;
                    }
                    //notifyDataSetChanged();
                }
            });
            ll_questions.addView(question_view);
        }

        return convertView;
    }
}

7.MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        List<GroupItem> LIST_GROUP = new ArrayList<>();
        for (int i = 0; i<3; i++){
            GroupItem groupItem = new GroupItem();
            groupItem.setGroup_name("Group " + (i+1));

            List<QuestionItem> LIST_QUESTION = new ArrayList<>();
            for (int j = 0; j < 4; j++){
                QuestionItem questionItem = new QuestionItem();
                questionItem.setQuestionName("Question " + (j+1));
                LIST_QUESTION.add(questionItem);
            }
            groupItem.setLIST_QUESTION(LIST_QUESTION);
            LIST_GROUP.add(groupItem);
        }


        ListView listView = (ListView) findViewById(R.id.listview);
        QuestionAdapter adapter = new QuestionAdapter(MainActivity.this, LIST_GROUP);
        listView.setAdapter(adapter);
    }
}