Sunday, March 18, 2012

Saving Objects(Synchronized) in Files in Android


We can save the all the synchronized Objects in Android using File Connections even if the Object is a customized or user defined object.

 Saving the Objects:


step 1: 

Open a file using the below code.

File suspend_f = new File("/data/data/com.rama.rama/cache/check.txt");

here i had saved the file in the application space in the device which will be removed when the application is un-installed. You can save it any where. but you should remember it for further fetching of the objects.

Step 2:

Opening an outputStream for the File object and writing the object to file as shown below.

                fos = new FileOutputStream(suspend_f);
                oos = new ObjectOutputStream(fos);
                oos.writeInt(10);
                for(int i=0 ;i<10;i++)
                oos.writeObject(new Lecture("Mahesh"+i, "sta", "end", "one", true));

We should read the objects in the same order that you write objects.


Reading the Objects:


step 1:


Opening the file object just as like the above step1.

Step 2:


Opening InputStream of the File Object and reading the objects in the same order that we write in the file.


                fis = new FileInputStream(suspend_f);
                 ois = new ObjectInputStream(fis);
                 String s = "";
                 int j=ois.readInt();
                 for(int i=0;i                 {
                _l = (Lecture)ois.readObject();
                s+=_l;
                 }
The whole code can be downloaded from this link.
Blog Update
Custom Broadcasts:

Unlike system originated broadcasts, these are the broadcasts which are sent by user. Usually these are useful in communicating back with activity from services.

Step 1: Write the below code where ever you want to send a custom broadcast:

Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.vl.dumptruck.ACTION_LOGOUT");
sendBroadcast(broadcastIntent);

In above code, we are creating a Intent with custom action and broadcasting it.

Step 2: Write the below code in the class which will be responsible for receiving broadcasts:
private
BroadcastReceiver logoutReceiver;
IntentFilter logoutIntentFilter = new IntentFilter();
logoutIntentFilter.addAction("com.vl.dumptruck.ACTION_LOGOUT");
logoutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
             //perform the task here
        }
};
registerReceiver(logoutReceiver, logoutIntentFilter);

1. In the above code, we are creating an IntentFilter with the action same as specified when sending the broadcast.
2. And a BroadcastReceiver, which is responsible for performing a task upon receing the broadcast(override the onReceive() method).
3. Now, register the broadcast using registerReceiver() method by passing BroadcastReceiver and IntentFilter objects. Here receiver is to call the callback method onReceive() and intent filter is to check whether the the receiver is authorized to respond to the broadcasted intent.
4. Finally, unregister the broadcast receiver using unregisterReceiver() by passing the receiver object, otherwise you will get a broadcast leaked exception.

        unregisterReceiver(logoutReceiver);

Note: Be careful with registering and unregistering broadcasts.
1. If you register a broadcast in onCreate(), then you have to unregister it in onDestroy(), with this the activity is capable of receiving the broadcasts even when activity is in background(i.e, in onPause() state also).
2. If you register a broadcast in onCreate() and you dont want to respond to broadcasts when you are in background(onPause()), then unregister your receiver in onPause() and register again in onResume() to start receiving broadcasts again and finally unregister it in onDestroy().



Move Android Apps Installation to SD Card
Please start using the tag name  android:installation as shown below to enable the option  to move the installation files to SDCard.
           package="xxx.xx.xxxx"
          android:versionCode="1"
           android:versionName="0.9.6" android:installLocation= "auto" >
This property is introduced in Introduced in  API Level 8.

Sunday, January 29, 2012

Android Project Tracking & Management & Tools

BlogUpdater_1_27_2012.doc
        Hi friends, after a long time I want to help all of you people in the below concerns.
  1. Architecture:
  2. Exception Tracking
  3. 2DScrollView
  4. C2DM
  5. Tools
Architecture
        I know lot of you people knows about this. But, let me explain this for the other people. The structure of the project should be as shown in thebelow format.
In the above image the custom Activity is the Super Activity for all of the activities where you can add unique requirements throughout the project. i.e., Exception tracking/MenuItems handling according to currentModule etc…,
First of all we should take care about the architecture while we are starting a project which will helps you a lot in the process of project enhancements and re-usability.
package.ui: Here we need to add all the custom views that are developed. So that we can use these UI from anywhere in the project and can also be maintained same for all of your future projects.
package.util: Here we need to add all the constants and utility functions like validations for dates/times or project specific things which can be used from the project.
Dispatchmodule: This is the startup module for all the projects. So that you can easily identify the starting activity in all the projects.
        Every module should have an engine. All the activities should implement CustomActivity which is there in the package.ui which is implementing Activity.
Module1,2…..n:  Depending upon the project, the number of modules will be divided to manage the project with ease.
At any instant, we can know all the information about the project (i.e., Module ID, Activity ID, Stack which contains all the Activity instances which are running in the background etc…,).
NetworkHandler: We should write all the handlers which can give the project running status information. Every time we starting a module/activity, this class should be intimated with the corresponding information.
Exception Tracking:
         Here is a simple class file which will be very useful to track your Android applications even after sending it to the client or to the market or to the testers. This class will always track your application and it will get informed with all the exceptions (even if it is a Force Close).
How to use this:
  1. Just copy and paste the downloaded java file in to your project.
  2. Create an instance for this activity in the CustomActivity as shown below.
protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this);

 
  1. Just to start the exception tracking.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);                                                            mDamageReport.initialize();
}
  1. Closing/Stopping the tracker in the Activity.
protected void onDestroy() {
                                               mDamageReport.restoreOriginalHandler();
                                               mDamageReport = null;
                                               super.onDestroy();
                                    }
        Every thing done. You can get updated with crash or exceptions.
Customizing the Tracker:
                We can customize the way of getting the information of the exception or crash from the mobile device to the server. Either we can go for creating a specific web service to catch the crash report or else we can go for mail option in which we can respect the user’s privacy and can ask for his permission to send the mail.
private static final int SENDING_OPTION = 1;// 0 --> Send Through Mail (Need user interference)
                                                                      // 1 --> Sending without user interference or confirmation
By using this variable, we can select the options wether we can directly post it to our webservice or to take the user's permission by preparing a mail and asking him to send it. 
if we want to send it to a mail id the we can specify the mail id for the below variable
private static final String MSG_SENDTO = xyz@gmail.com;
private static final String BUG_TRACKER_URL = http://tracking.webservice/gather.php

// This is the webservice URL which is used to post the issue info
2DscrollView:
In Android, we should not add a scrollview to another scrollview.  Because, If we add in such  a way then it will leads to the memory issues. If you want both horizontal and vertical scrolls for a single view, then you should go for a CustomFrameView.
For further information about the 2Dscroll view please click on the below link.


C2DM:
Cloud To Device Messaging is a concept which is introduced in Android from OS version 2.2.  The concept of C2DM is to optimize the network usage of the Android applications in push notifications.
Normally for every application, in order to get the push notifications, we should have a separate thread /service running in the background of the operating system continuously hitting the server in equal intervals of time which will drains the battery of the device and unnecessary usage of network. If we want push notifications for ‘n’ number of applications, then we should run ‘n’ number of services to get the notifications for n applications.
For every Android device, there will be default Google service running in the background which will take care about all the Google applications in device. After 2.2, they gave us an option to use the same Google service. So, that there is no need of running separate threads for each and every application.
We should send the desired message with the device ID to the Google C2DM server. then, the message will be sent to the device from the Google C2DM server.
We can get the device ID from the device after registering it to the Google C2DM server. We should send this ID from device to our Application third party Server. Then after, the application server will send the message to that specific device by using this device ID.
The device ID will be updated every time when the Google server get refreshed. Then the Google server will automatically send a broadcast message to the device and then we should get the device ID again and should intimate about the change of the Device ID to application third party server. So, that the application server will send the messages by using the updated device ID.
I will update this later by adding the code snippets later.
TOOLS:
DDMS:
This is used to fetch the logs, process id’s  of the applications and to get the memory usage of the operating system and many more.
ADB:
This is used to install/uninstall/to fetch running devices/pushing or pulling files/opening shell/fetching logs/ starting or killing the adb server.
ADT:
 This is a plugin for eclipse, which will be helpful in developing android applications in Eclipse.
9-patch:
This tool is used to optimize the usage of assets. This tool will add a single line pixel around the image. In which we can specify whether the corresponding pixels can be stretched or not. If we change the white space to black, then it resembles that the corresponding pixels are stretchable.
Hierarchyviewer:
This is used to view the hierarchy of the layouts in the application. Even we can download the psd’d of the screen which will provide the complete information of the screen in photoshop.
Monkeyrunner:
 This is a tool for automation testing. We can specify the number of turns for testing basing on which it will test the application.
sqlite3:
 This is used to check the sqllite database.

Wednesday, August 10, 2011

Checking Internet Connection in Android

private boolean checkInternetConnection() {

ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {

//tryLogic;
return true;

} else {

Toast.makeText(Login.this, “Internet Connection Not Present”, Toast.LENGTH_LONG).show();
Log.v(TAG, “Internet Connection Not Present”);
return false;

}
}

Saturday, August 6, 2011

Exiting the Android Application Safely

Myblog.doc

Android don't have a proper option to exit the complete application with a single line code. The only option we can do is, just calling the finish in all the activities. Even after calling finish(), the static variables wont go, will be there even after restarting the application. In order to exit the application completely we have to follow the bottom trick. We should call “addActivityInstance” method from all the activities. This method will save all the activitiy instances in _list_screens which is nothing but a ArrayList<Activity>. Whenevr you want to exit the application, just call the method “closeAllScreens”. Where we just called the finish of all the activities and after that we are calling “android.os.Process.killProcess” to kill the whole process including all the static data.

public static void addActivityInstance(Activity _activity)

{

if( _list_screens == null )

{

_list_screens = new ArrayList<Activity>();

}

_list_screens.add(_activity);

}

public static void closeAllScreens()

{

if(_list_screens!=null)

for(int i=0;i<_list_screens.size();i++)

if(_list_screens.get(i)!=null)

_list_screens.get(i).finish();

try{

android.os.Process.killProcess(android.os.Process.myPid());

}catch(Exception e){

}

}

Tuesday, September 28, 2010

How to create a Calendar in Android.doc

How to create a Calendar in Android

Hi dudes, In Android there is no Calendar View (Android 2.2 version or above has Calendars). If u want it then we need to create our own Calendar. So, I had developed a dummy Calendar in Android.

Here is the simple code for Calendar. I used the Java Calendar so Java’s Calendar Limitation is this calendar’s Limitation.

You can download Source from here or here.

Implementation of “Please wait” Dialogues in Android projects

Implementing Dialogue boxes also plays with us some times. In order to handle it properly again it’s better to handle the AsyncTask in Android as shown in the previous blog for handling the list of Server Images downloading.

Here you can download the source for previous XML parsing with Dialog Bar Implementation.

You can download Source from here or here.


Sunday, July 11, 2010

Splashscreen, Customizing List, Connecting Internet, XML Parsing,Downloading Images, Updating the User Interface Images at Runtime

Hi Friends,

              Here is the next part of my blog. Here I am going to discuss about the important things today. Every project will starts with a splash in first page. So let’s discuss about the splash.

 

Splash Screen

              We need to display the logo at the middle of the screen, whatever the screen mode it may be. So in order to handle this we will use the below XML file.

 

<?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:background="@color/white">

 

<ImageView android:id="@+id/ImageView01"

android:scaleType="center"

android:layout_height="fill_parent"

android:layout_width="fill_parent"

android:layout_centerInParent="true" android:src="@drawable/sun">

</ImageView>

</LinearLayout>

 

In the above XML file we have a layout with an ImageView which is centered in parent, without stretching it completely to its parent. Here according to the background of the logo we need to change the background color of the layout. Here it is “@color/White” in the above example. These colors will be maintained in project\res\values\color.xml folder. We can add new colors, which are needed for our project over there. That’s it, our layout is ready now. Let’s go to source.

 

 

             

              There is a class named Handler in android which will be going to handle the assigned work to do after some particular time. You may already know that we can start the Activities by using the Intents, we will start the activity after a period of splashTime as shown below.

 

 

 

new Handler().postDelayed(new Runnable(){

            public void run() {

                          startActivity(new Intent(MainActivity.this, MainMenu.class));

                finish();

            }

        }, _splashTime);

 

              Finally we are moving to the main menu from splash. The whole above process works perfectly if and only if the logo doesn’t have designs and different colors on the background screen. If you have different kinds of logo with lot of background colors  then let’s go for the second option.

              Here we need to prepare two images of splash one is for portrait and another is for landscape.  Create a xml file in the folder project\res\layout-land\menu.xml with the same name in the layout folder. According to the screen mode the xml files will be used. But don’t forget to maintain the same names just like in \layout folder.

 

If we want Fade-in or fade-out effects for our splash then we need to create xml files with desired effects as shown below and need to place it in \anim folder.

 

 

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

<set>

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

              android:interpolator="@android:anim/accelerate_interpolator"

              android:fromAlpha="0.0"

              android:toAlpha="1.0"

              android:duration="1000" />

</set>

fromAlpha, toAlpha and duration will be used according to your requirements. If we change the values fromAlpha to toAlpha then we will get fadeout effect.

The total source with Fadein and Fadeout effects  can be downloaded from below link.

You can download the project with source from here. or You can download the project with source from here.

Customizing List, Connecting Internet, XML Parsing,Downloading Images, Updating the User Interface Images at Runtime, Handling UI without specifying height and width of any view in the layout

 

Connecting to the internet

              We have two methods in connecting the internet server.

1.      Get

2.      Post

In first method as you already know all the values will be appended to the url . In the second (Post) method we will send the data separately which is secured. I am going to give both the methods to connect the net.

1)Get Method

 

 

 

 

 

 

 

 

 

 

 

private InputStream openHttpConnection(String urlStr) {

                            InputStream in = null;

                            int resCode = -1;

                           

                            try {

                            Log.d("openHttpConnection", "URL:"+urlStr);

                            URL url = new URL(urlStr);

                            URLConnection urlConn = url.openConnection();//Opening Connection

                                         

                            if (!(urlConn instanceof HttpURLConnection)) {

                                          throw new IOException ("URL is not an Http URL");

                            }

                            Log.d("openHttpConnection", "httpConn:1");

                            HttpURLConnection httpConn = (HttpURLConnection)urlConn;

                            httpConn.setAllowUserInteraction(false);

            httpConn.setInstanceFollowRedirects(true);

            httpConn.setRequestMethod("GET");

            httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");

            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            Log.d("openHttpConnection", "setting requests and properties");

            httpConn.connect();

            Log.d("openHttpConnection", "Connected successfully");

           

            resCode = httpConn.getResponseCode();   

           

            Log.d("openHttpConnection", "resCode"+resCode);

            if (resCode == HttpURLConnection.HTTP_OK) {

                in = httpConn.getInputStream();

                Log.d("openHttpConnection", "Fetchinf data done");

            }        

                            } catch (MalformedURLException e) {

                                          e.printStackTrace();

                                          Log.d("openHttpConnection", "1"+e);

                            } catch (IOException e) {

                                          e.printStackTrace();

                                          Log.d("openHttpConnection", ""+e);

                            }

                            return in;

              }

 

The above code will connect to the specific site and will get the response and the data in the form of InputStream. The variable resCode will get the  response from the server. The value should be 200 i.e., HttpURLConnection.HTTP_OK otherwise we have some problem with server.

2)Post Method:

              This method will send the data separately .The code is as shown below.This method needs two strings. One is for URL and the other is for the data which we want to post the data.

 

 

private InputStream postPage(String url, String data) {

                  InputStream is = null;

                  ret = null;

 

                  httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

 

                  httpPost = new HttpPost(url);

                  response = null;

 

                  StringEntity tmp = null;                           

 

                  httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +

                                "i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");

                  httpPost.setHeader("Accept", "text/html,application/xml," +

                                "application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

                  httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

 

                  try {

                                tmp = new StringEntity(data,"UTF-8");

                  } catch (UnsupportedEncodingException e) {

                                System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);

                  }

 

                  httpPost.setEntity(tmp);

 

                  try {

                                response = httpClient.execute(httpPost,localContext);

                  } catch (ClientProtocolException e) {

                                System.out.println("HTTPHelp : ClientProtocolException : "+e);

                  } catch (IOException e) {

                                System.out.println("HTTPHelp : IOException : "+e);

                  }

                ret = response.getStatusLine().toString();

                HttpEntity he = response.getEntity();

                try {

                                                                      InputStream inStream = he.getContent();

                                                                      is = inStream;

                                                        } catch (IllegalStateException e) {

                                                                      // TODO Auto-generated catch block

                                                                      e.printStackTrace();

                                                        } catch (IOException e) {

                                                                      // TODO Auto-generated catch block

                                                                      e.printStackTrace();

                                                        }

                                                        return is;

                  }

 

 

 

 

Downloading Images

              Lets discuss about downloading the images. Here we have some issues with google api. Some times this is throwing decoder->decode returned false.  For this I am also trying. 95% it wont come. Most of the cases it works well and code is as shown below.

 

public Drawable downloadDrawable(String imageUrl) {

    try {

                  Log.d("downloadDrawable", "Starting Connection");

        URL url = new URL(imageUrl);

        URLConnection conn = url.openConnection();

        conn.connect();

        Log.d("downloadDrawable", "Connection Created Successfully");

        InputStream is = conn.getInputStream();

        Log.d("downloadDrawable", "InputStream created Successfully");

        d = Drawable.createFromStream(is, url.toString());

        Log.d("downloadDrawable", "Drawable created Successfully");

                is.close();

                } catch (IOException e) {

                   Log.d("ERROR3", "Ex::"+e);

                }

              return d;

                            }

 

 

Updating UI at Runtime after completion of the downloading Image using AsyncTask

              This is very important one in Android. Normally in the other Technologies we will download the images using a separate Thread. But here if we use the same separate thread then it will create issue at the time of setting the image to the ImageView.

              Android doesn’t support updating the UI in a separate  thread. So, we cannot create a separate thread for updating the UI with images after downloading it. So, Inorder to handle this Android is having a class named AsyncTask. This really helps us a lot. The code is as shown below.

Calling AsyncTask

 

try {

      DownloadFilesTask d = new DownloadFilesTask();

              d.execute(new URL(bookImageUrl));//url of the image

              d.sendObjectImageView(iv_logo);// This is the object to which the image                        //has to set

} catch (Exception e)                                                                                                  e.printStackTrace();

}

 

 

AsyncTask Code

This Class will take care of downloading the image. This is not only for downloading. If we want to know whenever the work completed to it then chose this. The method onPostExecute method will be called by the Asynctask then we can do what ever we want to do after completion of that work. Here we need to set the image to the object that we got from the method sendObjectImageView.

 

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

                  ImageView iv;

                  int id;

                  protected Long doInBackground(URL... urls) {

                      int count = urls.length;

                      long totalSize = 0;

                      downloadDrawable(urls[0].toString());

                       return totalSize;

                  }

                  public void sendObjectImageView(ImageView ivLogo) {

                                          // TODO Auto-generated method stub

                                this.iv = ivLogo;

                                id = -1;

                            }

                            public void sendObjectImageView(ImageView iv,int id) {

                                          // TODO Auto-generated method stub

                                          this.iv = iv;

                                          this.id = id;

                            }

                            protected void onProgressUpdate(Integer... progress) {

                                Log.d("DownloadFilesTask", "onProgressUpdate"+progress[0]);

                  }

                            protected void onPostExecute(Long result) {

                                          Log.d("DownloadFilesTask", "onPostExecute"+result);

                                          if(d!=null && iv!=null)

                                          {

                                                        iv.setImageDrawable(d);

                                                        if(id!=-1)

                                                        booksImagesList[id] = d;

                                          }

                  }

 

XML Parsing

              The description of these things will be displayed soon. until then check out the project.

 

Layout Handling

              The description of these things will be displayed soon. until then check out the project.

 

Customizing Lists

              The description of these things will be displayed soon. until then check out the project.

 

 

You can download the project source from here or You can download the project source from here