Blogs

Working with Text to Speech in Android

May 03, 2013 by Ravi Sharma

One of the many features that Android provides  is the one of “speech synthesis”.

This is also known as “Text-To-Speech” (TTS) and is mainly the capability of the device to “speak” text of different languages.

In this blog I am going to show you how to quickly introduce TTS capabilities into your application.

Here is the xml file

 

	<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

	 xmlns:tools="http://schemas.android.com/tools"

	 android:layout_width="match_parent"

	 android:layout_height="match_parent"

	 tools:context=".TTSActivity"

	 android:background="@drawable/canvas">

	
	    <EditText

	        android:id="@+id/enterText"

	        android:layout_width="fill_parent"

	        android:layout_height="wrap_content"

	        android:layout_alignParentLeft="true"

	        android:layout_alignParentTop="true"

	        android:layout_marginTop="105dp"

	        android:ems="10"        

	        android:textColor="#ffffff" >

	      
	    </EditText>

	

	    <TextView

	        android:id="@+id/textView"

	        android:layout_width="wrap_content"

	        android:layout_height="wrap_content"

	        android:layout_alignParentTop="true"

	        android:layout_centerHorizontal="true"

	        android:layout_marginTop="46dp"

	        android:text="Enter text below :-"

	        android:textSize="30dp"

	        android:textColor="#ffffff"/>

	

	    <Button

	        android:id="@+id/speakButton"

	        android:layout_width="150dp"

	        android:layout_height="70dp"

	        android:layout_centerHorizontal="true"

	        android:layout_centerVertical="true"

	        android:background="#2C70A0"

	        android:text="Speak" />

	

	</RelativeLayout>

 

Three basic views are used edittext, textview, button.

And, here is the TTS Activity.

 

	package com.example.texttospeech;

	

	import android.os.Bundle;

	import android.app.Activity;

	import android.speech.tts.TextToSpeech;

	import android.speech.tts.TextToSpeech.OnInitListener;

	import android.view.Menu;

	import android.view.View;

	import android.widget.Button;

	import android.widget.EditText;

	import android.widget.Toast;

	

	public class TTSActivity extends Activity implements OnInitListener {

	    TextToSpeech talker;

	    EditText enteredText;

	    Button speak;

	    String text;

	

	    @Override

	    protected void onCreate(Bundle savedInstanceState) {

	        super.onCreate(savedInstanceState);

	        setContentView(R.layout.activity_tts);

	        speak = (Button) findViewById(R.id.speakButton);

	        enteredText = (EditText) findViewById(R.id.enterText);

	        talker = new TextToSpeech(this, this);

	

	    }

	

	    @Override

	    public void onInit(int arg0) {

	

	        if (arg0 == TextToSpeech.SUCCESS) {

	            speak.setOnClickListener(new View.OnClickListener() {

	

	                public void onClick(View arg0) {

	                    text = enteredText.getText().toString();

	                    talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);

	                }

	            });

	

	        }

	    }

	

	}

 

In this activity whatever is entered in edittext you can hear that back by clicking on button.

Just implement the OnInitListener interface, within onInit method the check

if (arg0 == TextToSpeech.SUCCESS) ,

is very important since it might take some time for tts for initialisation so if this argument turns to be true only then you will be able to hear speech.

That's it. Hope it helps.

Here is the snapshot of working code.

Thanks,

Ravi Sharma

ravi.sharma@oodlestechnologies.com

Implementing Speedometer in Android

May 01, 2013 by Ravi Sharma

Making speedometer work in android can be one tough task since  not much is available on internet.

So in order to create your own app like SpeedTest you can use basic android view ---ImageView.

You will simply need two images one of speedmeter, other of needle. And rotate needle image based on download speed available.

So this blog will be helpful for implementing both speedometer and download manager.

Here is the working code for xml file (speedometer.xml).
 

	<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

	    xmlns:tools="http://schemas.android.com/tools"

	    android:layout_width="match_parent"

	    android:layout_height="match_parent"

	    tools:context=".MainActivity" >

	

	 <Button

	 android:id="@+id/download"

	        android:layout_width="150dp"

	        android:layout_height="70dp"

	        android:layout_alignParentBottom="true"

	        android:layout_alignParentLeft="true"

	        android:layout_marginBottom="13dp"

	        android:layout_marginLeft="300dp"

	        android:text="Begin Test" />

	

	 <ImageView

	 android:id="@+id/meter"

	 android:layout_width="wrap_content"

	 android:layout_height="wrap_content"

	 android:layout_alignParentLeft="true"

	        android:layout_alignParentTop="true"

	        android:layout_marginLeft="223dp"

	        android:layout_marginTop="26dp"

	        android:src="@drawable/meter" />

	

	    <ImageView

	        android:id="@+id/needle"

	        android:layout_width="130dp"

	        android:layout_height="20dp"

	        android:layout_alignBottom="@+id/meter"

	        android:layout_alignLeft="@+id/download"

	        android:src="@drawable/meter_needle" />

	

	 <TextView

	 android:id="@+id/speed"

	 android:layout_width="wrap_content"

	        android:layout_height="wrap_content"

	        android:layout_alignTop="@+id/meter"

	        android:layout_marginLeft="191dp"

	        android:layout_marginTop="55dp"

	        android:layout_toRightOf="@+id/meter"

	        android:text="TextView"

	        android:textSize="20dp"

	        android:textColor="#000000"/>

	

	</RelativeLayout>

You can adjust UI accordingly I have kept it simple since we are more interested in logic than UI.

You need to paste the images in drawable folder(res->drawable)

Make sure you position the needle correctly so that the rotation is good enough (can take few tests if you work with your own images).

I guess there ain't enough to explain in xml just two ImageViews, one TextView, one button thats it.

Here is the code we are more interested in.

Speedometer.class.

 

 

	package com.example.speedometer;

	

	import java.util.List;

	import android.net.Uri;

	import android.os.AsyncTask;

	import android.os.Build;

	import android.os.Bundle;

	import android.os.Handler;

	import android.annotation.SuppressLint;

	import android.app.Activity;

	import android.app.DownloadManager;

	import android.content.BroadcastReceiver;

	import android.content.Context;

	import android.content.Intent;

	import android.content.IntentFilter;

	import android.content.pm.PackageManager;

	import android.content.pm.ResolveInfo;

	import android.database.Cursor;

	import android.view.View;

	import android.view.animation.RotateAnimation;

	import android.widget.Button;

	import android.widget.ImageView;

	import android.widget.TextView;

	import android.widget.Toast;

	

	public class SpeedometerActivity extends Activity {

	

	ImageView needle;    

	long id;

	Handler h;

	    DownloadManager manager;

	    Button download;

	    Long startTime;

	    int check = 0;

	    String uri;

	    TextView speed;

	

	    @Override

	    protected void onCreate(Bundle savedInstanceState) {

	        super.onCreate(savedInstanceState);

	        setContentView(R.layout.speedometer);

	        download = (Button) findViewById(R.id.download);

	

	    }

	

	    @Override

	    protected void onResume() {

	        super.onResume();

	        h = new Handler();

	        new speedTask().execute();

	        speed = (TextView) findViewById(R.id.speed);

	    }

	

	    public class speedTask extends AsyncTask<Void, String, Void> {

	

	        protected void onPreExecute() {

	

	        }

	

	        protected void onProgressUpdate(final String... message) {

	            try {

	

	                download.setVisibility(View.VISIBLE);

	

	            } catch (Exception e) {

	                e.printStackTrace();

	            }

	

	        }

	

	        @Override

	        protected Void doInBackground(Void... params) {

	            try {

	

	            } catch (Exception e) {

	                e.printStackTrace();

	

	            }

	

	            return null;

	        }

	

	        @Override

	        protected void onPostExecute(Void result) {

	            // TODO Auto-generated method stub

	            super.onPostExecute(result);

	

	            try {

	

	                download.setOnClickListener(new View.OnClickListener() {

	

	                    public void onClick(View arg0) {

	                        downloadFile("testFile",

	                                "https://s3.amazonaws.com/TranscodeAppVideos2/macdonald3.mp4");

	

	                        registerReceiver(broadcast, new IntentFilter(

	                                DownloadManager.ACTION_DOWNLOAD_COMPLETE));

	

	                        startTime = System.currentTimeMillis();

	                        download.setEnabled(false);

	                        check = 1;

	                    }

	

	                });

	

	            } catch (Exception e) {

	                e.printStackTrace();

	

	            }

	

	        }

	

	    }

	

	    @SuppressLint("NewApi")

	    public void downloadFile(String fileName, String downloadUrl) {

	        String DownloadUrl = downloadUrl;

	        DownloadManager.Request request = new DownloadManager.Request(

	                Uri.parse(DownloadUrl.replace("https://", "http://")));

	        request.setDescription("Downloading..."); // appears the same in

	                                                    // Notification bar

	                                                    // while downloading

	        request.setTitle(fileName);

	        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

	            request.allowScanningByMediaScanner();

	            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

	        }

	        request.setDestinationInExternalPublicDir("/test/", fileName);

	        request.setVisibleInDownloadsUi(true);

	        // get download service and enqueue file

	        manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

	        id = manager.enqueue(request);

	

	        try {

	

	            final Runnable r2 = new Runnable() {

	                public void run() {

	

	                    h.postDelayed(this, 0000);

	

	                    DownloadManager.Query q = new DownloadManager.Query();

	                    q.setFilterById(id);

	                    Cursor cursor = manager.query(q);

	                    cursor.moveToFirst();

	

	                    Integer bytes_downloaded = cursor

	                            .getInt(cursor

	                                    .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));

	

	                    Long endTime = System.currentTimeMillis();

	                    Long toSeconds = (endTime - startTime);

	

	                    Long downloadedLength = Long.parseLong(bytes_downloaded

	                            .toString());

	                    Long tokB = (downloadedLength) / toSeconds;

	                    Long percentage = (downloadedLength / 11405) / 10;

	                    uri = cursor

	                            .getString(cursor

	                                    .getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));

	                    Integer totalLength = cursor

	                            .getInt(cursor

	                                    .getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

	

	                    if (downloadedLength < totalLength) {

	                        try {

	                            needle = (ImageView) findViewById(R.id.needle);

	                            ((TextView) speed).setText(tokB + " " + "kB/sec");

	                            RotateAnimation rpmNeedleDeflection = new RotateAnimation(

	                                    (float) (((downloadedLength) / toSeconds) / 2.78),

	                                    (float) (((downloadedLength) / toSeconds) / 2.78),

	                                    130, 0);

	                            rpmNeedleDeflection.setDuration(900);

	                            rpmNeedleDeflection.setFillAfter(true);

	                            needle.startAnimation(rpmNeedleDeflection);

	                            needle.refreshDrawableState();

	

	                        } catch (Exception e) {

	

	                        }

	                    }

	                    cursor.close();

	

	                }

	

	            };

	            h.postDelayed(r2, 0000);

	        } catch (Exception e) {

	            Toast.makeText(getBaseContext(), "try again", 3000).show();

	        }

	    }

	

	    public boolean isDownloadManagerAvailable(Context context) {

	        try {

	            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {

	                return false;

	            }

	            Intent intent = new Intent(Intent.ACTION_MAIN);

	            intent.addCategory(Intent.CATEGORY_LAUNCHER);

	            intent.setClassName("com.android.providers.downloads.ui",

	                    "com.android.providers.downloads.ui.DownloadList");

	            List<ResolveInfo> list = context.getPackageManager()

	                    .queryIntentActivities(intent,

	                            PackageManager.MATCH_DEFAULT_ONLY);

	            return list.size() > 0;

	        } catch (Exception e) {

	            return false;

	        }

	    }

	

	    BroadcastReceiver broadcast = new BroadcastReceiver() {

	        @Override

	        public void onReceive(Context context, Intent intent) {

	

	            String action = intent.getAction();

	            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

	                Long endTime = System.currentTimeMillis();

	

	                Long toSeconds = (endTime - startTime);

	                Long tokB = 11405 / (toSeconds / 1000);

	

	                download.setEnabled(true);

	                RotateAnimation rpmNeedleDeflection = new RotateAnimation(

	                        (float) (tokB / 2.78), (float) (tokB / 2.78), 130, 0);

	                rpmNeedleDeflection.setDuration(1900);

	                rpmNeedleDeflection.setFillAfter(true);

	                needle.startAnimation(rpmNeedleDeflection);

	                needle.refreshDrawableState();

	            }

	

	        }

	

	    };

	

	@Override

	public void onDestroy() {

	if (check == 1)

	            unregisterReceiver(broadcast);

	

	        super.onDestroy();

	    }

	

	}

To start with you got to use background task to download file from internet. In downloadFile() method, You have to query DownloadManager using DownloadManager.Query class so that you can find out the downloaded bytes so far. And based on that you can find the number of seconds and divide to obtain speed. It's android's RotateAnimation that does all the work of rotating image. It requires four parameters, fromDegrees, to Degrees(speed) pivotX , pivotY. I have divided speed furthur by 2.78 so as to accomodate the speed into degrees.This changes based on your image range. And that's all . Just make sure you provide internet, write_external_storage permission as well in your manifest file.

Here is the output

Thanks,

 

Ravi Sharma

ravi.sharma@oodlestechnologies.com

 

Facebook Style Slide Menu In Android

April 25, 2013 by ARPIT SHARMA

Today I will blog on Facebook style slide menu in android, you have to follow the given step in order to implement fb style menu.

  • Create a new android project in eclipse(Minimum Required Android SKD 2.2 ).
  • Download slider.jar file from here.
  • Place slider.jar in lib folder in project

Now our basic project structure is ready and its time to focus on layouts, replace main.xml code from given one. 

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/left_buton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Left Menu" />

    <Button
        android:id="@+id/right_buton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Right Menu" />

</RelativeLayout>

 

  • Create two  Android XML Files one for left menu and other for right menu say "left_menu.xml" and "right_menu.xml".

 

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="260dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Left Menu"
        android:textColor="#ffffff" />

</LinearLayout>

 

<?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:background="#000000"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="260dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Right Menu"
        android:textColor="#ffffff" />

</LinearLayout>
  • There are some pre defined funstions in "slider.jar" which help us to create fb style slide menu.

         * setLeftBehindContentView(left_layout) is used to set left menu.

         * setRightBehindContentView(right_layout) is used to set right menu.

         *  toggleLeftDrawer() is used to show the left menu.

         * toggleRightDrawer() is used to show the right menu.

 

  • Now, open "MainActivity.java" and place the given code in it.

 

package com.example.slide_menu;

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

import com.navdrawer.SimpleSideDrawer;

public class MainActivity extends Activity {
	SimpleSideDrawer slide_me;
	Button left_button, right_button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		slide_me = new SimpleSideDrawer(this);
		slide_me.setLeftBehindContentView(R.layout.left_menu);
		slide_me.setRightBehindContentView(R.layout.right_menu);

		left_button = (Button) findViewById(R.id.left_buton);
		right_button = (Button) findViewById(R.id.right_buton);
		left_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				slide_me.toggleLeftDrawer();
			}
		});
		right_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				slide_me.toggleRightDrawer();
			}
		});
	}
}

 

Download Source Code

 

Arpit Sharma

arpit.sharma@oodlestechnologies.com

http://oodlestechnologies.com/

Working with Graphs using AndroidPlot in Android

March 12, 2013 by Ravi Sharma

Android provides various libraries to draw graphs. But AndroidPlot is a fairly simple library to use.

In your project copy the androidplot library in libs folder.

The xml file is as follows-
 

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

	

	    <com.androidplot.xy.XYPlot

	        android:id="@+id/graph"

	        android:layout_width="fill_parent"

	        android:layout_height="fill_parent"

	        title="Profit vs Year"/>

	

	</LinearLayout>


You can give any title you like depending on your requirements.

Following is the java code.
 

	public class GraphDemo extends Activity {

	public XYPlot xyPlot;

	    

	    

	    @Override

	    protected void onCreate(Bundle savedInstanceState) {

	        super.onCreate(savedInstanceState);

	        

	        setContentView(R.layout.activity_graph_demo);

	                       

	                

	                xyPlot = (XYPlot) findViewById(R.id.graph);

	                

	                Number[] company1 = {20,12,40,30,70};

	                Number[] company2 = {10,1,50,40,70};

	              

	                XYSeries series1 = new SimpleXYSeries(

	                        Arrays.asList(company1),         

	                        SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,

	                        "Company1");                       

	

	                XYSeries series2 = new SimpleXYSeries(

	                        Arrays.asList(company2),         

	                        SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,

	                        "Company2");    

	

	                LineAndPointFormatter company1Format = new LineAndPointFormatter(

	                        Color.BLUE,                  

	                        Color.BLACK,                  

	                        null);                                  

	

	                LineAndPointFormatter company2Format = new LineAndPointFormatter(

	                        Color.YELLOW,                   

	                        Color.BLACK,                

	                        null);                                  

	                xyPlot.addSeries(series1, company1Format);

	

	               

	                xyPlot.addSeries(series2, company2Format);

	                xyPlot.setDomainValueFormat(new Format() {

	

	                    @Override

	                    public StringBuffer format(Object obj, StringBuffer toAppendTo,

	                            FieldPosition pos) {

	                        return new StringBuffer ();

	                    }

	

	                    @Override

	                    public Object parseObject(String source, ParsePosition pos) {

	                        return null;

	                    }

	                });

	                xyPlot.setDomainLabel("Year");

	                xyPlot.setRangeLabel("Amount in Crore");        

	

	           

	                xyPlot.setTicksPerRangeLabel(2);

	

	               

	                xyPlot.disableAllMarkup();

	            }

	        }

	    

Code is fairly simple.

Refer the graph view by using id "graph".
Create two arrays of type Number, enter any values you want.

Then,turn the above arrays into XYSeries:
Create a formatter to use for drawing a series using LineAndPointRenderer.

First parameter gives color to line, second to points, thirs colors the area covered(better leave it as null).

Add series to xyplot.

Create as many series as number of lines you want to plot in the graph.

Lastly, give names to x, y axis.
 

And here is the output.

 

Dynamically adding view to viewgroup in Android

February 22, 2013 by Ravi Sharma

Here I will discuss how to add view to viewgroup dynamically in android.

To create flexible UI it is better to create view progmatically rather than using xml file.

Here I will explain how to add tablelayout dynamically and populate it.

Here is the xml file-

 

	<?xml version="1.0" encoding="utf-8"?>

	<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

	    android:id="@+id/rl"

	    android:layout_width="match_parent"

	    android:layout_height="match_parent"

	    android:orientation="horizontal" >

	

	
	 <TableLayout

	 android:id="@+id/tab"

	 android:layout_width="750dp"

	 android:layout_height="70dp"

	 android:layout_marginLeft="20dp"

	 android:layout_marginTop="75dp"

	 android:layout_weight="0.95"

	 android:background="@drawable/rounded_table1"

	 android:shrinkColumns="*"

	 android:stretchColumns="*">

	
	</TableLayout>

	
	 <TableRow

	                android:id="@+id/tableRow1"

	                android:layout_width="wrap_content"

	                android:layout_height="200dp"

	                android:gravity="center_horizontal"

	                android:layout_margin="2dp"

	                android:background="@drawable/rounded_table"

	                 >

	

	                <TextView

	                    android:id="@+id/textView1"

	                    android:layout_width="wrap_content"

	                    android:layout_height="70dp"

	                    android:gravity="center"

	                    android:text="Time"

	                    android:textSize="30dp"                   

	                    android:textColor="#FFFFFF"/>

	

	                <TextView

	                    android:id="@+id/textView2"

	                    android:layout_width="wrap_content"

	                    android:layout_height="wrap_content"

	                    android:gravity="center"

	                    android:text="Date"

	                    android:textSize="30dp"                   

	                    android:textColor="#FFFFFF"/>

	

	                <TextView

	                    android:id="@+id/textView3"

	                    android:layout_width="wrap_content"

	                    android:layout_height="wrap_content"

	                    android:gravity="center"

	                    android:text="Description"

	                    android:textSize="30dp"                   

	                    android:textColor="#FFFFFF"/>

	

	            </TableRow>

	

	</TableLayout>

	</RelativeLayout>

	

 

Here the relativelayout is given an id because that is how we will refer to it in code.
It is not necessary to add tablelayout in xml but just to compare both xml , coding styles I added it.

Now in java code we will do the following to add tablelayout.
 

	public class tableView extends Activity {

	

	RelativeLayout rl

	
	public void onCreate(Bundle savedInstanceState) {

	        super.onCreate(savedInstanceState);

	        setContentView(R.layout.activity_tableView);                    

	        rl=(RelativeLayout)findViewById(R.id.rl);           

	       

	        TableLayout MainLayout = new TableLayout(getApplicationContext());  

	     

	             TableRow tr = new TableRow(getApplicationContext());

	             

	                 tr.setPadding(0, 10, 0, 0);

	                     tr.setGravity(Gravity.CENTER);

	                      tr.setBackgroundResource(R.drawable.rounded_table1);   

	                      tr.setLayoutParams(new LayoutParams(

	                             LayoutParams.FILL_PARENT,

	                             LayoutParams.WRAP_CONTENT));

	                   /* Create a textView to be the row-content. */

	            

	                      TextView textView = new TextView(getApplicationContext());

	                                textView.setTextColor(Color.WHITE);

	                                textView.setGravity(Gravity.CENTER);

	                               textView.setText("10:10");

	                                textView.setTextSize(25);

	                                textView.setHeight(88);

	             

	                    tr.addView(textView);

	                

	                    TextView textView1 = new TextView(getApplicationContext());

	                     textView1.setTextColor(Color.WHITE);

	                           textView1.setText("22 Feb 2013");

	                          textView1.setTextSize(25);

	                           textView1.setGravity(Gravity.CENTER);

	                           textView1.setHeight(88);

	             

	                  tr.addView(textView1);

	                

	                  TextView textView2 = new TextView(getApplicationContext());

	                          textView2.setTextColor(Color.WHITE);

	                          textView2.setText("Hello");   

	                          textView2.setGravity(Gravity.CENTER);

	                          textView2.setTextSize(25);

	                          textView2.setHeight(88);

	                     

	                     tr.addView(textView2);

	               

	                

	                  TableLayout.LayoutParams tableRowParams=

	                           new TableLayout.LayoutParams

	                           (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);

	

	                        

	                         tableRowParams.setMargins(3,3,3,0);

	                        

	                         tr.setLayoutParams(tableRowParams);

	                         ((TableLayout)MainLayout).addView(tr,tableRowParams);

	                         ((TableLayout)MainLayout).setStretchAllColumns(true);

	                        

	                         ((TableLayout)MainLayout).setBackgroundResource(R.drawable.rounded_table);                     

	                                                 

	       

	                RelativeLayout.LayoutParams tableRowParams1=

	                           new RelativeLayout.LayoutParams

	                           (1000,300);                       

	                         tableRowParams1.setMargins(3,180,3,0);                       

	                         MainLayout.setLayoutParams(tableRowParams1);

	                         rl.addView(MainLayout,tableRowParams1);                       

	                                    

	        }

	

	

	 }

 


 
Firstly, we refer the viewgroup using id "rl".

Then create tablelayout, tablerow , three textviews .

 tr.addView(textView), adds text to table row.

 ((TableLayout)MainLayout).addView(tr,tableRowParams), adds table to tablelayout.
 
 rl.addView(MainLayout,tableRowParams1), adds tablelayout to the viewgroup.

And thats it we have successfully added view dynamically to viewgroup.

Thanks,

Ravi Sharma

ravi.sharma@oodlestechnologies.com
 
 

 

 

Working with MediaController, VideoView in Android

February 11, 2013 by Ravi Sharma

This blog will be helpful to those who would like to use MediaController, include Video Content in their android apps.

Playing video content in android is fairly simple. Here, I will be talking about how to play video from Amazon s3.

In your xml file , paste the following-

 

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

   <VideoView
       android:id="@+id/video_view"
       android:layout_width="match_parent"
       android:layout_height="600dp"
      />

</LinearLayout>  

 

Here, VideoView is the view which will allow you to play the video at runtime.you may set width, height accordingly. In your activity, use the following code to play video-

 

void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_play_video);
		video = (VideoView) findViewById(R.id.video_view);

		new BackgroundAsyncTask()
				.execute("https://s3.amazonaws.com/TranscodeAppVideos/ocean.mp4");

						
			
	}

I have used AsyncTask to perform background operations.

The parameter passed is the url of the video stored in Amazon s3 bucket.

Following is the Background task.


public class BackgroundAsyncTask extends AsyncTask<String, Uri, Void> {
		Integer track = 0;
		ProgressDialog dialog;

		protected void onPreExecute() {
			dialog = new ProgressDialog(PlayVideo.this);
	        dialog.setMessage("Loading, Please Wait...");
	        dialog.setCancelable(true);
	        dialog.show();
		}

		protected void onProgressUpdate(final Uri... uri) {

			try {

				media=new MediaController(PlayVideo.this);
				video.setMediaController(media);
				media.setPrevNextListeners(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// next button clicked

					}
				}, new View.OnClickListener() {
					@Override
					public void onClick(View v) {

						finish();
					}
				});
				media.show(10000);

				video.setVideoURI(uri[0]);
				video.requestFocus();
				video.setOnPreparedListener(new OnPreparedListener() {

				    public void onPrepared(MediaPlayer arg0) {
				    	video.start();
						dialog.dismiss();
				    }
				});
				

			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			

		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				Uri uri = Uri.parse(params[0]);
				
				publishProgress(uri);
			} catch (Exception e) {
				e.printStackTrace();

			}

			return null;
		}

		
	}

The string passed is parsed as Uri. Then onProgressUpdate is called where ultimately video is played.

Playing online video is a long task so I have used Progress dialog which indicates of long background progress going on.

Also, I have used MediaController class so that you could see the pause, back and next button on tapping the video.

You can also program the functionality on back , next button like I have done here.

 

media.setPrevNextListeners(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// next button clicked

					}
				}, new View.OnClickListener() {
					@Override
					public void onClick(View v) {

						finish();
					}
				});
				media.show(10000);

I finish the current activity playing video on click of back button.

Also use the internet permission in the Android Manifest file.

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

And , finally after running the app you should see something like below-

Thanks,

 

Ravi Sharma,

ravi.sharma@oodlestechnologies.com

 

Drawing graphs in Android using aChartEngine charting library (Pie Charts)

February 03, 2013 by ankush gulati

Using Pie Charts in Android

1) We will create a sample pie chart displaying % of shares held by four different personnels.

2) aChartEngine has the capability to show Pie Chart in two ways too i.e.

   a) As a separate Activity.

   b) as a view to be embedded in current activity.

   c) we will be using the second approach, but we will be creating a new activity PieChart and then we will embed the PieChartView in that activity.

3) So, first of all, create a new android activity and name it as PieChart.

4) Now, navigate to "/res/layout" and select the xml file associated with above activity. In this case, activity_pie_chart.xml and paste the following code there.

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

	<LinearLayout android:id="@+id/chart" android:orientation="horizontal"
		android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" />

</LinearLayout>
        

.

Notice that we have created an empty container with id "chart". This layout will contain the actual pie chart generated.

5) Now, navigate to PieChart.java file and replace the code with below code:


import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

public class PieChart extends Activity {

	int[] pieChartValues={25,15,20,40};
	
	  public static final String TYPE = "type";
	  private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN };
	  private CategorySeries mSeries = new CategorySeries("");
	  private DefaultRenderer mRenderer = new DefaultRenderer();
	  private GraphicalView mChartView;

	  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pie_chart);
		
		    mRenderer.setApplyBackgroundColor(true);
		    mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
		    mRenderer.setChartTitleTextSize(20);
		    mRenderer.setLabelsTextSize(15);
		    mRenderer.setLegendTextSize(15);
		    mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
		    mRenderer.setZoomButtonsVisible(true);
		    mRenderer.setStartAngle(90);
		    
		    if (mChartView == null) {
			      LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
			      mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
			      mRenderer.setClickEnabled(true);
			      mRenderer.setSelectableBuffer(10);
			      layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
			          LayoutParams.FILL_PARENT));
			    } else {
			      mChartView.repaint();
			    }
			fillPieChart();
	}
	
	public void fillPieChart(){
		for(int i=0;i<pieChartValues.length;i++)
		{
			 mSeries.add(" Share Holder " + (mSeries.getItemCount() + 1), pieChartValues[i]);
		        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
		        renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
		        mRenderer.addSeriesRenderer(renderer);
		        if (mChartView != null)
		           mChartView.repaint();     
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}
        

   a) The working of code is almost similar to that of Bar chart. Renderer is used to actually draw the Pie chart and we created a Dataset as a sample array:

int[] pieChartValues={25,15,20,40};
        

It may vary according to your requirements.

   b) Then, we declare the different colors which will be used the differentiate the graph area. In our case,

private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN };
        

   c) Then we have to declare some basic characteristics for renderer such as title, title size, margin, zoom option or start angle etc. You can always modify it as per requirements. Since we are using another activity to display the Pie chart so we declare it in onCreate method of PieChart activity.

   d) Then we actually create reference of the "chart" layout we created in step 4 and assign the "chartView" to it and call the fillPieChart() method.

 if (mChartView == null) {
			      LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
			      mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
			      mRenderer.setClickEnabled(true);
			      mRenderer.setSelectableBuffer(10);
			      layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
			          LayoutParams.FILL_PARENT));
			    } else {
			      mChartView.repaint();
			    }
			fillPieChart();
        

   e) The Fx fillPieChart() populates the Pie Chart with the values provided in as in given step a.

6) Now, the working of PieChart is complete. So, we just need to start this activity when required. So, navigate to your activity_main.xml file, create a new button as:

    <Button
        android:id="@+id/generatePieChart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="45dp"
        android:text="Generate Pie Chart --->" />
        

7) Now in your MainActivity.java file, start the PieChart activity on click of this button as:

		Button genPieChart=(Button)findViewById(R.id.generatePieChart);
		genPieChart.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent pieChartIntent=new Intent(MainActivity.this,PieChart.class);
				startActivity(pieChartIntent);
			}
		});
        

8) Now, run your project in emulator or device, click on "generate Pie Chart -->" button and you will see something like below screenshot.

Hope it helps :)

Ankush Gulati

ankush.gulati@oodlestechnologies.com

Downloading and Retrieving Files on SD card in Android using Android SDK in Eclipse

January 31, 2013 by ankush gulati

Each android device supports external storage (SD card) which can be used directly by user to save multimedia content as well as by an app to save it's data. Since the Internal storage of a device is very limited so it becomes a necessity for an app to transfer the large files to SD card. 

Downloading Files in Android:

In Android version 2.3 Gingerbread (API level 9), a new service was added to android OS "DownloadManager" specially for the purpose of downloading files throughout HTTP requests. It automatically manages the Progress bar in Notification, large sized Files, Retry Download if fail or even after the device reboots. So, currently it's the best solution for downloading files. Below are the steps to create a simple application for testing purpose:

1. Create a new Android project in Eclipse.

2. Select Blank Activity.

3. In Activity_main.xml file, Place the below code.

  a.) One button to start downloading a file throughout internet.

  b.) Another button to Generate the list of files present in app directory.

  c.) Edit Text to display the list of files in app directory.

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <EditText
        android:id="@+id/listOfFiles"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:inputType="textMultiLine" >
        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/getListOfFilesBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/listOfFiles"
        android:layout_marginTop="17dp"
        android:text="Get the list" />
    <Button
        android:id="@+id/fileDownloadBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/getListFiles"
        android:layout_marginTop="15dp"
        android:text="Download sample file" />
</RelativeLayout>

4. In your MainActivity.java file, paste the below code in OnCreate method of Activity

                
	Button fileDwnloadBtn=(Button)findViewById(R.id.fileDownloadBtn);
		fileDwnloadBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Boolean result=isDownloadManagerAvailable(getApplicationContext());
				if (result)
					downloadFile();
			}
		});

        

5. Paste the below two functions in same MainActivity class.

        @SuppressLint("NewApi")
	public void downloadFile(){
		String DownloadUrl = "Paste Url to download a pdf file here…";
		DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
		request.setDescription("sample pdf file for testing");   //appears the same in Notification bar while downloading
		request.setTitle("Sample.pdf");					
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
		    request.allowScanningByMediaScanner();
		    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		}
		request.setDestinationInExternalFilesDir(getApplicationContext(),null, "sample.pdf");

		// get download service and enqueue file
		DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
		manager.enqueue(request);
	}

	public static boolean isDownloadManagerAvailable(Context context) {
	    try {
	        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
	            return false;
	        }
	        Intent intent = new Intent(Intent.ACTION_MAIN);
	        intent.addCategory(Intent.CATEGORY_LAUNCHER);
	        intent.setClassName("com.android.providers.downloads.ui","com.android.providers.downloads.ui.DownloadList");
	        List <resolveinfo> list = context.getPackageManager().queryIntentActivities(intent,
	                PackageManager.MATCH_DEFAULT_ONLY);
	        return list.size() > 0;
	    } catch (Exception e) {
	        return false;
	    }
	}
      

 

a) isDownloadManagerAvailable Function queries and returns a boolean indicating whether the Download Manager Service for device's OS version or not (not available in Android version less than 2.3).

b) IF the above function returns TRUE, only then we can use the downloadFile method.

c) downloadFile function makes use of the DownloadManager manager to enqueue the download request and the process starts.

d) Notice this line:

             request.setDestinationInExternalFilesDir(getApplicationContext(),null, "sample.pdf");   
        

It simply places the file "sample.pdf" in your "/sdcard/Android/data/Your_Projects_PackageName/files/" directory.This directory is private to your app only. It will create this directory if doesn't exist already.

e) If You want the downloaded file to go to the default "Downloads" directory of SD card, replace the above line with below line:

            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "sample.pdf"); 
        

It's a public directory.

6. Now, Lastly, define the below two permissions in your AndroidManifest.xml file:

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

7. Now, Either create Emulator with SD card or test it on device. After giving proper download URL and Clicking on "Download File" button, downloading will start and you can see the progress in Notification bar like screenshot below.

 

Retrieving Files from SD card:

1. There are several ways to retrieve the list of files present in a particular directory of SD card. We'll be using the simplest approach.

2. Place the below code in your MainActivity.java file's OnCreate method of main activity:

		EditText listOfFiles=(EditText) findViewById(R.id.listOfFiles);
		Button getListBtn=(Button)findViewById(R.id.getListOfFilesBtn);
		
		getListBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if (Environment.MEDIA_MOUNTED.equals(state)) {
				    // We can read and write the media
				    Toast.makeText(getApplicationContext(), "Media Mounted status: true", 5000).show();	    
				    try
				    {
				        File mfile=new File("/sdcard/Android/data/Your_Projects_PackageName/files/");
						File[] list=mfile.listFiles();
						if (list.length==0)
							listOfFiles.setText("Folder is empty");
						else
						{
							for(int i=0;i < list.length;i++)
								listOfFiles.setText("\n"+list[i].getName());
						}
				    }
				    catch(Exception e)
				    {
				    	Toast.makeText(getApplicationContext(), "Exception: Folder not created yet", 5000).show();
				    }
					
				} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
				    Toast.makeText(getApplicationContext(), "Media Mounted status: Read only access", 5000).show();
				} else {
				    Toast.makeText(getApplicationContext(), "Media Mounted status: Error occured", 5000).show();
				}
			}
		});

3. The Above code simply generates the list of files present in app's data folder and displays the list in Edit Text. (if there is no permission or access error).

 

Hope it helps  :)

Ankush Gulati

ankush.gulati@oodlestechnologies.com

Drawing graphs in Android using aChartEngine charting library (Bar Charts)

January 30, 2013 by ankush gulati

In this blog, I will explain how to use charts in android in the easiest way. There are different ways to implement charts in Android such as:

1. Google Charts

2. aChartEngine charting library

3. AndroidPlot

Each comes with it's advantages and disadvantages. Like, internet is necessary if one wants to use google charts in Android app. The aChartEngine library provides support for a wide range of charts like Line, Bar and Pie etc. We will be using this library to demonstrate how to make graphs in Android. You can download the latest code and docs as well as demo app from following link: http://www.achartengine.org/  . We will be making a single project to explain all three basic types of charts.

  • Create a new Android Project, select Blank activity.

  • Create the "libs" folder under your projects root directory, if it doesn't already exist.

  • Place the achartengine's latest jar file in this "libs" folder.

  • Now, we are ready to use graphs in Android using aChartEngine.

Using Bar Charts in Android

1. We will be creating a bar chart displaying growth comparison between two companies over 10 years.

 2. aChartEngine has the capability to render and return the graph by two ways:

   a) It can return a Graph Activity.

   b) Or it can return a Graph view, which can be embedded in another activity or fragment etc.

   c) We'll be using the first approach. i.e. GraphActivity

3. So, First of all, navigate to your AndroidManifest.xml file and place following line there.

<activity android:name="org.achartengine.GraphicalActivity" />
        

4. Now, navigate to your "activity_main.xml" file and place a button clicking on which will open the bar graph. Something like:

    <Button
        android:id="@+id/generatePieChart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="45dp"
        android:text="Generate Pie Chart --->" />
        

5. Now it's time to actually code for Bar graph. Navigate to your MainActivity.java file and paste the below two lines in MainActivity class. These two arrays contain the sample values which will be used to draw the graph. You are free to modify or change according to requirements.

	 int[] firstData={23,145,67,78,86,190,46,78,167,164};
	 int[] secondData={83,45,168,138,67,150,64,87,144,188};
        

6. Now add the following functions in your MainActivity class.


	public void getBarChart(){
		XYMultipleSeriesRenderer barChartRenderer = getBarChartRenderer();
	    setBarChartSettings(barChartRenderer);
		Intent intent = ChartFactory.getBarChartIntent(this, getBarDemoDataset(), barChartRenderer, Type.DEFAULT);
	    startActivity(intent);
		}
	
	 private XYMultipleSeriesDataset getBarDemoDataset() {
		    XYMultipleSeriesDataset barChartDataset = new XYMultipleSeriesDataset();
				    CategorySeries firstSeries = new CategorySeries("Growth of Company1");
				    for(int i=0;i<firstData.length;i++)
				    	firstSeries.add(firstData[i]);
				    barChartDataset.addSeries(firstSeries.toXYSeries());
		    
		    	 CategorySeries secondSeries = new CategorySeries("Growth of Company2");
				    for(int j=0;j<secondData.length;j++)
				    	secondSeries.add(secondData[j]);
				    barChartDataset.addSeries(secondSeries.toXYSeries());
		    return barChartDataset;
		  }
	 
	 public XYMultipleSeriesRenderer getBarChartRenderer() {
		    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		    renderer.setAxisTitleTextSize(20);
		    renderer.setChartTitleTextSize(18);
		    renderer.setLabelsTextSize(18);
		    renderer.setLegendTextSize(18);
		    renderer.setMargins(new int[] {20, 30, 15, 0});
		    SimpleSeriesRenderer r = new SimpleSeriesRenderer();
		    r.setColor(Color.BLUE);
		    renderer.addSeriesRenderer(r);
		    r = new SimpleSeriesRenderer();
		    r.setColor(Color.GREEN);
		    renderer.addSeriesRenderer(r);
		    return renderer;
		  }
	 private void setBarChartSettings(XYMultipleSeriesRenderer renderer) {
		    renderer.setChartTitle("Growth comparison company1 vs company2");
		    renderer.setXTitle("No of Years in industry");
		    renderer.setYTitle("Profit in millions");
		    renderer.setXAxisMin(0.5);
		    renderer.setXAxisMax(10.5);
		    renderer.setYAxisMin(0);
		    renderer.setYAxisMax(210);
		  }
        

   a) Renderer and Dataset are two basic elements of a Graph Activity.

   b) Dataset and Renderer should have same number of series. i.e if you want to design a bar graph for two dataset comparisons, there must be two renderers.

   c) The Fx "getBarDemoDataset()" simply returns an object of XYMultipleSeriesDataset class. Since we are using two series as described in step 5, so we are creating two series and adding both series to Dataset.

   d) The Fx getBarChartRenderer() creates and returns an object of XYMultipleSeriesRenderer class defining it's specific attributes such as color of two bars and text size, margin etc.

   e) The Fx setBarChartSettings() manages the most basic characteristics of a bar chart like X or Y axis, min or max values, title to be displayed etc.

   f) The Fx getBarChart() binds all the above functions together and call for intent for Graph Activity.

   g) Organize the imports if missing.

7) Now, in your MainActivity.java file, create object of the button you created in step4 and call the getBarChart() function. Paste the following lines in onCreate() method of MainActivity:

Button genBarChart=(Button)findViewById(R.id.generateBarChart);
genBarChart.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				getBarChart();
			}
		});
        

8) Now, Run the project on emulator or device and click on "Generate Bar Chart --->" button and you will see something like following screenshot.

Hope it helps :)

Ankush Gulati

ankush.gulati@oodlestechnologies.com

Drawing graphs in Android using aChartEngine charting library (Line Charts)

January 25, 2013 by ankush gulati

Using Line Chart in Android

1) We will create a sample Line chart displaying two sample values set.

2) aChartEngine has the capability to show Line Chart in two ways too i.e.

   a) As a separate Activity.

   b) as a view to be embedded in current activity.

   c) we will be using the second approach, but we will be creating a new activity LineChart and then we will embed the LineChartView in that activity.

3) So, first of all, create a new android activity and name it as LineChart.

4) Now, navigate to "/res/layout" and select the xml file associated with above activity. In this case, activity_Line_chart.xml and paste the following code there.

<?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">	
	<LinearLayout
	    android:id="@+id/chart"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_weight="0.81"
	    android:orientation="horizontal" />
</LinearLayout>
        

Notice that we have created an empty container with id "chart". This layout will contain the actual Line chart generated.

5) Now, navigate to LineChart.java file and replace the code with below code:

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

public class LineChart extends Activity {
	public static final String TYPE = "type";
	private XYMultipleSeriesDataset mDataset = getDemoDataset();
	private XYMultipleSeriesRenderer mRenderer = getDemoRenderer();
	private GraphicalView mChartView;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_line_chart);

		setRendererStyling();
		if (mChartView == null) {
			LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
			mChartView = ChartFactory.getLineChartView(this, mDataset,
					mRenderer);
			mRenderer.setSelectableBuffer(100);
			layout.addView(mChartView, new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		} else
			mChartView.repaint();
	}

	private void setRendererStyling() {
		mRenderer.setApplyBackgroundColor(true);
		mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
		mRenderer.setAxisTitleTextSize(16);
		mRenderer.setChartTitleTextSize(20);
		mRenderer.setLabelsTextSize(15);
		mRenderer.setLegendTextSize(15);
		mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
		mRenderer.setZoomButtonsVisible(true);
		mRenderer.setPointSize(10);
	}

	private XYMultipleSeriesDataset getDemoDataset() {
		double[] seriesFirstY = {20,-20,67,180,-45,24,99,-34,-8};
		double[] seriesSecondY = {10,80,-40,-20,135,24,199,-34,80};
		
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

		XYSeries firstSeries = new XYSeries("Sample series One");
		for (int i = 0; i < 9; i++)
			firstSeries.add(i, seriesFirstY[i]);
		dataset.addSeries(firstSeries);

		XYSeries secondSeries = new XYSeries("Sample series Two");
		for (int j = 0; j < 9; j++)
			secondSeries.add(j, seriesSecondY[j]);
		dataset.addSeries(secondSeries);
		return dataset;
	}

	private XYMultipleSeriesRenderer getDemoRenderer() {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setMargins(new int[] { 20, 30, 15, 0 });
		XYSeriesRenderer r = new XYSeriesRenderer();
		r.setColor(Color.BLUE);
		r.setPointStyle(PointStyle.SQUARE);
		r.setFillBelowLine(true);
		r.setFillBelowLineColor(Color.WHITE);
		r.setFillPoints(true);
		renderer.addSeriesRenderer(r);
		r = new XYSeriesRenderer();
		r.setPointStyle(PointStyle.CIRCLE);
		r.setColor(Color.GREEN);
		r.setFillPoints(true);
		renderer.addSeriesRenderer(r);
		renderer.setAxesColor(Color.DKGRAY);
		renderer.setLabelsColor(Color.LTGRAY);
		return renderer;
	}
} 

  a) The working is almost similar to the previous charts in a way that renderer and dataset are required to draw the graph and the properties associated differ.

  b) First of all, we create a demoDataset by following two sets of values:

		double[] seriesFirstY = {20,-20,67,180,-45,24,99,-34,-8};
		double[] seriesSecondY = {10,80,-40,-20,135,24,199,-34,80};
        

  We chose only Y-axis points as X-axis will be just incremented from 0 to 8.

  c) The Fx getDemoDataset() generates the Dataset according to above two series and returns the XYMultipleSeriesDataset object.

  d) Next step is to create a demoRenderer. This task is achieved pin the getDemoRenderer() function. Renderer and Dataset must contain same number of series always (2 in our case) .

  e) After this, we need to style the Renderer according to our needs such as backgroundColor, label sizes etc. We defined e method for this purpose as setRendererStyling().

  f) Now, we just need to create the actual lineChartView and embed it. So, we use the following lines in our activity's onCreate() method.

mChartView = ChartFactory.getLineChartView(this, mDataset,mRenderer);
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        

6) Now, we need to start this activity. So, navigate to your activity_main.xml file and create yet another button. or paste the following code:

    <Button
        android:id="@+id/generateLineChart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="Generate Line Chart -->" />
        

7) Navigate to MainActivity.java file and start the LineChart activity on click of the recently created button.

Button genLineChart=(Button)findViewById(R.id.generateLineChart);
genLineChart.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent lineChartIntent=new Intent(MainActivity.this,LineChart.class);
				startActivity(lineChartIntent);
			}
		});
        

8) Now, start the project in emulator or device and you will see something like following screenshot:

Hope it helps :)

Ankush Gulati

ankush.gulati@oodlestechnologies.com

Powered byApache Solr

Follow Us

Recent Entries