Guide: Android: Parsing JSON Files with Gson and Native Objects:

I see a lot of questions as for how to parse JSON object in android, So I decides to write
a small guide to demonstrate how it’s done. Android platform has build-in tools for dealing
with those parsing tasks so I going to talk about those today. I also going to
show you a basic use of Google’s Gson library.

When we talk about JSON files, important to say that JSON (stand for JavaScript Object Notation) is, and I quote Wikipedia:

“a text-based open standard designed for human-readable data interchange. It is
derived from the JavaScript scripting language for representing simple data structures
and associative arrays, called objects.”

So JSON standard was basically designed to interchange data between different devices
over the internet. There are actually two main structures in JSON files which are Objects and
Arrays. Those will be the objects we will use in our code in order to parse those files.
Lets dive into an example:

Say we received a JSON file that represents a class and a list of students with their grades,
and this file looks like this:

{
    "Class":{
        "Class_Id": "A2",
        "Class_Type": "Science",
        "Class_Student_Count": 23,
        "Class_Studens": [
            {
                "Student_Id": "123456789",
                "Student_Name": "DavStudent_Id",
                "Student_Age": 23,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "987654321",
                "Student_Name": "Dan",
                "Student_Age": 25,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "123789456",
                "Student_Name": "Smith",
                "Student_Age": 30,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "987321654",
                "Student_Name": "Jhon",
                "Student_Age": 18,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "789123456",
                "Student_Name": "Leon",
                "Student_Age": 19,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "654987321",
                "Student_Name": "Philip",
                "Student_Age": 22,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            }
        ]
    }
}

As you can see this JSON file describes a students class with class details. In addition it
contains a list of class’s students while each one of them contains a list as well with the
student’s related course grades. It’s a fairly simple valid JSON file and at the moment I will
parse only the students list part, but before that I would like to share the following service
with you: http://jsonlint.com/. It will allow you to validate your JSON file and make
sure that what you receive from any web service is in fact a valid JSON file.

1. First we will create the relevant classes for parsing:
Student Class:

public class Student 
{
    private String studentId;
    private String studentName;
    private int studentAge;
    private List<Grade> studentGrades;
     
	public Student() {
		super();
		this.studentGrades = new ArrayList<Grade>();
	}
	public String getStudentId() {
		return studentId;
	}
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public int getStudentAge() {
		return studentAge;
	}
	public void setStudentAge(int studentAge) {
		this.studentAge = studentAge;
	}
	public List<Grade> getStudentGrades() {
		return studentGrades;
	}
	public void setStudentGrades(List<Grade> studentGrades) {
		this.studentGrades = studentGrades;
	}
    
	public void addGradeToGradesList(Grade grade)
	{
		this.studentGrades.add(grade);
	}
	@Override
	public String toString() {
		return "Student [studentId=" + studentId + ", studentName="
				+ studentName + ", studentAge=" + studentAge
				+ ", studentGrades=" + studentGrades + "]";
	}	
}

Grade Class:

public class Grade 
{
	private String course;
	private int courseGrade;
	
	public String getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}
	public int getCourseGrade() {
		return courseGrade;
	}
	public void setCourseGrade(int courseGrade) {
		this.courseGrade = courseGrade;
	}
	@Override
	public String toString() {
		return "Grade [course=" + course + ", courseGrade=" + courseGrade + "]";
	}	
}

Those classes are really self-explanatory so I’m not going to dwell on them much.

2. Second, I will create the JSON parsing class:

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class JSONParsingClass 
{
	private static final String TAG = JSONParsingClass.class.getSimpleName();
	
	//static final String for parsed elements
	//Class elements
	public static final String STUDENTS_LIST_ELEMENT = "Class_Studens";
	
	//Student elements
	public static final String STUDENT_ID = "Student_Id";
	public static final String STUDENT_NAME = "Student_Name";
	public static final String STUDENT_AGE = "Student_Age";
	public static final String STUDENT_GRADE_LIST = "Student_Grades";
	public static final String CLASS = "Class";
	
	//Grade elements
	public static final String COURSE_NAME = "Course_Name";
	public static final String COURSE_GRADE = "Course_Grade";

	//Native method for parsing json file
	public static List<Student> NativeJsonParseMethodForStudents(String jsonString) {
		try{
			//Creating list object for storing the parsed students
			List<Student> studentsList = new ArrayList<Student>();
			
			//Creating JSON object from string
			JSONObject json = new JSONObject(jsonString);
			
			//Getting "Class" element from JSON file
			JSONObject classElement = json.getJSONObject(CLASS);

			//Making sure that students list array exists
			if (!classElement.isNull(STUDENTS_LIST_ELEMENT))
			{
				//Getting students array
				JSONArray array = classElement.getJSONArray(STUDENTS_LIST_ELEMENT);
				
				//Creating empty json object for students loop
				JSONObject currentStudent;
				
				//looping all the students and adding them parsed one by one to the list
				for (int i = 0 ; i < array.length() ; i ++){
					currentStudent = array.getJSONObject(i);
					
					//Method to parse students and add them to the list
					addCurrentStudentToStudentsList(currentStudent, studentsList);
				}
				//Returning parsed students list
				return studentsList;
			}
			else
			{
				Log.d(TAG, "Students List is Null");
				return null;
			}
		} catch (Exception e) {
		   	Log.e("EXC", "Error", e);
		   	return null;
		}
	}
	
	//Method to parse students and added them to the list
	private static void addCurrentStudentToStudentsList(JSONObject currentStudent, List<Student> studentsList) 
	{
		//Initializing Student Object
		Student student = new Student();
		
		//Creating empty list for student's grades.
		List<Grade> studentGrades = new ArrayList<Grade>();
		try {
			//Parsing student's details.
			student.setStudentId(currentStudent.getString(STUDENT_ID));
			student.setStudentName(currentStudent.getString(STUDENT_NAME));
			student.setStudentAge(currentStudent.getInt(STUDENT_AGE));	
			
			//Making sure that student's grades list array exists
			if (!currentStudent.isNull(STUDENT_GRADE_LIST))
			{
				//Getting grades array
				JSONArray array = currentStudent.getJSONArray(STUDENT_GRADE_LIST);
				
				//Creating empty json object for grades loop
				JSONObject currentGrade;
				
				//looping all the student's grades and adding them parsed one by one to the list
				for (int i = 0 ; i < array.length() ; i ++){
					currentGrade = array.getJSONObject(i);
					
					//Method to parse grades and add them to the list
					addCurrentGradeToGradesList(currentGrade, studentGrades);
				}
			}
			//Setting student's grades
			student.setStudentGrades(studentGrades);
			
			//Adding student to the list
			studentsList.add(student);
			Log.d(TAG, "Added student: "+ student.toString()); 
		} catch (JSONException e) {
			Log.e(TAG, "Exception thrown on adding student to students list: "+ e.toString());
			e.printStackTrace();
		}	
	}
	
	//Method to parse grades and add them to the list
	private static void addCurrentGradeToGradesList(JSONObject currentGrade, List<Grade> studentGrades) {
		Grade grade = new Grade();
		Log.d(TAG, "currentGrade object: " + currentGrade.toString());
		try 
		{
			//Parsing grade's details
			grade.setCourse(currentGrade.getString(COURSE_NAME));
			grade.setCourseGrade(currentGrade.getInt(COURSE_GRADE));
			
			//Adding grade to the list
			studentGrades.add(grade);
			
		} catch (JSONException e) {
		Log.e(TAG, "Exception thrown on adding grade to grades list: "+ e.toString());
		e.printStackTrace();
		}
	}	
}

I added a comment above each line of code, So this class should be more then understandable
as well. And basically you are done, you have a parsed list of all the students with their grades
from the JSON file. You can practice by creating the “Class” class and try to parse it and add
the students to it’s list.

Gson Library Usage:

In the next part of this guide I will show you a way to cut down on the written code for parsing
this simple file by using the Gson library, because lets admit it, it’s whole lot of code
for parsing such a simple file.

1. So the first step for using Gson library as with any other library is of course to download it,
head to Gson Download and download the latest version.

2. Next, as before we will have to create the class we are going to populate with the parsed
data, but this time with a small difference:

Student Class for Gson:

import com.google.gson.annotations.SerializedName;

public class Student 
{
    @SerializedName(JSONParsingClass.STUDENT_ID)
    private String studentId;
	
    @SerializedName(JSONParsingClass.STUDENT_NAME)
    private String studentName;
	
    @SerializedName(JSONParsingClass.STUDENT_AGE)
    private int studentAge;
	
    @SerializedName(JSONParsingClass.STUDENT_GRADE_LIST)
    private List<Grade> studentGrades;

    //Rest of code is unchanged...    

Grade Class for Gson:

import com.google.gson.annotations.SerializedName;

public class Grade 
{
    @SerializedName(JSONParsingClass.COURSE_NAME)
    private String course;
	
    @SerializedName(JSONParsingClass.COURSE_GRADE)
    private int courseGrade;
    
    //Rest of code is unchanged...

It possible to omit the Gson annotations if you use the same variable names for the class
parameters as they appear in the JSON file, but because this is not the case those annotations are necessary.

3. Now, I will added another method to my JSONParsingClass:

private static void addCurrentStudentToStudentsListUsingGson(JSONObject currentStudent, List<Student> studentsList) 
{
    Gson gson = new Gson();
    Student student = gson.fromJson(currentStudent.toString(), Student.class);
    studentsList.add(student);
}

4. Finally, I will replace this line of code:

addCurrentStudentToStudentsList(currentStudent, studentsList);

In the

public static List<Student> NativeJsonParseMethodForStudents(String jsonString)

Method, with this line of code:

addCurrentStudentToStudentsListUsingGson(currentStudent, studentsList);

So we basically replaced the two long parsing methods: addCurrentStudentToStudentsList
and addCurrentGradeToGradesList from the first part of this guide with this single 3 lines of
code method: addCurrentStudentToStudentsListUsingGson. And that’s it, Now you can
parse JSON files in your application in the native way or use the Gson library.

One last thing, during the writing of this post, I have created an Android project with all the source
code presented here. You can download this project from here.

Enjoy and stay tuned.

May 18, 2013Emil Adjiev No Comments »
FILED UNDER :Guide , Guide - Android Development , Guide - JSON Parsing

Guide: Android: Crash Reports and Usage Monitoring:

Well you reached a step where you have completed your application and want
to test it or even publish it to the Google Play store. At this point (It’s strongly recommended
to do that even before that) it’s very important to integrated some sort of crash reports
service in your application and could be very useful to integrate some kind of usage
monitoring system as well.

So, today I’m going to talk about those features and more specifically I’m going to talk
about integration of two crash report services:

1. Crittercism
2. ACRA with BugSense back-end.

Both of those services can be used for free, but got paid programs as well.
I’m going to talk about one usage monitoring system as well named:
3. Flurry.
Lets start with the crash reports. So how is it done:

1. Well for Crittercism the deal is very simple, head to their site: www.crittercism.com,
and sign in. You will need to download the jar file from Documentation for Android section.
Once you did that and added the jar file to the /libs folder of your project you are ready to start
configuring it. Open your Apps section and create an application for which you would like to
receive crash reports. Press the:

Untitled

button, and enter the application details. When you finish press the REGISTER APP button at
the bottom of the page. Open your Apps page again and you will see the newly
added application under the Registered Apps section. Click on the app name to enter
it’s configurations and go to the Settings page (red), under “To initiate Crittercism for this
Application:”
you will find a row of code (green) you will have to integrate in your application
in order for the crash reports service to work:

Untitled5

You should integrate this line in the first Activity of your application in the onCreate() method:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Crittercism.init(getApplicationContext(), "516a6c4e46b7c26e6f000002");
    // rest of code here...
}

Add this Activity to the Manifast file:

<activity android:name="com.crittercism.NotificationActivity"/>

Finally you need to add the following three permissions to your Manifest file:

<!--  Internet Permission  -->
<uses-permission android:name="android.permission.INTERNET"/>
<!--  Crittercism Permissions  -->
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.GET_TASKS"/>

2. The second crash reporting service is greatly popular among Android developers:
Application Crash Report for Android or ACRA in short. up until not long ago
this service was used with Google Doc back-end to store the crash logs. this use of
Google Doc have became deprecated by Google, and they have asked developers nicely
not to use their service for this purpose.

So I searched for another back-end service that will work with ACRA and found out that
BugSense provide this kind of service. What you need to do as before is to head
to their site and sign up. Next, you will receive a dashboard screen, in it create a new
project that will represent the project you want to receive error reports for. Press the:

add project

button, and enter the application details like: Project Name, Billing Account, Platform (Technology) and another application details. Open your My projects page again and you will
see the newly added application:

new project

You can see that with the new project you receive an ApiKey(red) that you will use next to integrate ACRA in your project. To do that first head to acra.ch and download the
last .jar file from the Quick Setup section. As before add the jar file to the /libs folder of your project.

Now you can start integrate ACRA in your code, all you need to do is to add 2 lines to your application class:

import org.acra.*;
import org.acra.annotation.*;

@ReportsCrashes(formUri = "http://www.bugsense.com/api/acra?api_key=1e76b702", formKey="")
public class MyApplication extends Application 
{
    @Override
    public void onCreate() 
    {
        // The following line triggers the initialization of ACRA
        super.onCreate();
        ACRA.init(this);
        // rest of code here...
    }
}		

So as you can see you need to add the @ReportsCrashes annotation right before the class
definitions, where you would replace the api_key, with the key you were given from BugSense
when you registered your app. Second line would be:

ACRA.init(this);

to initialize ACRA monitoring. As with the first crash service don’t forget to add here the internet permission as well:

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

3. Now for the usage monitoring system: Flurry:
So as with the other two services, we need to register so head to www.flurry.com, sign up for
the service, and open the Applications tab in you dashboard screen. click the Add a New Application option from the up-right corner, choose the platform of your project (Android in our case), pick a name for the project and select it’s category. Finally press the Create App button.

Next, you will receive the following screen:
flurry

Here as you can see you receive Your unique application key (1) and you have a button to
download the relevant SDK file for you platform (2). Download the SDK and as before integrate
it into the /libs folder of your application. Now for Flurry integration you need to add in each Activity of your application were you want to monitor user actions, those lines to start and stop monitoring:

@Override
protected void onStart()
{
    super.onStart();
    FlurryAgent.onStartSession(this, "65KYTTCTDCMT7J69S7XT");
}
	 
@Override
protected void onStop()
{
    super.onStop();		
    FlurryAgent.onEndSession(this);
}

To monitor an event you should add this line in the relevant position in your code:

FlurryAgent.onEvent("Event text");

If you want to monitor parameters as well then you need to pass a HashMap of parameters to the FlurryAgent like this:

final HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("String key", "String value");
FlurryAgent.logEvent("Text relevant to parameter", parameters);

As before, don’t forget to add the internet permission to your project:

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

And that it. Now you can and should monitor your application for errors and usage.
Enjoy and stay tuned.

April 23, 2013Emil Adjiev No Comments »
FILED UNDER :Guide , Guide - Android Development

Guide: Android: Use Camera Activity for Thumbnail and Full Size Image:

Today I have decided to show you how to use the build in camera Activity to
Take thumbnail and full size images. The reason for that is that this is a common problem
and many people get confused as for why do they get a low resolution image when they are
using the build in camera Activity for taking images in their Android application
(I was one of those people).

But first I would like to stop and explain why do you need thumbnail images in your app.
The problem with mobile devices as we all know is that they are low on resources (CPU,
Memory, Storage, etc.. today clearly this statement becomes less and less true), as for this
reason the Android OS was designed to allow a single application use only a very limited
amount of memory at run time.

That means that you can’t take a full 5 or 8 megapixels image and load it into memory just to
show it inside a small ImageView. Well, you can, but on the second or third image your
application will simply crash with an java.lang.OutOfMemoryError. So clearly you have
to care always to use the image with the most low resolution but yet satisfies with it quality at run time.

Back to where I started, people get confused because there are several ways to perform this
operation and I will show you them today:

Thumbnail Image:

Actually this will be the easiest way to take an image using the camera and to save it in
you application. The problem with this is that this image is very low resolution and is
not fit for displaying on a full mobile screen:

1. First of all define:

public static final int CAPTURE_IMAGE_THUMBNAIL_ACTIVITY_REQUEST_CODE = 1888; 

This will be your code so you could read the result of the camera Activity. You can
define here any number you would like.

2. Next fire an intent that will start an Activity for result.

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, CAPTURE_IMAGE_THUMBNAIL_ACTIVITY_REQUEST_CODE);

3. Finally receive the result and save it:

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{  
    //Check that request code matches ours:
    if (requestCode == CAPTURE_IMAGE_THUMBNAIL_ACTIVITY_REQUEST_CODE) 
    {
        //Check if your application folder exists in the external storage, if not create it:
        File imageStorageFolder = new File(Environment.getExternalStorageDirectory()+File.separator+"Your application Folder");
        if (!imageStorageFolder.exists())
        {
            imageStorageFolder.mkdirs();
            Log.d(TAG , "Folder created at: "+imageStorageFolder.toString());
        }

        //Check if data in not null and extract the Bitmap:
        if (data != null)
        {
            String filename = "image";
            String fileNameExtension = ".jpg";
            File sdCard = Environment.getExternalStorageDirectory();
            String imageStorageFolder = File.separator+"Your application Folder"+File.separator;
            File destinationFile = new File(sdCard, imageStorageFolder + filename + fileNameExtension);
            Log.d(TAG, "the destination for image file is: " + destinationFile );
            if (data.getExtras() != null)
            {
                Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                try 
                {
                    FileOutputStream out = new FileOutputStream(destinationFile);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                    out.flush();
                    out.close();
                } 
                catch (Exception e) 
                {
                    Log.e(TAG, "ERROR:" + e.toString());
                }
            }
        }
    }
}

You can see that in this case we are getting our image from the Extras of the intent under
the “data” key. We cast it to a Bitmap and save it to a file using an FileOutputStream.
But actually we didn’t had to save it to file and could use the bitmap straight forward.

Full Size Image:

Well the big difference here is if we want to produce a high quality image from the
camera Activity we don’t have a choice but to save it into file and then use:

1. So First of all as before we need to create a static int that will be our requestCode:

public static final int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE = 1777; 

2. Next we fire again the same intent to start Activity for result but this time with a little difference:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);

and the difference in this case is with this line: intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

Here we are actually passing an URI as an extra to the intent in order to save the image at this location
when it will be taken.

3. Finally we will receive the result in onActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{  
    //Check that request code matches ours:
    if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE) 
    {
        //Get our saved file into a bitmap object:
       File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
       Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
    }
}

When decodeSampledBitmapFromFile method is:

public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) 
{ // BEST QUALITY MATCH
    
    //First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize, Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    int inSampleSize = 1;

    if (height > reqHeight) 
    {
        inSampleSize = Math.round((float)height / (float)reqHeight);
    }
    int expectedWidth = width / inSampleSize;

    if (expectedWidth > reqWidth) 
    {
        //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
        inSampleSize = Math.round((float)width / (float)reqWidth);
    }

    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(path, options);
}

For both cases don’t forget to add the relevent camera permissions to the manifest file:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

And that’s it, now you can add the build in camera capabilities to your application and take
images with the quality you want. Enjoy.

April 7, 2013Emil Adjiev No Comments »
FILED UNDER :Guide , Guide - Android Development

Guide: Android – MultiClickable ListView:

Well today I want to talk about implementation of a multiclickable list.
And what do I mean by that? Well what I mean is that every list item has
more then one location where you can press it following by different operation.

So lets for example take a row where you want to place a CheckBox, ImageView
and a TextView while all of them are clickable. Meaning that you can click the
row it self for going to another Actvity for more details on the row, check its
CheckBox or press the ImageView to perform another operation.

So what you should do is:

1. First create an XML layout file for your ListView row:

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <CheckBox 
        android:id="@+id/cbCheckListItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="10dp" />
    <TextView
        android:id="@+id/tvItemTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="item string" />
    <ImageView
        android:id="@+id/iStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:contentDescription="@drawable/ic_launcher"
        android:src="@drawable/ic_launcher" /> 
</LinearLayout>

2. Second in your java code define a ViewHolder, a ViewHolder
is designed to hold the row views and that way operating more quickly.

static class ViewHolder 
{
    TextView title;
    CheckBox checked;
    ImageView changeRowStatus;
}

3. Now we have to define CustomArrayAdapter, using the array adapter
we can define precisely what is the desired output for each row based on the content of this
row or it’s position. We can do so by overriding the getView method:

private class CustomArrayAdapter extends ArrayAdapter<RowData>
{	
    private ArrayList<RowData> list;
    
    //this custom adapter receives an ArrayList of RowData objects.
    //RowData is my class that represents the data for a single row and could be anything.
    public CustomArrayAdapter(Context context, int textViewResourceId, ArrayList<RowData> rowDataList) 
    {
        //populate the local list with data.
        super(context, textViewResourceId, rowDataList);
        this.list = new ArrayList<RowData>();
        this.list.addAll(rowDataList);
    }
		
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        //creating the ViewHolder we defined earlier.
        ViewHolder holder = new ViewHolder();) 
        
        //creating LayoutInflator for inflating the row layout.
        LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //inflating the row layout we defined earlier.
        convertView = inflator.inflate(R.layout.row_item_layout, null);
        
        //setting the views into the ViewHolder.
        holder.title = (TextView) convertView.findViewById(R.id.tvItemTitle);
        holder.changeRowStatus = (ImageView) convertView.findViewById(R.id.iStatus);
        holder.changeRowStatus.setTag(position);
 
        //define an onClickListener for the ImageView.
        holder.changeRowStatus.setOnClickListener(new OnClickListener() 
        {			
            @Override
            public void onClick(View v) 
            {
                Toast.makeText(activity, "Image from row " + position + " was pressed", Toast.LENGTH_LONG).show();
            }
        });
        holder.checked = (CheckBox) convertView.findViewById(R.id.cbCheckListItem);
        holder.checked.setTag(position);

        //define an onClickListener for the CheckBox.
        holder.checked.setOnClickListener(new OnClickListener() 
        {		
            @Override
            public void onClick(View v)
            {
                //assign check-box state to the corresponding object in list.    
                CheckBox checkbox = (CheckBox) v;
                rowDataList.get(position).setChecked(checkbox.isChecked());
                Toast.makeText(activity, "CheckBox from row " + position + " was checked", Toast.LENGTH_LONG).show();	 
            }
        });

        //setting data into the the ViewHolder.
        holder.title.setText(RowData.getName());
        holder.checked.setChecked(RowData.isChecked());

        //return the row view.
        return convertView;
    }
}

4. Now you need to set this adapter, as the adapter of your ListView.
this ListView can be created in java or using an XML file, in this case I’m using a list that was
defined in the XML file using the “list” id:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout); 
    ListView list = (ListView)findViewById(R.id.list);
    CustomArrayAdapter dataAdapter = new CustomArrayAdapter(this, R.id.tvItemTitle, rowDataList);
    list.setAdapter(dataAdapter);
}

5. Finally if we want to be able to press the row it self and not only a certain view in it
we should assign an onItemClickListener to the ListView:

list.setOnItemClickListener(new OnItemClickListener() 
{
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
    {
        Toast.makeText(activity, "row " + position + " was pressed", Toast.LENGTH_LONG).show();
    }
});
March 31, 2013Emil Adjiev No Comments »
FILED UNDER :Guide , Guide - Android Development

Guide: Android Emulator Speed-Up and Google Map V2:

Today I want to talk about the Android AVD – Android Virtual Device, or as
everyone call it the Emulator. I am developing for the Android Platform for about a
year now and only recently come to my ears that this emulator can be Accelerated on
Processors that support Virtual Acceleration. So I have looked at my Lenovo G580 specs,
and luckily the Core I3 sierras supports it.

I have became really interested to know is there really a big difference between
an accelerated machine and one that is not, because every single person who develops for
Android know how slow is the emulator. So I Goggled it and found the following page:
Intel® HAXM – Hardware Accelerated Execution Manager.

There is a great explanation there for what you should do in order to download
and install the HAXM. and how you can turn it on and off and I have to tell the
process of installing this is nothing compare to what you are getting back.
The AVD runs almost fluently like a real device. I was shocked that I didn’t discovered
this earlier. That would save me a lot of nerves while dealing with the painfully slow Android
emulator.

So for every one that develops for Android and going nuts for waiting a couple of second
for every action you make on the emulator I am totally recommending to spend 15 minutes,
find out if you machine support Hardware Acceleration and install the manager in order
to the get rid of this annoying problem.

Last thing if you know that you machine support Hardware Acceleration and still when you
try to install it you get a message that is not support, most likely you need to enable it from
the Bios of you machine.

Now that we covered Hardware Acceleration I want to talk about Google Map V2 support
in AVD.

NOTE: A quick but a very important note, from a further check I made this will work only if you are using google-play-service lib revision #4 in your application (and workspace). If you have already updated google-play-services using the SDK Manager to the latest version (Currently: revision #6) you will receive an error telling you that you that the google-play-services used by your application is too old and needs to be updated:

Google Play services out of date. Requires 3025100 but found 2012110 .

in order to make this guide work you can remove the new google-play-service library from you workspace and download revision #4 from the following link. After downloading reference this project instead of the newer one and then try to implement this guide.

Anyone that tried to develop an application that uses Google’s great new API
for maps has encountered the following message instead of a map:

get google play services

Pressing the “Get Google Play Services” button won’t do you any good and most likely
will crash your application. After some time that I was searching for a solution I
have stumbled on few post on Stack Overflow where people managed to get Google Maps
running by installing the apk of Google Services that are relevant for Google Maps.
Did the same and it works, now I am able to develop my map application even
without an Android device always by my side.

So the steps to enable Google Maps API V2 in the emulator are as following:

1. You need to download 2 apk files: com.android.vending.apk and com.google.android.gms.apk

2. Open eclipse and the AVD Manager and create an AVD with the following configuration:

img

3. Start the AVD and wait for it to finish booting, next open you command prompt and install
both apk’s using the “adb install” command. for example:

C:\Users\<your user name>\Downloads\adb install com.android.vending.apk

you should receive “SUCCESS” message at the end of the installation process (that may take some time).

4. When you finish installing both apk files, close the AVD and reopen it. Now you should see a
map in your application when you use the AVD instead of this annoying message.

That’s it for today, Enjoy.

February 11, 2013Emil Adjiev 13 Comments »
FILED UNDER :Guide , Guide - Android Development

Guide: Google Maps V2 for Android : Creating your Google Map Application:

If you already got your Google Maps Android API V2 key then you are ready to create
your map application. If you don’t head to my Guide: Google Maps V2 for Android :
Getting the API key
post to read how to get it.

So lets start:
1. Open Eclipse and create a new Android project.
The first thing that we will handle is the import of Google Map classes.
To get the Google Maps files we need to download the last version of
Google Play Services via the Android SDK Manager.

2. After you downloaded the Google Play Services, restart Eclipse and
in the Package Explorer Right-Click –> Import….
In the opened windows choose “Existing Android Code into Workspace” and click “Next”.
Click the “Browse…” Button and head to the location of your SDK folder.
in it find the following folder:

\extras\google\google_play_services\libproject\google-play-services_lib

and press “OK”, check the V next to it in the window and press the “Finish” button.

3. Now you added Google Play Services to your work space, we have to create a reference
from our project to this library. Right-Click your project and choose “Properties” go
to the Android section, in the lower part press the “Add…” button and add a reference
to that library. Your result should be as in the screen shot bellow:

adding google play services library

Note: If you try to reference google-play-service library and you receive a red X next to this
reference, what you should do is to move the .jar file to a location where it’s path will be shorter
and then reference it again.

4. Another import we have to make in order to make our application work on
Operation system prior to API11 is to import the support library this can be done very easily
using Eclipse: Right-Click you project and choose “Android Tools” and then choose
“Add Support Library…”:

supportlibrary

When you finish those import you should have the following libraries (Red) in the
Android Dependencies folder (Green) of your project:
Untitled

5. We are now ready for some codding: First of all open the Android Manifest file:
add the following permissions:

<permission android:name="your.application.package.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-permission android:name="your.application.package.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET" />
<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" />

Important: Replace your application package instead of the current “your.application.package” string.

6. Next, Google Maps uses OpenGL so we have to add OpenGL support to our application
by adding this to the Manifest file:

<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>

7. Finally add your key to you application right before you close your “application” node
in the Manifest file:

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your Google Maps API V2 Key" />

8. Now create an Activity that extends from “FragmentActivity”:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MapActivity extends FragmentActivity {

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

9. Finally for map_layout, XML layout file that was set
as a content view of the map activity write the following:

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

    <fragment
        android:name="com.google.android.gms.maps.SupportMapFragment"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

And that’s it, run the application and you should see a full screen map:

map

Remember that if you want to run the application in the emulator you should install
Google Play Services first.

Enjoy and stay tuned.

Guide: Google Maps V2 for Android : Getting the API key

Since I have been working on an Android application that uses Google map
services I have decided to write a couple of posts on this topic.
The application will be posted here as well in the near future.

The first thing you have to know when implementing Google Maps for android is
that you have to produce your own Google Map Android API V2 key.
Now there is a reason that I’m marking this name, take a careful look that you turning on
the right Key in you API Console and that you have chosen the API for Android
and not the Google Maps API V2 or V3 for example.

So how do we get an API key, you ask? Well it’s a few steps task:
1. First of all we need to find our SHA1 key. For debugging
purposes we will use the debug.keystore file to get our SHA1 key. to do that
we will use a tool named ‘Keytool‘ that come with Java installation.
so open you command prompt, head to the following location:

C:\Program Files\Java\<your JDK or JRE instllation>\bin>

and run the next command:

keytool -list -v -keystore C:\Users\<your user name>\.android\debug.keystore -storepass android -keypass android

You will recive the following output:

SHA1 key pic
Copy the SHA1 key by right-clicking the command prompt choosing ‘Mark’, then
mark the all key and right-click again on the marked text to copy it.

2. Now that we have the SHA1 key we can head to the Google API’s Console,
sign-in with our Google account and create a new project by clicking the drop box
in the upper-left corner of the screen and choosing the ‘Create…’ option:

create in google api

Give a name to your project and create it.

3. Once you have done that head to the Services section and turn on the Google Map Android API V2:

api service

4. Now open the API Access section and press the Create new Android key… button.

In the window that opens you will have to enter you SHA1 key you got in the 1. section adding
to it your application package name after a semicolon as in the example:

45:B5:E4:6F:36:AD:0A:98:94:B4:02:66:2B:12:17:F2:56:26:A0:E0;com.example.your_project_name

After pressing the Create button you will recieve you own Google Maps API V2 key for Android.

My next post will explain how to use this key to create a Google map in your application.

Guide: c3p0 – JDBC3 Connection and Statement Pooling

After I uploaded my JavaEE course project to Openshift hosting service as you
could do using the Guide: Introduction to Openshift hosting Apache Tomcat, I thought
that my work with this project is done. But strangely for me I started to encounter
database connectivity issues. I done a little research and realized that the reason for
those problems is the default MySQL configuration for closing inactive connections to
the database. MySQL automatically closes any inactive connections to the database
after the default 8 hours. Unfortunately Hibernate ins’t aware of that and still thinks
that the connection is open when trying access the database to perform a query.
Of course Hibernate will fail to perform that task and we will be given the following exception:

[org.hibernate.exception.JDBCConnectionException: could not execute query] with root cause java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

To fix this issue as it’s done in production environments it is important to implement
some sort of connection pool mechanism that will always keep open shared connections
to the database for all application users. Here I’m going to show you how to implement the
c3p0 – JDBC3 Connection and Statement Pooling mechanism in your project with
Hibernate already implemented:

1. So clearly the first thing that needs to be done is to download the c3p0 project files.
Use the following link to download the latest version from Source-forge.

2. Extract the files from the zip archive and copy the c3p0-0.9.2-pre7.jar
and mchange-commons-java-0.2.3.2.jar to the lib folder of your project.

3. Edit your hibernate.cfg.xml and add the following infomation under the
<session-factory> hive:

<!-- important to specify c3p0 as your connection provider -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

<!-- configuration for connection pool via c3p0 -->
<property name="c3p0.min_size">3</property>
<property name="c3p0.max_size">20</property>
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.max_statements">50</property>
<property name="c3p0.timeout">14400</property>
<property name="c3p0.idle_test_period">3600</property>

It is really important to specify the “connection.provider_class” property as:
org.hibernate.connection.C3P0ConnectionProvider or hibernate will continue using it’s
own default mechanism. Other properties may be customized to your liking.
Eventually your hibernate configuration file should look like this one:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
        <!-- default hibernate connection settings -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/database</property>
		<property name="connection.username">user</property>
		<property name="connection.password">password</property>
		<!-- for MySQL users specify the following dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">update</property>
		<!-- inmportant to specify c3p0 as your connection provider -->
		<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		<!-- configuration for connection pool via c3p0 -->
		<property name="c3p0.min_size">3</property>
		<property name="c3p0.max_size">20</property>
		<property name="c3p0.acquire_increment">1</property>
		<property name="c3p0.max_statements">50</property>
		<property name="c3p0.timeout">14400</property>
		<property name="c3p0.idle_test_period">3600</property>
		<!-- end of configuration -->
		<mapping class="com.eadesign.hibernate.CouponDetails"/>
		<mapping class="com.eadesign.hibernate.Company"/>
		<mapping class="com.eadesign.dto.User"/>
		<mapping class="com.eadesign.dto.Administrator"/>
		<mapping class="com.eadesign.hibernate.Feedback"/>	
	</session-factory>
</hibernate-configuratio

And that’s it, now you have connection pool in your project.

more information can be found in the c3p0 manual.
As this Appendix C: Hibernate-specific notes:

Appendix C-Hibernate of c3p0

December 19, 2012Emil Adjiev No Comments »
FILED UNDER :Guide , Guide - Java Development

Guide: WordPress hosting on OpenShift

Actually in my opinion this is one of the simplest ways to get your WordPress blog/site
up and running in no time. in just few simple commands you have a Blog in the air that
you can customize and edit to you liking. I am counting that you already have created your
own OpenShift account and installed the rhc Client Tools. If not please head to my
Guide: Introduction to Openshift hosting Apache Tomcat post and follow the first two
paragraphs to open the account and install the tools. I would recommend to read all of it
as it holds great information regarding tools that will simplify your work with OpenShift.

Now you are ready to create our own WordPress application container on OpenShift.
Open your command prompt and head to the location were you want your git repository
for this project to be created and enter the following command:

rhc app create -a <name for your container> -t php-5.3

Name your application container as you wish. This name will be part of the URL for accessing your application.
So now we allocated resources to ourselves in Red Hut’s cloud with php 5.3 application
already installed. WordPress needs a database to store it’s data and can’t live without
it so we will add MySQL database to this configuration using the next command:

rhc cartridge add -a <name of your container> -c mysql-5.1

And finally I always add the phpMyAdmin application to make it easier on me to manage my
databases. To do that run the following command:

rhc cartridge add -a <name of your container> -c phpmyadmin-3.4

Save your database credentials produced at the end of this process.

Now we are ready to install WordPress. There are two ways you can do that:

1. The first and the easy way to get a WordPress installation is to pull it from a git repository.
Head to your application folder using the next command:

cd <name of your container>

Now set the remote git repository to pull it’s stream from it:

git remote add upstream -m master git://github.com/openshift/wordpress-example.git

Pull the stream/content:

git pull -s recursive -X theirs upstream master

And push it to your repository on the cloud:

git push

To access your WordPress application use the default credentials:

User name: admin
Password: OpenShiftAdmin

The problem is that the version of WordPress now hosted on this repository is 3.4 and there
is a new 3.5 WordPress installation available. You could upgrade your WordPress version
using it’s Dashboard interface, but now you will have 2 different versions of WordPress
on your local git repository (3.4) and the clouded one (3.5). I will explain how to fix this
problem in the update section.

2. Alternatively you could push you own WordPress installation to your cloud repository.
Head to www.WordPress.org and download the latest version of WordPress.
Copy the downloaded content to the php folder in your local repository and open the
command prompt. Head to your local git repository folder and enter the following command:

git add .

For letting git know of all the changes that were made to that folder, then:

git commit -m "added wordpress3.5"

Committing the changes to the local repository. And finally Pushing the changes to the cloud:

git push

And that’s it, now you can access your new WordPress application using the URL
you are provided on OpenShift and start customize it.
 

Updating your local repositry with the changes made by WordPress in the cloud:

When you will update you WordPress installation in the future or maybe you would want to
change the looks of your blog/site by adding a sleek Theme or maybe a Widget and you’ll do
that using the Dashboard interface, you would have to update your local repository with
those changes. In that case what you need to do is to take a snapshot of your machine on
OpenShift using the next command:

rhc snapshot save -a <name of your container>

this will download a <name of your container>.tar.gz to you local git repository
containing a snapshot of your files from the clouded repository. Extract the files to a folder
with the same name and head to:
<name of your container>\<your OpenShift ID>\app-root\repo\
Copy the content of this folder to your local git repository folder and commit the changes
using the following commands:

git add .
git commit -m "wordpress updated"
git push

That way the files on your local repository will be identical to those in the cloud.

December 15, 2012Emil Adjiev No Comments »
FILED UNDER :Guide , Guide – Web Development

Guide: Introduction to Openshift hosting Apache Tomcat

To present my Java EE course project in this blog I had to find another
Apache Tomcat hosting service since the one we got during education was
not responding anymore. That’s how my search for a free Apache Tomcat
hosting service started. I contacted with my hosting service where i host
this blog and I was quickly explained that this kind of service is not
supported there. Next i went to the web (Goggled) to search for such free
service just to find out that there are not that many of them at all.
And then I saw that Red Hat offering Apache Tomcat service and much more
with their OpenShift PaaS – Platform as a Service. They basically give you
a platform (clouded resources) to deploy your applications and this platform
supports Node.js, Ruby, Python, PHP, Perl, and Java technologies and much more.

So how is it done?
1. The first thing is to go to http://openshift.com and create an account.
Once you have created an account you can publish 3 application for free.
During the creation of your account you will have to specify you Namespace
that latter on will be used for your application URL’s.

2. Install the OpenShift client tools. For that you need to install Git for Windows
and a Ruby and configure them. This is explained in the following link.
During the configurations of Git you will create an ssh key for connecting
to your repository on Red Hat.

3. Now that you installed the client tools you are ready to create your first
application container on OpenShift. Actually this can be done using their web
interface but it’s faster to do that with the command line. To create your
application container with Apache Tomcat already installed you need to run to
following commands in the command prompt:

rhc app create -a tomcat -t diy-0.1

this will create for you your DIY (do it yourself) application container on
Red Hat’s servers with the name “tomcat” and a local Git repository in your
current location at the command prompt with the same name. now all you need
to do is to edit your local repository and to push changed to the server
uisng git.

Enter your repository folder by entering:

cd tomcat

and then enter the following commands:

1.git remote add upstream -m master git://github.com/openshift/openshift-tomcat-quickstart.git
2.git pull -s recursive -X theirs upstream master
3.git push

what we are doing here is configuring a remote upstream and we pull it’s content from it
to our local git repository. finally we push this changes to our own application container.
at the end of this process we will have a DIY application with Apache Tomcat 7 installed.

4. Now we need to connect to our application container to copy there our application files.
There are 3 way to do that: we can copy the files to our local git repository and push the
changes to the server, we can use an SSH terminal (like PUTTY) and edit the files using
commands from the command line or we can use an SSH based FTP tool (like WinSCP)
to manage files as you would do in a commander interface.

you can download PUTTY from here. You should download the zipped file for all PUTTY package.
you can download WinSCP from here.

putting your project into the webapps folder of your local application repository and pushing
it to the server will put your files in the following location:

/var/lib/openshift/<your openshift userID>/app-root/
runtime/repo/diy/tomcat/webapps

and this is not the right webapps folder for the installed Apache Tomcat.
That is the reason I prefer to use the WinSCP application. So lets open WinSCP and
the first window you will receive is the WinSCP Login window:

enter the following information:

  1. Your full application container URL – you can get it from OpenShift.
  2. Your Username – again you can find it on your application page on OpenShift under the “GIT REPOSITORY” section.
  3. Your OpenShift password.
  4. You have to supply your ssh key, you can create it using puttygen.exe application that you can download from the PUTTY link. Open puttygen.exe:

  1. Click the “Load” button and go to your C:\Users\<your windows username>\.ssh folder. Chose the id_rsa file (without extension) and press Open. you will be notified that this is a security key.
  2. Click the “Save private key” button to save a new private key (.ppk) file.

5. Now you can supply your security key and connect via WinSCP to your machine on Openshift.
When you connected you will receive a commander window. The right pane connected to
your OpenShift repository at the following location:

/var/lib/openshift/<your openshift userID>/

Head to:

/var/lib/openshift/<your openshift userID>/app-root/
data/tomcat/webapps

and copy your project files here.
Head to:

/var/lib/openshift/<your openshift userID>/app-root/
data/tomcat/lib

and copy your project resource files (your Jars necessary for the project).

6. Finally open command prompt again and run:

rhc app restart tomcat

to restart your container and let the changes take affect. now you can access you project
using the application URL you can get on OpenShift.

December 11, 2012Emil Adjiev No Comments »
FILED UNDER :Guide , Guide - Java Development