Tuesday, 24 April 2012

ProgressBar running in AsyncTask

It's a exercise of a Horizontal ProgressBar which running in a background AsyncTask.

ProgressBar running in AsyncTask

Modify main.xml to have a button to start the progress, and the ProgressBar.
<?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"
 />
<Button
 android:id="@+id/startprogress"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Start"
 />
<ProgressBar
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 style="?android:attr/progressBarStyleHorizontal"
 android:id="@+id/progressbar_Horizontal"
 android:max="100"
 />
</LinearLayout>


Modify the java code.
package com.exercise.AndroidAsyncTaskProgressBar;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AndroidAsyncTaskProgressBar extends Activity {
 
 ProgressBar progressBar;
 Button buttonStartProgress;
 
 public class BackgroundAsyncTask extends
    AsyncTask<Void, Integer, Void> {
  
  int myProgress;

  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   Toast.makeText(AndroidAsyncTaskProgressBar.this,
         "onPostExecute", Toast.LENGTH_LONG).show();
   buttonStartProgress.setClickable(true);
  }

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   Toast.makeText(AndroidAsyncTaskProgressBar.this,
         "onPreExecute", Toast.LENGTH_LONG).show();
   myProgress = 0;
  }

  @Override
  protected Void doInBackground(Void... params) {
   // TODO Auto-generated method stub
   while(myProgress<100){
    myProgress++;
    publishProgress(myProgress);
       SystemClock.sleep(100);
   }
   return null;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
   // TODO Auto-generated method stub
   progressBar.setProgress(values[0]);
  }

 }
 
 
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
  
     buttonStartProgress = (Button)findViewById(R.id.startprogress);
     progressBar = (ProgressBar)findViewById(R.id.progressbar_Horizontal);
     progressBar.setProgress(0);
  
     buttonStartProgress.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    new BackgroundAsyncTask().execute();
    buttonStartProgress.setClickable(false);
   }});
 }
}


Download the files.

Android Menus

An application menu is critical to any mobile application. This is because real estate in a mobile device is limited, so the developer has to make judicious use of menus to provide good application usability. Android provides us with various ways to introduce a menu. This blog post will cover the different types of menus that you can include in your Android application along with code samples and screenshots.
Android Menus can be classified into 3 types:
  • Options Menu
  • Context Menu
  • Submenu

Options Menu:

Options Menu is the menu displayed when MENU key on the device is clicked.
Options menu is divided into 2 types: Icon Menu and Expanded Menu, based on the number of menu options. Options menu can have any number of menu options, but only the first six options are shown directly when the MENU key is clicked and this is called as Icon Menu. In case there are more than six options then first five are show directly and remaining are available when More button is clicked and is called as Expanded Menu.
Note: It is not mandatory to have icon for Icon Menu options. In case icons are associated with menu options,then the icons are displayed for Icon Menu only.
Important Points:
  • onCreateOptionsMenu() method of the Activity is called when the user clicks the Menu Key of the device. So override this method in the activity and populate the Menu object passed as parameter to this method.
  • Multiple add() methods are available. Use the one that accepts itemId as a parameter.
  • onOptionItemSelected() method of the activity is called when a particular Item/Option of the menu is clicked. Override this method in the activity and implement your code to perform the corresponding actions based on the menu option selected.
  • setIcon() is used for assigning icon with the option.
The listing below shows how to add a menu dynamically via code. We are overriding the onCreateOptionsMenu method that is automatically invoked when the User clicks on the MENU key on the device.
?
01
02
03
04
05
06
07
08
09
10
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ADD, 0, "Add").setIcon(R.drawable.ic_menu_add);
menu.add(0, MENU_DELETE, 0, "Delete").setIcon(R.drawable.ic_menu_delete);
menu.add(0, MENU_SAVE, 0, "Save").setIcon(R.drawable.ic_menu_save);
menu.add(0, MENU_DONE, 0, "Done").setIcon(R.drawable.ic_menu_done);
menu.add(0, MENU_HELP, 0, "Help").setIcon(R.drawable.ic_menu_help);
menu.add(0, MENU_SETTINGS, 0, Settings").setIcon(R.drawable.ic_menu_settings);
menu.add(0, MENU_EXIT, 0, "Exit").setIcon(R.drawable.ic_menu_exit);
return true;
}
The listing below shows how to you can react to different menu items that are clicked. We are only displaying the template below. The actual implementation when a specific menu item is clicked depends on your application.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case MENU_ADD:
// Add
<span style="white-space: pre;"> </span>return true;
case MENU_DELETE:
// Delete
<span style="white-space: pre;"> </span>return true;
case MENU_SAVE:
// Save
<span style="white-space: pre;"> </span>return true;
case MENU_DONE:
// Done
<span style="white-space: pre;"> </span>return true;
case MENU_HELP:
// Help
return true;
case MENU_SETTINGS:
// Settings
<span style="white-space: pre;"> </span>return true;
case MENU_EXIT:
// Exit
<span style="white-space: pre;"> </span>return true;
default:
<span style="white-space: pre;"> </span>return false;
}   <span style="white-space: pre;"> </span>
}

Context Menu:

Android provides the facility to open a menu in context with the object clicked. A Long-press on the view will bring up the registered Context menu.
Important Points
  • Using registerForContextMenu() method view is registered for context menu.
  • onCreateContextMenu() method of Activity is called on click (long-press) of registered view. So override this method to populate Context menu options.
  • onContextItemSelected() method of activity is called whenever item/option from context menu is selected. Override this method to perform the appropriate operations depending on the option selected.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public void onCreateContextMenu(ContextMenu menu, View v,
 ContextMenuInfo menuInfo) {
 super.onCreateContextMenu(menu, v, menuInfo);
 menu.add(0, MENU_ADD, 0, "Edit");
 menu.add(0, MENU_DELETE, 0, "Delete");
}
public boolean onContextItemSelected(MenuItem item) {
 switch(item.getItemId()){
 case MENU_ADD:
 // Add
 return true;
 case MENU_DELETE:
 // Delete
 return true;
 default:
 return false;
 }
}
For this example context menu is register to be shown on TextView. Here tv is an instance of a TextView that is present on the layout of this activity.
registerForContextMenu(tv);
Context Menu

Menu Using XML

Menu can also be defined and populated using XML. Following XML structure represents the same menu as of above.
Create optionsmenu.xml under folder res/menu
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<menu
 <item android:id="@+id/MENU_ADD"  android:title="Add"
 android:icon="@drawable/ic_menu_add"/>
 <item android:title="Delete" android:id="@+id/MENU_DELETE" android:icon="@drawable/ic_menu_delete"/>
 <item android:title="Save" android:id="@+id/MENU_SAVE" android:icon="@drawable/ic_menu_save"/>
 <item android:title="Done" android:id="@+id/MENU_DONE" android:icon="@drawable/ic_menu_done"/>
 <item android:title="Help" android:id="@+id/MENU_HELP" android:icon="@drawable/ic_menu_help"/>
 <item android:title="Settings" android:id="@+id/MENU_SETTINGS" android:icon="@drawable/ic_menu_settings"/>
 <item android:title="Exit" android:id="@+id/MENU_EXIT" android:icon="@drawable/ic_menu_exit"/>
</menu>
public boolean onCreateOptionsMenu(Menu menu) {
 MenuInflater inflater = new MenuInflater(this);
 inflater.inflate(R.menu.optionsmenu, menu);
 return true;
}
Advantages of using XML for creating menu are:
  • Easily maintain/modify the menu structure due to a clear separation of the menu creation from the code.
  • The code in onCreateOptionsMenu() method is reduced.

Submenus

Sub menu can be added to any type of menu.
Below code shows adding Submenu  for Options menu:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public boolean onCreateOptionsMenu(Menu menu) {
  SubMenu sendMenu = menu.addSubMenu("Send");
sendMenu.add(0,MENU_SMS,0,"SMS");
  sendMenu.add(0,MENU_EMAIL,0,"EMAIL");
 return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
 case MENU_SMS:
 // SMS
 return true;
 case MENU_EMAIL:
 // Email
 return true;
 default:
 return false;
 }
}
Submenu
Submenu
?
01
02
03
04
05
06
07
08
09
10
<menu
<item android:id="@+id/MENU_SEND"
 android:title="Send">
 <menu>
 <item android:id="@+id/MENU_SMS" android:title="SMS"></item>
 <item android:id="@+id/MENU_EMAIL" android:title="EMAIL"></item>
 </menu>
</item>
</menu>
As covered in this blog post, Android provides several ways to include menus in your application. You should pick and choose them depending on your needs. Context Menus are typically expected now by users and should be used carefully in order to provide good application usability

Android Async Task

This blog post introduces one of the important mechanism of Async Task for Android with sample code.
Android implements single thread model and whenever an Android application is launched, a thread is created. Now assume you have long running operations like a network call on a button click in your application. On button click a request would be made to the server and response will be awaited. Now due to the single thread model of Android, till the time response is awaited your UI screen hangs or in other words, it is non-responsive.
We can overcome this by creating a new Thread and implement the run method to perform the time consuming operation, so that the UI remains responsive.
As shown below a new Thread is created in onClick method
?
1
2
3
4
5
6
7
8
public void onClick(View v) {
    Thread t = new Thread(){
    public void run(){
  // Long running operation
    }
   };
   t.start();
}
But since Android follows single thread model and Android UI toolkit is not thread safe, so if there is a need to make some change to the UI based on the result of the operation performed, then this approach may lead some issues.
There are various approaches via which control can be given back to UI thread (Main thread running the application). Handler approach is one among the various approaches.

Handler

Let us look at the code snippet below to understand Handler approach.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
public void onClick(View v) {
   Thread t = new Thread(){
  public void run(){
       // Long time comsuming operation
    Message myMessage=new Message();
    Bundle resBundle = new Bundle();
    resBundle.putString("status", "SUCCESS");
    myMessage.obj=resBundle;
    handler.sendMessage(myMessage);
  }
  };
  t.start();
}
As seen we have modified the original run method and added code to create Message object, which is then passed as parameter to sendMessage method of Handler. Now let us look at the Handler. Note that the code below is present in the main activity code.
?
1
2
3
4
5
6
private Handler handler = new Handler() {
@Override
  public void handleMessage(Message msg) {
    // Code to process the response and update UI.
  }
};
After the execution of long running operation, the result is set in Message and passed to sendMessage of handler. Handle will extract the response from Message and will process and accordingly update the UI. Since Handler is part of main activity, UI thread will be responsible for updating the UI.
Handler approach works fine, but with increasing number of long operations, Thread needs to be created,  run method needs to be implemented and Handler needs to be created. This can be a bit cumbersome. The Android framework has identified this pattern and has nicely enveloped it into what is called an Android Async Task. Let us look at how it can help simplify things.

Async Task

Android Async Task takes cares of thread management and is the recommended mechanism for performing long running operations.
Let us look at a sample class LongOperation, which extends the AsyncTask below:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private class LongOperation extends AsyncTask<String, Void, String> {
 
  @Override
  protected String doInBackground(String... params) {
    // perform long running operation operation
    return null;
  }
 
  /* (non-Javadoc)
   * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
   */
  @Override
  protected void onPostExecute(String result) {
    // execution of result of Long time consuming operation
  }
 
  /* (non-Javadoc)
   * @see android.os.AsyncTask#onPreExecute()
   */
  @Override
  protected void onPreExecute() {
  // Things to be done before execution of long running operation. For example showing ProgessDialog
  }
 
  /* (non-Javadoc)
   * @see android.os.AsyncTask#onProgressUpdate(Progress[])
   */
  @Override
  protected void onProgressUpdate(Void... values) {
      // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
   }
}
Modify the onClick method as shown below:
?
1
2
3
public void onClick(View v) {
new LongOperation().execute("");
}
As seen class LongOperation extends AsyncTask and implements 4 methods:
  1. doInBackground: Code performing long running operation goes in this method.  When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
  2. onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  3. onPreExecute: This method is called before doInBackground method is called.
  4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.
Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.

Points to remember:

  1. Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.
  2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.
  3. Task can be executed only once.
Hope this blog helped you understand Android async task and why it is important in Android application development.

Saturday, 21 April 2012

Read the php service in android using json object

Note: the rules should followed as given bellow



Setting must be in manifesto.xml

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


if the version android 4.0

StrictMode  need to be added..... before calling the value of service



StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
   


*******************************************************************************

this is the code for reading through the url



package com.mmad.restaurant;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class RestService {
     JSONArray jArray;
     String result = null;
     InputStream is = null;
     StringBuilder sb = null;
       
    public String GetValue(int f,int t)
    {
     try {
               HttpClient httpclient = new DefaultHttpClient();
               // HttpPost httppost = new
               // HttpPost("http://192.168.40.23:9999/ppp.php?id=1");
               // HttpPost httppost = new
               // HttpPost("http://192.168.40.23:7777/domain_master_Mujusam.php");
               HttpPost httppost = new HttpPost("http://192.168.40.24:5050/web-services/Rest_Service/order_details.php?f="+f+"&t="+t);
               HttpResponse response = httpclient.execute(httppost);
               HttpEntity entity = response.getEntity();
               is = entity.getContent();

              } catch (Exception e) {
               Log.e("log_tag", "Error in http connection" + e.toString());
              }
              // convert response to string
              try {
               BufferedReader reader = new BufferedReader(new InputStreamReader(
                 is, "iso-8859-1"), 8);
               sb = new StringBuilder();
               sb.append(reader.readLine() + "\n");

               String line = "0";
               while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
               }
               is.close();
               result = sb.toString();
              } catch (Exception e) {
               Log.e("log_tag", "Error converting result " + e.toString());
              }
              return result;
       
    }
   
   
   
}


this is code for getting the json object



JSONArray jArray = new JSONArray(getTab);
                   for(int j=0;j<jArray.length();j++){
                      
                            JSONObject json_data = jArray.getJSONObject(j);
                           
                            String orderItem=json_data.getString("oi_foddname");
                            String orderQty=json_data.getString("oi_foodqty");
}








Thursday, 12 April 2012

Android - How To Set Up an API Key for Google Maps

It took me some time to figure out all the steps to get my Android
apps set up to use Google Maps.  Hopefully this will spare you some
time.  First I'll explain how the process goes when you don't have any problems.  If you're having problems, you can click here to find out about the troubles I ran into when I upgraded from SDK 1.1 to 1.5.

Open a command prompt and navigate to a file called debug.keystore. The location of this file depends on what OS you are using. I use Windows XP and my debug.keystore file is located at C:\Documents and Settings\User\.android.
As a side note, before the Android 1.5 SDK came out, my debug.keystore file was located in a different location (C:\Documents and Settings\HP_Administrator\Local Settings\Application Data\Android). When I later updated to 1.5 I ran into all sorts of problems getting the maps to work.
if you use a Mac or Linux OS, I've discovered that you'll find the debug.keystore file at: ~/.android/.

The debug.keystore contains a digitial certificate that android uses to launch applications on the emulator. The certificate is called 'androiddebugkey'.  We'll need to get some an MD5 hash for this certificate in order register for our map api key.

Hopefully you've located the debug.keystore file, so now we'll use Java's keytool utility to get the MD5.

I use XP so I navigated to the proper directory by opening a command prompt and typing:
cd C:\Documents and Settings\HP_Administrator\.android

Once you've navigated to the proper directory for your os, type this in...
keytool -list -alias androiddebugkey -storepass android -keypass android -key
store debug.keystore


Once you hit the enter key, you'll see something like this (the actual MD5 that we're interested in is the last line):
androiddebugkey, Mar 10, 2009, PrivateKeyEntry,
Certificate fingerprint (MD5): D1:16:4A:BD:73:73:A4:56:9D:CD:9A:44:A2:6C:11:AC


Now open your browser and go to the following url...
http://code.google.com/intl/ja/android/maps-api-signup.html

Accept the agreement and paste the md5 that the key tool returned to you, in my case it was something like...
D1:16:4A:BD:73:73:A4:56:9D:CD:9A:44:A2:6C:11:AC

Then press "Generate API Key" and you'll be redirected to a page that has your api key.

Now
that you have the api key, you can use it in the main.xml layout file
of your MapTest application. Here's what mine looks like:

<?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.google.android.maps.MapView
        android:id="@+id/mapview1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0q7NUYm4bgzeXlqXtKYVPJDRWUJmt8Cu0gvbWMx"
        />
</LinearLayout>


You'll also have to add some entries to your manifest file, here's what mine looks like...

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.remwebdevelopment.maptest"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- this was the kicker - had to import the library com.google.android.maps!!! -->
        <uses-library android:name="com.google.android.maps" />
        <activity android:name=".MapTest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <!--make sure you add the following permissions to your app!!!-->
    <uses-permission
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:name="android.permission.INTERNET">
    </uses-permission>
    <uses-permission
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:name="android.permission.ACCESS_FINE_LOCATION">
    </uses-permission>
</manifest>


Here's what my MapActivity looks like(note that it extends MapActivity, not Activiy)...

package com.remwebdevelopment.maptest;

import com.google.android.maps.MapActivity;


import android.os.Bundle;

public class MapTest extends MapActivity {

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

        //you could get a reference to the map view from the main.xml
        //layout like this...
        //mMapView = (MapView)findViewById(R.id.mapview1);
    }

    //you must provide an implementation for isRouteDisplayed()
    //when you extend MapActivity...
    @Override
    protected boolean isRouteDisplayed() {
    return false;
    }
}


You should see a map of the world when you run it.
Hopefully this will get you up and running.  I have other code samples
that might be helpful, I'll be posting them soon.