Sunday, 23 March 2014

Adding custom layou in alertdialog

Firstly, create the layout xml. I called mine customalertlayout.xml. It is a simple LinearLayout container with 2 EditTexts in it - with ids username and password. They are also stylized to look and behave like username and password fields in a log in window.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <EditText
        android:id="@+id/username"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="4dp"
        android:hint="Username" />
    <EditText
        android:id="@+id/password"
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:fontFamily="sans-serif"
        android:hint="Password"/>
</LinearLayout>

 Now go to MainActivity.java class. First we declare a View:

private View alertView;

 Then in onCreate() function we can use a LayoutInflater to get a View out of the xml layout. Apply this View value to alertView:

LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
alertView = inflater.inflate(R.layout.custom_alert_layout, null);
 You can apply this view to the AlertDialog using the builder's setView() method:
builder.setView(alertView);

 You can still use AlertDialog's elements made with the builder though! I'll add a title, an icon and a button to this layout using the builder.

In the onClick() event handler function of the button, I extract the text values of the two EditText objects and display them in a Toast:

@Override
public void onClick(DialogInterface dialog, int which) {
EditText t_user = (EditText)alertView.findViewById(R.id.username);
EditText t_pass = (EditText)alertView.findViewById(R.id.password);
String username = t_user.getText().toString();
String password = t_pass.getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), "User: " + username + ", Pass: " + password, Toast.LENGTH_SHORT);
toast.show();
}


 Full code:
package com.kircode.codeforfood_test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity{
private AlertDialog myDialog;
private View alertView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.testButton);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
alertView = inflater.inflate(R.layout.custom_alert_layout, null);
builder.setView(alertView);
builder.setTitle("Log in");
builder.setIcon(R.drawable.snowflake);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText t_user = (EditText)alertView.findViewById(R.id.username);
EditText t_pass = (EditText)alertView.findViewById(R.id.password);
String username = t_user.getText().toString();
String password = t_pass.getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), "User: " + username + ", Pass: " + password, Toast.LENGTH_SHORT);
toast.show();
}
});
builder.setCancelable(false);
myDialog = builder.create();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myDialog.show();
}
});
}
@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;
}
}

Saturday, 4 January 2014

OrmLite Database in Android

Hi Guys!,

Today we are learning about the OrmLite database in android.
In this post we will see the basics of OrmLite and its features and a little bit about its coding

In Android there are also several ways to do it, however the most advanced (in terms of flexibility and convenience) way to store structured data in Android is to use an SQLite relational database.

Probably everyone knows this, but still:
SQLite is basically a special file format and a set of APIs implemented in a library that ships with Android OS.  Like most relational databases management systems SQLite API allows to manipulate data with SQL queries.

The programming model in which one has to manipulate data with plain SQL queries inside the application business logic is tedious, inconvenient and outdated.  It should be forbidden to write spaghetti like code filled with SQL-queries in XXI century.  Even if you are completely forced to write SQL queries in code and if you are a good programmer - you will find yourself writing some sort of framework that encapsulates common query routines and allows you to easier do similar operations on different data entities.  What is more tedious, time-consuming and inconvenient - is dealing with SQLite API


The convenient programming model for me is:
- to be able to create/update objects in code and persist them by calling a method on a certain DB-manager object,
- to be able to fetch a set of objects with a certain predicate defined for one/several of the object's fields

This programming model is generally achieved with the help of any persistance/ORM framework such as Hibernate, however the latter is pretty heavy to be used in Android.  There is an excellent alternative called ORMLite.  As the name implies - it is a lightweight ORM framework, and it turns out to be well suited for Android.

OrmLite:
                   Object Relational Mapping Lite (ORM Lite) provides some lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages. It supports a number of SQL databases using JDBC and also supports Sqlite with native calls to Android OS database APIs

 Features:

  • Setup your classes by simply adding Java annotations.
  • Powerful abstract Database Access Object (DAO) classes to manage the object in the database
  • Flexible QueryBuilder to easily construct simple and complex queries.
  • Supports MySQL, Postgres, Microsoft SQL Server, H2, Derby, HSQLDB, and Sqlite and can be extended to additional databases relatively easily.
  • Provisional support for DB2, Oracle, ODBC, and Netezza. Contact the author if your database type is not supported.
  • Handles "compiled" SQL statements for repetitive query tasks.
  • Supports "foreign" objects with the class field being the object but an id stored in the database table.
  • Basic support for database transactions.
  • Auto generates SQL to create and drop database tables.


Now we will jump a little bit about coding part,

Use Annotations to Mark Classes to be Persisted

To use the package you add the @DatabaseTable annotation to the top of each class and a @DatabaseField annotation to each of the fields in the class that are to be persisted to the database. For example:

@DatabaseTable(tableName = "accounts")
public class Account {
    @DatabaseField(id = true)
    private String name;
   
    @DatabaseField(canBeNull = false)
    private String password;
    ...
    Account() {
    // all persisted classes must define a no-arg constructor with at least package visibility
    }
    ...  

Sample Code Example

The ORMLite Android code includes base activity, service, and tab classes to help create and manage your database connections and DAOs. The following is a quick code example to give you a taste on how to use the package.

// you get the SQLiteOpenHelper from your Android Activity
ConnectionSource connectionSource =
     new AndroidConnectionSource(sqliteOpenHelper);

// instantiate the DAO to handle Account with String id
Dao<Account,String> accountDao =
     BaseDaoImpl.createDao(connectionSource, Account.class);

// if you need to create the 'accounts' table make this call
TableUtils.createTable(connectionSource, Account.class);

// create an instance of Account
String name = "Jim Smith";
Account account = new Account(name, "_secret");

// persist the account object to the database
// it should return 1 for the 1 row inserted
if (accountDao.create(account) != 1) {
     throw new Exception("Failure adding account");
}

// retrieve the account
Account account2 = accountDao.queryForId(name);
// show its password
System.out.println("Account: " + account2.getPassword());

// close the connection source
connectionSource.close();








Friday, 3 January 2014

Creating custom SD card in Android emulator

The android sdk comes with a tool sdcard to create SD card file to be used with the Emulator.  In order to create a sdcard we need to go to the directory where android sdk tools are installed from command prompt (generally it is C:\android\android-sdk-windows) it can be done in two ways

Open a command prompt to open it press ctrl+r then type cmd in the new dialog box & click enter and manually traverse to that directory.
                                                                                           OR

Go to directory where android sdk tools is installed and select tools folder, directly open command prompt at  that location by pressing shift button and holding it and then right clicking & selecting option open command window here.



                                               Opening cmd directly at desired location

                                                  This is how your cmd should look like



Type the following command

mksdcard100M d:/sdcard

where

mksdcard :- is the command to create sd card.

100M  :- is the size of sdcard(which can be changed according to our requirement)

D:\   :- is the location where sdcard is created

sdcard:- is the name of sdcard which can be modified as per our wish

it may take few second depending upon size of sdcard, after this you will find a a image file with name sdcard in the location which you have created (D: in mycase).



ASSIGNING THE SDCARD TO EMULATOR

Now in eclipse in top menu Run>Run configuration

Select target tab
At the bottom of the window there is a field Additional Emulator command line options

Type -sdcard followed by path of folder in which sdcard was created (don’t forget to write the name of your sdcard at the end of the path as in my case complete command is  –sdcard D:\sdcard ).


                                                              Adding SD card to emulator


Adding SD card to emulator
Now hit the apply button at the bottom and close the dialog box.
Close the emulator if it was open and run it again .
If we run our app again nothing interesting is going to happen with your app :-) .
Now we need to push some data into our sdcard before we can use it

PUSHING DATA INTO THE  SDCARD


In the eclipse from the main menu select window>show view>file Explorer can also open File Explorer by choosing DDMS view which contains File explorer

                                                                  Selecting DDMS

Inside your file explorer select “push a file onto the device”
But beware u cannot push data in any file because many of file are read only there.
So to push file goto mnt/sdcard and push your data here.

To push data click on “push a file onto the device” and then drag and drop the file into the selected folder



                                                           Selecting push files to sdcard



Thursday, 2 January 2014

Save and Restore Instance State

The methods onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState) are the good place to Save and Restore Instance State.

onSaveInstanceState (Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause().

onRestoreInstanceState (Bundle savedInstanceState)

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

This method is called between onStart() and onPostCreate(Bundle).



java code:


package com.example.androidsavestate;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
 TextView textviewSavedState;
 EditText edittextEditState;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        textviewSavedState = (TextView)findViewById(R.id.savedstate);
     edittextEditState = (EditText)findViewById(R.id.editstate);
    }
 
 @Override
 protected void onRestoreInstanceState(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onRestoreInstanceState(savedInstanceState);
   
  String stateSaved = savedInstanceState.getString("saved_state");
   
  if(stateSaved == null){
   Toast.makeText(MainActivity.this,
     "onRestoreInstanceState:\n" +
     "NO state saved!",
     Toast.LENGTH_LONG).show();
  }else{
   Toast.makeText(MainActivity.this,
     "onRestoreInstanceState:\n" +
     "saved state = " + stateSaved,
     Toast.LENGTH_LONG).show();
   textviewSavedState.setText(stateSaved);
   edittextEditState.setText(stateSaved);
  }
 
 }
 
 @Override
 protected void onSaveInstanceState(Bundle outState) {
  // TODO Auto-generated method stub
  super.onSaveInstanceState(outState);
   
  String stateToSave = edittextEditState.getText().toString();
  outState.putString("saved_state", stateToSave);
   
  Toast.makeText(MainActivity.this,
    "onSaveInstanceState:\n" +
    "saved_state = " + stateToSave,
    Toast.LENGTH_LONG).show();
 }
 
}






Insert And Retrieve Image into DB

Hi Guys,

In this tutorial we are sharing the code to insert the image into db and retrieve the image from db. I hope this article might be helpful to all learning developer.

SQLite is really a quick and compact android database technology which incorporates SQL syntax to create queries and also handle data.

Android SDK by itself provides the SQLite support which without doubt making the setup as well as utilization process within our applications with no trouble.

Whenever we make use of an Android SQLite Database all of us undoubtedly require the help of SQLiteOpenHelper to handle our data.SQLiteOpenHelper is surely an superb destination to place some initial values right into the android sqlite database when it is built.

For storing the image we are using the blob type. Blob is a Java interface representing the SQL BLOB type.
An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.
The java.sql.Blob interface provides methods for setting and retrieving data in the Blob, for querying Blob data length, and for searching for data within the Blob. More details about Blob Here

But i think in big level storing the image in database is not valuable because database sqlite have limited space so store the image path is valuable.

main_activity.xml

<relativelayout android:layout_height="match_parent" android:layout_width="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".MainActivity" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
 
    <textview android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/hello_world">
 
    <imageview android:id="@+id/imageView_image" android:layout_below="@+id/textView1" android:layout_height="wrap_content" android:layout_margintop="64dp" android:layout_torightof="@+id/textView1" android:layout_width="wrap_content">
 
    <button android:id="@+id/button_insert" android:layout_below="@+id/imageView_image" android:layout_height="wrap_content" android:layout_margintop="45dp" android:layout_torightof="@+id/textView1" android:layout_width="wrap_content" android:text="Insert In DB">
 
    </button><button android:id="@+id/button_retrieve" android:layout_alignleft="@+id/button_insert" android:layout_below="@+id/button_insert" android:layout_height="wrap_content" android:layout_margintop="56dp" android:layout_width="wrap_content" android:text="Retrieve from DB">
 
</button></imageview></textview></relativelayout>


MainActivity.java

package com.sunil.insertimageindb;
 
import java.io.ByteArrayOutputStream;
 
import com.sunil.insertimageindb.R;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
 
public class MainActivity extends Activity implements OnClickListener{
 
    private ImageView imageview=null;
    private Button btninsert=null;
    private Button btnretrive=null;
    private MyDataBase mdb=null;
    private SQLiteDatabase db=null;
    private Cursor c=null;
    private byte[] img=null;
    private static final String DATABASE_NAME = "ImageDb.db";
    public static final int DATABASE_VERSION = 1;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        btninsert=(Button)findViewById(R.id.button_insert);
        btnretrive= (Button)findViewById(R.id.button_retrieve);
        imageview= (ImageView)findViewById(R.id.imageView_image);
        imageview.setImageResource(0);
        btninsert.setOnClickListener(this);
        btnretrive.setOnClickListener(this);
        mdb=new MyDataBase(getApplicationContext(), DATABASE_NAME,null, DATABASE_VERSION);
        
 
        Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 100, bos);
        img=bos.toByteArray();
        db=mdb.getWritableDatabase();
    }
    @Override
    public void onClick(View arg0) {
         
        if(btninsert==arg0)
        {
            ContentValues cv=new ContentValues();
            cv.put("image", img);
            db.insert("tableimage", null, cv);
            Toast.makeText(this, "inserted successfully", Toast.LENGTH_SHORT).show();
        }
        else if(btnretrive==arg0)
        {
                String[] col={"image"};
                c=db.query("tableimage", col, null, null, null, null, null);
                
                if(c!=null){
                    c.moveToFirst();
                    do{
                        img=c.getBlob(c.getColumnIndex("image"));
                       }while(c.moveToNext());
                }
                Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);
              
                 imageview.setImageBitmap(b1);
                 Toast.makeText(this, "Retrive successfully", Toast.LENGTH_SHORT).show();
            }
        }
 
}


MyDatabase.java

package com.sunil.insertimageindb;
 
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
 
public class MyDataBase extends SQLiteOpenHelper{
     
    public MyDataBase(Context context, String dbname, CursorFactory factory, int dbversion) {
        super(context, dbname, factory, dbversion);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table tableimage(image blob);");
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        
    }
 
}

Store the image in db looks like that

Integration of Yahoo Weather Api in Android

Integration weather api in android has so many choices. But I consider yahoo as the cheap and best api solution. Some other apis are provided by metwit, wunderground,worldweather, etc.

Yahoo provides a detailed documentation on the usage of their api. Its simple to integrate, however little bit of knowledge on parsing a xml response is needed.

Let me give a sample of parsing yahoo weather data to display current weather and five day forecast in android application.

Read the details given this link  http://developer.yahoo.com/weather/ to follow easily. And note down the WOEID for your city.To find your WOEID, browse or search for your city from the Weather home page.


Let’s create UI. My sample layout.xml looks like this..

<?xml version=”1.0″ encoding=”UTF-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#ffffff”
tools:context=”.Weather” >

<TextView
android:id=”@+id/weather_title”
android:layout_width=”fill_parent”
android:layout_height=”40dp”
android:background=”@layout/searchgradient”
android:gravity=”center_vertical|center_horizontal”
android:text=”Weather Report”
android:textColor=”#ffffff”
android:textSize=”22sp”
android:textStyle=”bold” />

<ImageView
android:id=”@+id/weather_border”
android:layout_width=”fill_parent”
android:layout_height=”2dp”
android:layout_below=”@+id/weather_title”
android:layout_marginBottom=”10dp”
android:background=”#CCCCCC” />

<ScrollView
android:id=”@+id/scrollView1″
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:layout_above=”@+id/footer_border”
android:layout_below=”@+id/weather_border” >

<RelativeLayout
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” >

<TextView
android:id=”@+id/dateText”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentRight=”true”
android:layout_alignTop=”@+id/icon”
android:layout_toRightOf=”@+id/icon”
android:textColor=”#333333″
android:textSize=”16sp” />

<TextView
android:id=”@+id/tempText”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_below=”@+id/dateText”
android:layout_toRightOf=”@+id/icon”
android:textColor=”#333333″
android:textSize=”16sp” />

<TextView
android:id=”@+id/conditionText”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentRight=”true”
android:layout_below=”@+id/tempText”
android:layout_toRightOf=”@+id/icon”
android:textColor=”#333333″
android:textSize=”16sp” />

<TextView
android:id=”@+id/humidityText”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentRight=”true”
android:layout_below=”@+id/conditionText”
android:layout_toRightOf=”@+id/icon”
android:textColor=”#333333″
android:textSize=”16sp” />

<TextView
android:id=”@+id/windText”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentRight=”true”
android:layout_below=”@+id/humidityText”
android:layout_marginBottom=”10dp”
android:layout_toRightOf=”@+id/icon”
android:paddingBottom=”10dp”
android:textColor=”#333333″
android:textSize=”16sp” />

<ImageView
android:id=”@+id/border2″
android:layout_width=”fill_parent”
android:layout_height=”2dp”
android:layout_below=”@+id/windText”
android:background=”#ff6600″ />

<TextView
android:id=”@+id/forecast_title”
android:layout_width=”fill_parent”
android:layout_height=”40dp”
android:layout_below=”@+id/border2″
android:background=”@layout/listgradient”
android:gravity=”center_vertical|center_horizontal”
android:text=”Forecast”
android:textColor=”#333333″
android:textSize=”18sp”
android:textStyle=”bold” />

<ImageView
android:id=”@+id/forecastBorder”
android:layout_width=”fill_parent”
android:layout_height=”1dp”
android:layout_below=”@+id/forecast_title”
android:background=”#CCCCCC” />

<TextView
android:id=”@+id/day1″
android:layout_width=”wrap_content”
android:layout_height=”40dp”
android:layout_alignParentLeft=”true”
android:layout_alignParentRight=”true”
android:layout_below=”@+id/forecastBorder”
android:background=”@layout/listgradient”
android:gravity=”left|center_vertical”
android:paddingLeft=”10dp”
android:textAlignment=”gravity”
android:textColor=”#333333″
android:textSize=”16sp” />

<TextView
android:id=”@+id/day2″
android:layout_width=”wrap_content”
android:layout_height=”40dp”
android:layout_alignParentLeft=”true”
android:layout_alignParentRight=”true”
android:layout_below=”@+id/day1″
android:background=”@layout/listgradient”
android:gravity=”left|center_vertical”
android:paddingLeft=”10dp”
android:textAlignment=”gravity”
android:textColor=”#333333″
android:textSize=”16sp” />

<TextView
android:id=”@+id/day3″
android:layout_width=”wrap_content”
android:layout_height=”40dp”
android:layout_alignParentLeft=”true”
android:layout_alignParentRight=”true”
android:layout_below=”@+id/day2″
android:background=”@layout/listgradient”
android:gravity=”left|center_vertical”
android:paddingLeft=”10dp”
android:textAlignment=”gravity”
android:textColor=”#333333″
android:textSize=”16sp” />

<TextView
android:id=”@+id/day4″
android:layout_width=”wrap_content”
android:layout_height=”40dp”
android:layout_alignParentLeft=”true”
android:layout_alignParentRight=”true”
android:layout_below=”@+id/day3″
android:background=”@layout/listgradient”
android:gravity=”left|center_vertical”
android:paddingLeft=”10dp”
android:textAlignment=”gravity”
android:textColor=”#333333″
android:textSize=”16sp” />

<ImageView
android:id=”@+id/icon”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
android:padding=”10dp” />
</RelativeLayout>
</ScrollView>

<ImageView

android:id=”@+id/footer_border”

android:layout_width=”fill_parent”

android:layout_height=”2dp”

android:layout_above=”@+id/footer”

android:background=”#CCCCCC” />

 

<ImageView

android:id=”@+id/footer”

android:layout_width=”fill_parent”

android:layout_height=”50dp”

android:layout_alignParentBottom=”true”

android:background=”#E4E4E4″ />

 

<ImageButton

android:id=”@+id/reportBtn”

android:layout_width=”160dp”

android:layout_height=”wrap_content”

android:layout_alignParentBottom=”true”

android:layout_alignParentRight=”true”

android:layout_alignTop=”@+id/footer”

android:background=”@layout/footer_button_gradient”

android:paddingBottom=”5dp”

android:paddingLeft=”10dp”

android:paddingRight=”10dp”

android:paddingTop=”5dp”

android:src=”@drawable/iconreport” />

 

<ImageButton

android:id=”@+id/backBtn”

android:layout_width=”160dp”

android:layout_height=”wrap_content”

android:layout_alignParentBottom=”true”

android:layout_alignParentLeft=”true”

android:layout_alignTop=”@+id/footer”

android:background=”@layout/footer_button_gradient”

android:paddingBottom=”5dp”

android:paddingLeft=”10dp”

android:paddingRight=”10dp”

android:paddingTop=”5dp”

android:src=”@drawable/iconback” />

 

</RelativeLayout>

And my Activity file looks like this.

package com.xxxx.xxxxxx;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Weather extends Activity {

String temperature, date, condition, humidity, wind, link;
Bitmap icon = null;
TextView title, tempText, dateText, conditionText, windText, humidityText,day1,day2, day3, day4;
ImageView image;
ArrayList<String> weather = new ArrayList<String>();
ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
image = (ImageView)findViewById(R.id.icon);
title = (TextView) findViewById(R.id.weather_title);
dateText = (TextView) findViewById(R.id.dateText);
tempText = (TextView) findViewById(R.id.tempText);
conditionText = (TextView) findViewById(R.id.conditionText);
humidityText = (TextView) findViewById(R.id.humidityText);
windText = (TextView) findViewById(R.id.windText);
day1 = (TextView)findViewById(R.id.day1);
day2 = (TextView)findViewById(R.id.day2);
day3 = (TextView)findViewById(R.id.day3);
day4 = (TextView)findViewById(R.id.day4);
weatherLink = (TextView)findViewById(R.id.weatherLink);
Typeface tf = Typeface.createFromAsset(getAssets(),
“Fonts/Roboto-Condensed.ttf”);
title.setText(“Madurai Weather Report”);
tempText.setTypeface(tf);
conditionText.setTypeface(tf);
dateText.setTypeface(tf);
humidityText.setTypeface(tf);
windText.setTypeface(tf);
title.setTypeface(tf);
day1.setTypeface(tf);
day2.setTypeface(tf);
day3.setTypeface(tf);
day4.setTypeface(tf);
ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
ImageButton report = (ImageButton) findViewById(R.id.reportBtn);

new retrieve_weatherTask().execute();

}

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

protected class retrieve_weatherTask extends AsyncTask<Void, String, String> {

protected void onPreExecute(){
dialog = new ProgressDialog(Weather.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage(“Loading…”);
dialog.setCancelable(false);
dialog.show();
}

@Override
protected String doInBackground(Void… arg0) {
// TODO Auto-generated method stub
String qResult = “”;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(“http://weather.yahooapis.com/forecastrss?w=2295425&u=c&#8221;);

try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();

if (entity != null) {
InputStream inputStream = entity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + “\n”);
}
qResult = stringBuilder.toString();
}

} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(Weather.this, e.toString(), Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(Weather.this, e.toString(), Toast.LENGTH_LONG)
.show();
}

Document dest = null;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser
.parse(new ByteArrayInputStream(qResult.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(Weather.this, e1.toString(), Toast.LENGTH_LONG)
.show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(Weather.this, e.toString(), Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(Weather.this, e.toString(), Toast.LENGTH_LONG)
.show();
}

Node temperatureNode = dest.getElementsByTagName(
“yweather:condition”).item(0);
temperature = temperatureNode.getAttributes()
.getNamedItem(“temp”).getNodeValue().toString();
Node tempUnitNode = dest.getElementsByTagName(“yweather:units”).item(0);
temperature = temperature + “°” +tempUnitNode.getAttributes().getNamedItem(“temperature”).getNodeValue().toString();

Node dateNode = dest.getElementsByTagName(“yweather:forecast”)
.item(0);
date = dateNode.getAttributes().getNamedItem(“date”)
.getNodeValue().toString();

Node conditionNode = dest
.getElementsByTagName(“yweather:condition”).item(0);
condition = conditionNode.getAttributes()
.getNamedItem(“text”).getNodeValue().toString();

Node humidityNode = dest
.getElementsByTagName(“yweather:atmosphere”).item(0);
humidity = humidityNode.getAttributes()
.getNamedItem(“humidity”).getNodeValue().toString();
humidity = humidity + “%”;

Node windNode = dest.getElementsByTagName(“yweather:wind”).item(0);
wind = windNode.getAttributes().getNamedItem(“speed”).getNodeValue().toString();
Node windUnitNode = dest.getElementsByTagName(“yweather:units”).item(0);
wind = wind + ” “+windUnitNode.getAttributes().getNamedItem(“speed”)
.getNodeValue().toString();

String desc = dest.getElementsByTagName(“item”).item(0)
.getChildNodes().item(13).getTextContent().toString();
StringTokenizer str = new StringTokenizer(desc, “<=>”);
System.out.println(“Tokens: ” + str.nextToken(“=>”));
String src = str.nextToken();
System.out.println(“src: “+ src);
String url1 = src.substring(1, src.length() – 2);
Pattern TAG_REGEX = Pattern.compile(“(.+?)<br />”);
Matcher matcher = TAG_REGEX.matcher(desc);
while (matcher.find()) {
weather.add(matcher.group(1));
}

Pattern links = Pattern.compile(“(.+?)<BR/>”);
matcher = links.matcher(desc);
while(matcher.find()){
System.out.println(“Match Links: “+ (matcher.group(1)));
link = matcher.group(1);
}

/* String test = (Html.fromHtml(desc)).toString();
System.out.println(“test: “+ test);
StringTokenizer tkn = new StringTokenizer(test);
for(int i=0; i < tkn.countTokens(); i++){
System.out.println(“Remaining: “+tkn.nextToken());
}*/

InputStream in = null;
try {
// in = OpenHttpConnection(url1);
int response = -1;
URL url = new URL(url1);
URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection))
throw new IOException(“Not an HTTP connection”);
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod(“GET”);
httpConn.connect();

response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
System.out.println(“*********************”);
in = httpConn.getInputStream();
}
icon = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return qResult;

}

protected void onPostExecute(String result) {
System.out.println(“POST EXECUTE”);
if(dialog.isShowing())
dialog.dismiss();
tempText.setText(“Temperature: “+temperature);
conditionText.setText(“Condition: “+condition);
dateText.setText(“Date: “+date);
humidityText.setText(“Humidity: “+humidity);
windText.setText(“Wind: “+wind);
image.setImageBitmap(icon);
day1.setText(weather.get(3));
day2.setText(weather.get(4));
day3.setText(weather.get(5));
day4.setText(weather.get(6));
weatherLink.setText(Html.fromHtml(link));

}
}

}

Try this code and you can showcase the weather forecast of your city now! Let me know your comments.


Wednesday, 1 January 2014

Android include and merge layout example

How to use the <include> and <merge> tags in Android to create efficient and reusable layouts


The include tag as the name suggests is more like the one in JSP, HTML or other languages. It takes another layout and includes that in the current layout.The <merge /> tag was created for the purpose of optimizing Android layouts by reducing the number of levels in view trees. Use the merge tag instead of linearLayout as a root tag around your layout elements if you are going to include that in another layout.

In this example we are going to use both include and merge tags to generate our complete layout. We have created the header and the footer layouts with merge tags as they will be used throughout the application and can be included in all pages. In addition to that we have created another layout that will be merged programmatically in the activity by inflating the layout. 

Application Layout source - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="vertical">
 <include android:layout_width="wrap_content"
  android:layout_height="wrap_content" layout="@layout/header" />
 
 <TextView android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:text="@string/hello"
  android:textSize="20sp" />
 
 
 <LinearLayout
     android:id="@+id/linearLayout1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginTop="10dp"
     android:layout_weight="1"
     android:orientation="vertical" >
 
 </LinearLayout>
 
 
 <include android:layout_width="wrap_content"
  android:layout_height="wrap_content" layout="@layout/footer"
  android:layout_gravity="right" />
 
</LinearLayout>

Application Header source - header.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
 
 <TextView
     android:id="@+id/textView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:paddingBottom="10dp"
     android:text="My Application Header"
     android:layout_gravity="center_horizontal"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
</merge>

Application Footer source - footer.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
 
 
 <TextView
     android:id="@+id/textView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="right"
     android:text="My Application Footer"
     android:textAppearance="?android:attr/textAppearanceSmall" />
 
</merge>

Application Item Detail source - item.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Item Number"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
   </EditText>
 
 
</merge>

Activity source - AndroidIncludeActivity.java

package com.as400samplecode;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
 
public class AndroidIncludeActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        LinearLayout myLayout = (LinearLayout)findViewById(R.id.linearLayout1);
        View itemInfo1 = getLayoutInflater().inflate(R.layout.item, myLayout, true);
        View itemInfo2 = getLayoutInflater().inflate(R.layout.item, myLayout, true);
        View itemInfo3 = getLayoutInflater().inflate(R.layout.item, myLayout, true);
         
    }

Android common menu options for multiple activities

Android menu options provide user with actions and other options to choose from the action bar of the screen. Some of these actions are common to all the activities for your application, so instead of creating them in each of your activities you can create a BaseActivity that extends the Activity class and does all your menu processing. Then you can extend then base activity class in your application activities to get the same menu options. In case you want a slightly customized menu option for one or more of your activities then override the onPrepareOptionsMenu method to manipulate the menu before its displayed on the screen. Here you can add/remove menu options to the existing menu before being displayed. Here is a simple example doing exactly what we just discussed.





Source for the common menu options - common_menu.xml

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

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu1" android:alphabeticShortcut="a"
        android:title="Menu No. 1" android:orderInCategory="1" />
    <item android:id="@+id/menu2" android:alphabeticShortcut="b"
        android:title="Menu No. 2" android:orderInCategory="2">
        <menu >
        <group android:id="@+id/group2" android:checkableBehavior="single">
            <item android:id="@+id/submenu1" android:title="SubMenu No. 1" />
            <item android:id="@+id/submenu2" android:title="SubMenu No. 2" />
        </group>   
        </menu>
    </item>
     
</menu>

Source for the main activity layout - activity_main.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Main Activity"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

    <Button
        android:id="@+id/nextActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_alignParentTop="false"
        android:layout_below="@id/textView1"
        android:layout_centerHorizontal="true"
        android:text="Go to the next Activity" />

</RelativeLayout>

Source for the next activity layout - activity_next.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Another Activity"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

    <Button
        android:id="@+id/goBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_alignParentTop="false"
        android:layout_below="@id/textView1"
        android:layout_centerHorizontal="true"
        android:text="Go back to previous Activity" />


</RelativeLayout>

Source for the base activity - BaseActivity.java

package com.as400samplecode;


import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class BaseActivity extends Activity{

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.common_menu, menu);
  return true;
 }
  
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {

  switch (item.getItemId()) {
   
  case R.id.menu1:
   Toast.makeText(this, "Clicked: Menu No. 1", Toast.LENGTH_SHORT).show();
   return true;
    
  case R.id.submenu1:
            Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .1", Toast.LENGTH_SHORT).show();
            return true;
         
  case R.id.submenu2:
            Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .2", Toast.LENGTH_SHORT).show();
            return true;  

  default:
   return super.onOptionsItemSelected(item);
  }

 }
  
}

Source for the main activity - MainActivity.java

package com.as400samplecode;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends BaseActivity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        Button nextActivity = (Button) findViewById(R.id.nextActivity);
        nextActivity.setOnClickListener(this);
         
    }
     
    @Override
 public void onClick(View v) {
   
  switch (v.getId()) {
   
  case R.id.nextActivity:
   Intent nextActivity = new Intent(this,NextActivity.class);
   startActivity(nextActivity);
   break;

   
  }
   
 }
     
}

Source for the next activity - NextActivity.java

package com.as400samplecode;


import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class NextActivity extends BaseActivity implements OnClickListener{

 private static final int MENU3 = 1;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);
         
        Button goBack = (Button) findViewById(R.id.goBack);
        goBack.setOnClickListener(this);
    }
     
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
         
        MenuItem menu3 = menu.findItem(MENU3);
        if(menu3 == null){
            menu3 = menu.add(Menu.NONE, MENU3, 3, "Menu No. 3");
        }
         
        return true;
     
    }
     
    @Override
 public boolean onOptionsItemSelected(MenuItem item) {

     super.onOptionsItemSelected(item);
  switch (item.getItemId()) {
   
  case MENU3:
   Toast.makeText(this, "Clicked: Menu No. 3", Toast.LENGTH_SHORT).show();
   return true;
    
  default:
   return super.onOptionsItemSelected(item);
  }

 }
    @Override
    public void onClick(View v) {
      
     switch (v.getId()) {
      
     case R.id.goBack:
      finish();
      break;

      
     }
      
    }
     
     

}