Friday, December 5, 2014

Android JSON Parsing Tutorial

There are many ways to get JSON data, In this tutorial I'm getting JSON data from a text file stored in assets folder alternatively you can also get JSON data from a URL or web service.


1. The JSON Structure


I am taking an example of following JSON which will give you list of employees and each employee will have details like id, name, city, gender, age etc.

{
    "employee": [
        {
            "id": 101,
            "name": "Amar",
            "city": "Dausa",
            "gender": "M",
            "age": 21
        },
        {
            "id": 102,
            "name": "Sunil",
            "city": "Bharatpur",
            "gender": "M",
            "age": 22
        },
        {
            "id": 103,
            "name": "Uday",
            "city": "Bharatpur",
            "gender": "M",
            "age": 22
        },
     
        {
            "id": 104,
            "name": "Rahul",
            "city": "Alwar",
            "gender": "M",
            "age": 21
        }
    ]
}

Consider that above JSON data is stored in jsondata.txt file which is stored in assets folder.


2. Reading Text File (from assets folder)


Before we start parsing the above JSON data, first we need to store data from jsondata.txt file to a string. Here is the code snippet-

// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsondata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}

String myjsonstring = sb.toString();


 3. Parsing JSON data from String


In second step we store JSON data from jsondata.txt file to a string called myjsonstring, Now we are ready to parse JSON data from it. Here is the code snippet-

// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);

// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");

// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {

// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);

// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String city = jsonObj.getString("city");
String gender = jsonObj.getString("gender");
int age = jsonObj.getInt("id");

}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Note:- The parsing of JSON data from URL is same as in step 3. If you want to parse JSON data from URL, first you need to download the JSON data from server using HTTP & then you need to store that data into a string. After that you can easily parse JSON data from that string (similar to step 3).


Final Code



Project Name : JsonFromString
Package : com.sunil.jsonfromstring
Main Activity : MainActivity.java
Layout : main.xml
Build Target : Android 2.2

main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</RelativeLayout>


MainActivity.java
package com.sunil.jsonfromstring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

String myjsonstring;

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

// Preparing TextView to display JSON results
TextView tvResult = (TextView) findViewById(R.id.tvResult);

// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsondata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}

myjsonstring = sb.toString();

// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);

// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");

// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {

// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);

// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String city = jsonObj.getString("city");
String gender = jsonObj.getString("gender");
int age = jsonObj.getInt("id");

// Append result to TextView
tvResult.append("ID : " + Integer.toString(id) + "\n");
tvResult.append("NAME : " + name + "\n");
tvResult.append("CITY : " + city + "\n");
tvResult.append("GENDER : " + gender + "\n");
tvResult.append("AGE : " + Integer.toString(age) + "\n\n");

}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


Output

android json


That's it ! You can also download the source code of this tutorial.

Download from here

Source

Friday, May 18, 2012

Using Google Translate API In Android

In this tutorial we are going to know how we can use google translate API in Android

At first download google-api-translate-java-0.95.jar here 


Import that JAR file to android buid Path (Right-click project->Properties->Java Build Path-> Libraries->Add External JARS.)

The xml file


main.xml:

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


The JAVA file 


Translator.java:


package com.myapps.translate;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;


import com.google.api.translate.Language;
import com.google.api.translate.Translate;


public class Translator extends Activity {
    /** Called when the activity is first created. */
String translatedText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TextView tv = new TextView(this);
        Translate t = new Translate();
        
        try {
translatedText = t.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);


//tv.setText(translatedText);
        } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


        Toast.makeText(this, translatedText, Toast.LENGTH_SHORT).show();
        
        tv.setText(translatedText);
        
        setContentView(tv);
    }
}

Thursday, April 12, 2012

Change background color, by SeekBar

In this exercise, the background color is changed, controlledby SeekBar.

SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys.

When SeekBarChange, the onProgressChanged() of OnSeekBarChangeListener will be called, and the background of the screen(LinearLayout) will be upda

ted according to the value (SeekBar.getProgress()).




Create a Android Application, SeekColor, with three SeekBar for Red, Green and Blue setting.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<SeekBar
android:id="@+id/mySeekingBar_R"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
<SeekBar
android:id="@+id/mySeekingBar_G"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
<SeekBar
android:id="@+id/mySeekingBar_B"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
</LinearLayout>


SeekColorActivity.java
package com.exercise.seekcolor;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;

public class SeekColorActivity extends Activity {

private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mScreen = (LinearLayout) findViewById(R.id.myScreen);
    redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
    greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
    blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
    updateBackground();

    redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);

}

private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
  boolean fromUser) {
// TODO Auto-generated method stub
 updateBackground();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};

private void updateBackground()
{
 seekR = redSeekBar.getProgress();
 seekG = greenSeekBar.getProgress();
 seekB = blueSeekBar.getProgress();
 mScreen.setBackgroundColor(
  0xff000000
  + seekR * 0x10000
  + seekG * 0x100
  + seekB
  );
}
}


The project files can be downloaded here.

Monday, February 6, 2012

Apply animation on Button


Create four XML files for animation:

/res/anim/anim_alpha.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.1"
        android:duration="500"
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>


/res/anim/anim_rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <rotate
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="500"
        android:startOffset="0"
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>


/res/anim/anim_scale.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:fromXScale="1.0"
        android:toXScale="3.0"
        android:fromYScale="1.0"
        android:toYScale="3.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="500"
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>


/res/anim/anim_translate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <translate
        android:fromXDelta="0"
        android:toXDelta="100%p"
        android:duration="500"
        android:repeatCount="1"
        android:repeatMode="reverse"/>
</set>


main.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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/translate"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Translate" />
    <Button
        android:id="@+id/alpha"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Alpha" />
    <Button
        android:id="@+id/scale"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Scale" />
    <Button
        android:id="@+id/rotate"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Rotate" />

</LinearLayout>


Main activity:
package com.exercise.AndroidAnimButtons;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

public class AndroidAnimButtonsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final Animation animTranslate = AnimationUtils.loadAnimation(this, R.anim.anim_translate);
        final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
        final Animation animScale = AnimationUtils.loadAnimation(this, R.anim.anim_scale);
        final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
       
        Button btnTranslate = (Button)findViewById(R.id.translate);
        Button btnAlpha = (Button)findViewById(R.id.alpha);
        Button btnScale = (Button)findViewById(R.id.scale);
        Button btnRotate = (Button)findViewById(R.id.rotate);
       
        btnTranslate.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    arg0.startAnimation(animTranslate);
   }});
       
        btnAlpha.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    arg0.startAnimation(animAlpha);
   }});
       
        btnScale.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    arg0.startAnimation(animScale);
   }});
       
        btnRotate.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    arg0.startAnimation(animRotate);
   }});
    }
}


Download the files here.

Video View in Adroid with Event Handler

We can Play Video in android with Video View . We can also implement our own event handlers and register with our VideoView using the methods setOnCompletionListener(), setOnPreparedListener() and setOnErrorListener().



Code
AndroidVideoViewActivity.java



package com.exercise.AndroidVideoView;

import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

public class AndroidVideoViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    VideoView myVideoView = (VideoView)findViewById(R.id.videoview);

    String viewSource ="rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQklThqIVp_AsxMYESARFEIJbXYtZ29vZ2xlSARSBWluZGV4YIvJo6nmx9DvSww=/0/0/0/video.3gp";

    myVideoView.setVideoURI(Uri.parse(viewSource));
    myVideoView.setMediaController(new MediaController(this));

    myVideoView.setOnCompletionListener(myVideoViewCompletionListener);
    myVideoView.setOnPreparedListener(MyVideoViewPreparedListener);
    myVideoView.setOnErrorListener(myVideoViewErrorListener);

    myVideoView.requestFocus();
    myVideoView.start();
}

MediaPlayer.OnCompletionListener myVideoViewCompletionListener
= new MediaPlayer.OnCompletionListener(){

  @Override
  public void onCompletion(MediaPlayer arg0) {
   Toast.makeText(AndroidVideoViewActivity.this,
     "End of Video",
     Toast.LENGTH_LONG).show();
  }};
  
 MediaPlayer.OnPreparedListener MyVideoViewPreparedListener
 = new MediaPlayer.OnPreparedListener(){

  @Override
  public void onPrepared(MediaPlayer arg0) {
   Toast.makeText(AndroidVideoViewActivity.this,
     "Media file is loaded and ready to go",
     Toast.LENGTH_LONG).show();
   
  }};
  
 MediaPlayer.OnErrorListener myVideoViewErrorListener
 = new MediaPlayer.OnErrorListener(){

  @Override
  public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
   Toast.makeText(AndroidVideoViewActivity.this,
     "Error!!!",
     Toast.LENGTH_LONG).show();
   return true;
  }};
}


Layout, main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<VideoView
android:id="@+id/videoview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>

Download the Source here


Monday, January 30, 2012

Custom adapter for ListView to create bubble shaped list rows


For this example, I have created a ListView which has a custom background, and custom rows representing a conversation in bubble format.

Here's the screenshot to make things clear:



Find the whole source code at this link.

The whole concept works like this-
  • You create two layouts:
    • One for Even rows
    • One for Odd rows
  • These layouts are designed keeping in mind that they'll be used as layouts of a row.
  • Your code has an array containing the data that will be displayed in the list view.
  • Inside your code, write a simple class extending BaseAdapter.
    • In this class we implement following methods of Android.Widget.Adapter super class, in order to get things working:
      • getCount() - returns the total number of elements in your data array
      • getIterm() - returns the data item associated with the specified position in the data set. Not implemented at this point.
      • getItemId() - returns the row id associated with the specified position in the list. Not implemented at this point.
      • getView() - returns the row that has to be drawn. This is the method we're interested in the most. It will be called every time the ListView draws a new row.
        Here, you can control what gets drawn in a particular row, by selecting a layout and setting data into it.
        In our example, we are checking whether the position of the row is even or odd, and according to that, we are setting the row's layout.
  • I have also set a background to the layout which holds the list.
  • A list has a transparent background in normal conditions which makes you see the image that you set as the layout background, but when the List is scrolled, it doesn't remain transparent any more.
  • If you want you background image to be visible while scrolling too, set cacheColorHint of your ListView.

Refer to the project for more, and revert for feedback.

Download the source code here.
Happy Coding!

Thursday, January 19, 2012

Eclipse for Android C/C++ Development


Programming in C/C++ on Android is just awesome! This tutorial shows how to setup Eclipse for using C/C++ together with Java in Android projects.
0) Prerequisities
You need to have Google ADT (Android Development Tools) installed. See http://developer.android.com/sdk/eclipse-adt.html how to do it.
You also need Android ndk. Download it from http://developer.android.com/sdk/ndk/index.html and unpack it somewhere.
1) Install CDT (C/C++ Development Tools) into Eclipse.
Choose Help->Install New Software… from the main menu.
Choose http://download.eclipse.org/releases/galileo as the source site. If you have another Eclipse release than Galileo choose the appropriate url.
Click Next, Accept licences and finish the installation process.
2) In Eclipse create Android project to which you want to add C/C++ code (if you already don’t have one).
For this tutorial I’ve created simple MyAndroidProject.
3) In file manager create jni/ directory in your project directory and place your C/C++ sources file here. Also put here Android.mk file which is a makefile that tells Android build-system how to build your files.
Take a look into Android ndk docs/ANDROID-MK.html file how to create one.
Simple example of Android.mk file:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_LDLIBS    := -llog

LOCAL_MODULE    := native

LOCAL_SRC_FILES := native.c

include $(BUILD_SHARED_LIBRARY)
4)  Refresh (F5) directories in Package Explorer to see jni directory here. Open your .c/.cpp file.
Your .c/.cpp file (native.c in my case) contains a lot of syntax errors which are not truly syntax errors. This is because Eclipse threats the project as a pure Java project. We have to convert the project into mixed Java & C/C++ project.
5) Press Ctrl+n (or choose File->New->Other… from main menu) and selectConvert to a C/C++ Project.
This will convert your project into a mixed Java & C/C++ project rather than into pure C/C++ project (the name of the function is misleading).
Click Next. Then choose your project and below choose Makefile project and – Other Toolchain –. Click Finish.
After doing this Eclipse will ask you if you want to switch to C/C++ perspective. ChooseYes because otherwise you wouldn’t be able to set C/C++ build preferences.
6) Click on your project with right button and select Properties or press Alt+Enter
Properties windows will appear. Here you have to configure use of ndk-build instead of make all command and set proper include paths.
7) Choose C/C++ Build and configure ndk-build as a build command
In Builder settings fill ndk-build into Build command entry. You have to uncheck Use default build command. You also need to have ndk-build script in your PATH.
In Behaviour setting uncheck clean (ndk-build cleans project automatically on build and does not support separate clean command) and clear all text from build (ndk-build does not accept all as a parameter.
Click Apply to save settings.
8) Choose C/C++ General->Paths and Symbols and configure include path
In Includes tab choose GNU C or GNU C++ and click Add… button. Add path to include directory which is located in platforms/android-4/arch/arm/usr/include subdirectory of place where you’ve unpacked Android ndk. Include path depends on target for which you are compiling (android-4 in my case — i.e. Android 1.6).
Finally click Apply and OK and that is all. Now you can use all Eclipse power for editing your C/C++ sources. If you click Run or Debug Eclipse will compile C/C++ code as well as Java code and run it on device/emulator. However you will not be able to debug C/C++ code.