ImageView as CheckBox in ListView

Screenshot_2014-11-30-02-02-51
Favorite or not? Selected, not selected? As Android developer I faced this issue many times. This code snippet shows how to demonstrate imageview as checkbox. You just use custom list adapter which extends BaseAdapter:

public class TopDrugstoresAdapter extends BaseAdapter {
.....

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

.....

            if (drugstore.getFavorite()) {
                ivStar.setImageResource(R.drawable.ic_active_star);
            }
            ivStar.setTag(drugstore);

            ivStar.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Drugstore drugstore = (Drugstore) ivStar.getTag();

                    if (drugstore.getFavorite()) {
                        drugstore.setFavorite(false);
                        ivStar.setImageResource(R.drawable.ic_inactive_star);
                    } else {
                        drugstore.setFavorite(true);
                        ivStar.setImageResource(R.drawable.ic_active_star);
                    }
                }
            });

.....

    }

}

Error on Eclipse

When I tried to import project into Eclipse, I encountered following error:

Could not set the project description for ‘MedApp’ because the project description file(.project) is out of sync with the file system.
Reason: Could not set the project description for ‘MedApp’ because the project description file(.project) is out of sync with the file system.

Searched for solution and found this solution. This solution says that project should be imported in this way:
File->Import->General->Existing Projects into Workspace.
Imported project but now it is giving another error:

Unparsed aapt error(s)! Check the console for output. MedApp line 1 Android ADT Problem

android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application

When I tried to show progress dialog when content is loading through http channel. It gave this error:
android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application
I was using like this:

Context mContext;
    ProgressDialog pDialog;

    public AuthTask(Context context) {
        mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(mContext);
        pDialog.setMessage(mContext.getString(R.string.authorization));
        pDialog.setCancelable(false);
        pDialog.show();
    }

Solution: On Activity, where I am starting this task, I have created public static instance of this activity

    public static Activity activity;
...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);

        context = getApplicationContext();
        activity = SignInActivity.this;

Instead of mContext, I used copy of that activity – SignInActivity.activity

Context mContext;
    ProgressDialog pDialog;

    public AuthTask(Context context) {
        mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(SignInActivity.activity);
        pDialog.setMessage(mContext.getString(R.string.authorization));
        pDialog.setCancelable(false);
        pDialog.show();
    }

Anthem of Java coders

SPOKEN:
In the cubicles representin’ for my JAVA homies…
In by nine, out when the deadlines are met, check it.

CHORUS:
We code hard in these cubicles
My style’s nerd-chic, I’m a programmin’ freak
We code hard in these cubicles
Only two hours to your deadline? Don’t sweat my technique.

Sippin’ morning coffee with that JAVA swirl.
Born to code; my first words were “Hello World”
Since 95, been JAVA codin’ stayin’ proud
Started on floppy disks, now we take it to the cloud.

On my desktop, JAVA’s what’s bobbin’ and weavin’
We got another winning app before I get to OddEven.
Blazin’ code like a forest fire, climbin’ a tree
Setting standards like I Triple E….

Boot it on up, I use the force like Luke,
Got so much love for my homeboy Duke.
GNU Public Licensed, it’s open source,
Stop by my desk when you need a crash course

Written once and my script runs anywhere,
Straight thuggin’, mean muggin’ in my Aeron chair.
All the best lines of code, you know I wrote ‘em
I’ll run you out of town on your dial-up modem.

CHORUS:
‘Cause…
We code hard in these cubicles
Me and my crew code hyphy hardcore
We code hard in these cubicles
It’s been more than 10 years since I’ve seen the 404.

Inheriting a project can make me go beeee-serk
Ain’t got four hours to transfer their Framework.
The cleaners killed the lights, Man, that ain’t nice,
Gonna knock this program out, just like Kimbo Slice

I program all night, just like a champ,
Look alive under this IKEA lamp.
I code HARDER in the midnight hour,
E7 on the vending machine fuels my power.

Ps3 to Smartphones, our code use never ends,
JAVA’s there when I beat you in “Words with Friends”.
My developing skills are so fresh please discuss,
You better step your game up on that C++.

We know better than to use Dot N-E-T,
Even Dan Brown can’t code as hard as me.
You know JAVA’s gettin’ bigger, that’s a promise not a threat,
Let me code it on your brain

WHISPERED:
so you’ll never forget.

CHORUS:
We code hard in these cubicles,
it’s the core component…of what we implement.
We code hard in these cubicles,
Straight to your JAVA Runtime Environment.

We code hard in these cubicles,
Keep the syntax light and the algorithm tight.
We code hard in these cubicles,
Gotta use JAVA if it’s gonna run right.

We code hard in these cubicles
JAVA keeps adapting, you know it’s built to last.
We code hard in these cubicles,
Robust and secure, so our swag’s on blast

CODE HARD

Android. Generate hash key for Facebook

This code logs out device hash key to use Facebook API:

        // Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager()
                    .getPackageInfo("com.globalsolutions.medapp",
                            PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d(MainActivity.LOG_TAG,
                        Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }

Java. Color interpolator

    // used to take colors mix according to proportion
    private int interpolateColor(final int a, final int b,
            final float proportion) {
        final float[] hsva = new float[3];
        final float[] hsvb = new float[3];
        Color.colorToHSV(a, hsva);
        Color.colorToHSV(b, hsvb);
        for (int i = 0; i < 3; i++) {
            hsvb[i] = interpolate(hsva[i], hsvb[i], proportion);
        }
        return Color.HSVToColor(hsvb);
    }

    private float interpolate(final float a, final float b,
            final float proportion) {
        return (a + ((b - a) * proportion));
    }

Android. Change color using SeekBar + Color interpolator

        // initialize color changer seekbar and set change listener
        sbChangeColor = (SeekBar) findViewById(R.id.sbChangeColor);
        sbChangeColor.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {

                // change top left rectange background color according
                // to seekbar progress from red to blue
                llLeftTop.setBackgroundColor(interpolateColor(redColor,
                        blueColor, seekBar.getProgress() / 100f));

                // change middle right rectange background color according
                // to seekbar progress from blue to red
                llRightMiddle.setBackgroundColor(interpolateColor(blueColor,
                        redColor, seekBar.getProgress() / 100f));

            }
        });
.....
    // used to take colors mix according to proportion
    private int interpolateColor(final int a, final int b,
            final float proportion) {
        final float[] hsva = new float[3];
        final float[] hsvb = new float[3];
        Color.colorToHSV(a, hsva);
        Color.colorToHSV(b, hsvb);
        for (int i = 0; i < 3; i++) {
            hsvb[i] = interpolate(hsva[i], hsvb[i], proportion);
        }
        return Color.HSVToColor(hsvb);
    }

    private float interpolate(final float a, final float b,
            final float proportion) {
        return (a + ((b - a) * proportion));
    }

Android. Dialog with custom layout. Closing dialog implemented

    private void showMoreInfoDialog() {

        // initialize dialog
        // using res/styles.xml - dialog_more_about_style
        // this style helps to turn off title area in dialog
        final Dialog dialog = new Dialog(MainActivity.this,
                R.style.dialog_more_about_style);
        // set dialog's custom layout
        dialog.setContentView(R.layout.dialog_more_info);

        // Clickable text view: Visit MoMA
        TextView tvVisitMoma = (TextView) dialog.findViewById(R.id.tvVisitMoma);
        tvVisitMoma.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // open MoMA website in web browser
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(URL_MOMA));
                startActivity(i);

                // close dialog if user visits MoMA's website
                dialog.dismiss();
            }
        });

        // Clickable text view: Not now
        TextView tvNotNow = (TextView) dialog.findViewById(R.id.tvNotNow);
        tvNotNow.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // close custom dialog
                dialog.dismiss();
            }
        });

        // show more information dialog
        dialog.show();
    }
    <style name="dialog_more_about_style" parent="android:style/Theme.Dialog">
        <item name="android:windowBackground">@null</item>
        <item name="android:windowNoTitle">true</item>
    </style>

Android. XMLPullParser example

class XMLResponseHandler implements ResponseHandler<List<String>> {

    private static final String MAGNITUDE_TAG = "magnitude";
    private static final String LONGITUDE_TAG = "lng";
    private static final String LATITUDE_TAG = "lat";
    private String mLat, mLng, mMag;
    private boolean mIsParsingLat, mIsParsingLng, mIsParsingMag;
    private final List<String> mResults = new ArrayList<String>();

    @Override
    public List<String> handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {
        try {

            // Create the Pull Parser
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xpp = factory.newPullParser();

            // Set the Parser's input to be the XML document in the HTTP Response
            xpp.setInput(new InputStreamReader(response.getEntity()
                    .getContent()));
           
            // Get the first Parser event and start iterating over the XML document
            int eventType = xpp.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {

                if (eventType == XmlPullParser.START_TAG) {
                    startTag(xpp.getName());
                } else if (eventType == XmlPullParser.END_TAG) {
                    endTag(xpp.getName());
                } else if (eventType == XmlPullParser.TEXT) {
                    text(xpp.getText());
                }
                eventType = xpp.next();
            }
            return mResults;
        } catch (XmlPullParserException e) {
        }
        return null;
    }

    public void startTag(String localName) {
        if (localName.equals(LATITUDE_TAG)) {
            mIsParsingLat = true;
        } else if (localName.equals(LONGITUDE_TAG)) {
            mIsParsingLng = true;
        } else if (localName.equals(MAGNITUDE_TAG)) {
            mIsParsingMag = true;
        }
    }

    public void text(String text) {
        if (mIsParsingLat) {
            mLat = text.trim();
        } else if (mIsParsingLng) {
            mLng = text.trim();
        } else if (mIsParsingMag) {
            mMag = text.trim();
        }
    }

    public void endTag(String localName) {
        if (localName.equals(LATITUDE_TAG)) {
            mIsParsingLat = false;
        } else if (localName.equals(LONGITUDE_TAG)) {
            mIsParsingLng = false;
        } else if (localName.equals(MAGNITUDE_TAG)) {
            mIsParsingMag = false;
        } else if (localName.equals("earthquake")) {
            mResults.add(MAGNITUDE_TAG + ":" + mMag + "," + LATITUDE_TAG + ":"
                    + mLat + "," + LONGITUDE_TAG + ":" + mLng);
            mLat = null;
            mLng = null;
            mMag = null;
        }
    }
}

Android. Networking using Java socket

Using sockets

    private class HttpGetTask extends AsyncTask<Void, Void, String> {

        private static final String HOST = "api.geonames.org";

        // Get your own user name at http://www.geonames.org/login
        private static final String USER_NAME = "aporter";
        private static final String HTTP_GET_COMMAND = "GET /earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username="
                + USER_NAME
                + " HTTP/1.1"
                + "\n"
                + "Host: "
                + HOST
                + "\n"
                + "Connection: close" + "\n\n";

        private static final String TAG = "HttpGet";

        @Override
        protected String doInBackground(Void... params) {
            Socket socket = null;
            String data = "";

            try {
                socket = new Socket(HOST, 80);
                PrintWriter pw = new PrintWriter(new OutputStreamWriter(
                        socket.getOutputStream()), true);
                pw.println(HTTP_GET_COMMAND);

                data = readStream(socket.getInputStream());

            } catch (UnknownHostException exception) {
                exception.printStackTrace();
            } catch (IOException exception) {
                exception.printStackTrace();
            } finally {
                if (null != socket)
                    try {
                        socket.close();
                    } catch (IOException e) {
                        Log.e(TAG, "IOException");
                    }
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            mTextView.setText(result);
        }

        private String readStream(InputStream in) {
            BufferedReader reader = null;
            StringBuffer data = new StringBuffer();
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    data.append(line);
                }
            } catch (IOException e) {
                Log.e(TAG, "IOException");
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        Log.e(TAG, "IOException");
                    }
                }
            }
            return data.toString();
        }

HttpUrlConnection

private class HttpGetTask extends AsyncTask<Void, Void, String> {

        private static final String TAG = "HttpGetTask";

        // Get your own user name at http://www.geonames.org/login
        private static final String USER_NAME = "aporter";
        private static final String URL = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username="
                + USER_NAME;

        @Override
        protected String doInBackground(Void... params) {
            String data = "";
            HttpURLConnection httpUrlConnection = null;

            try {
                httpUrlConnection = (HttpURLConnection) new URL(URL)
                        .openConnection();

                InputStream in = new BufferedInputStream(
                        httpUrlConnection.getInputStream());

                data = readStream(in);

            } catch (MalformedURLException exception) {
                Log.e(TAG, "MalformedURLException");
            } catch (IOException exception) {
                Log.e(TAG, "IOException");
            } finally {
                if (null != httpUrlConnection)
                    httpUrlConnection.disconnect();
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            mTextView.setText(result);
        }

        private String readStream(InputStream in) {
            BufferedReader reader = null;
            StringBuffer data = new StringBuffer("");
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    data.append(line);
                }
            } catch (IOException e) {
                Log.e(TAG, "IOException");
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return data.toString();
        }
    }

AndroidHttpClient

    private class HttpGetTask extends AsyncTask<Void, Void, String> {

        private static final String TAG = "HttpGetTask";

        // Get your own user name at http://www.geonames.org/login
        private static final String USER_NAME = "aporter";

        private static final String URL = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username="
                + USER_NAME;

        AndroidHttpClient mClient = AndroidHttpClient.newInstance("");

        @Override
        protected String doInBackground(Void... params) {

            HttpGet request = new HttpGet(URL);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            try {

                return mClient.execute(request, responseHandler);

            } catch (ClientProtocolException exception) {
                exception.printStackTrace();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {

            if (null != mClient)
                mClient.close();

            mTextView.setText(result);

        }
    }