Search This Blog

Monday, January 23, 2012

Get an Display Resolution of the Screen

android.util.DisplayMetrics is a structure describing general information about a display, such as its size, density, and font scaling.

To use android.util.DisplayMetrics to get resolution:

Create a dummy Android Application, add a TextView in main.xml to display the result.

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

Modify the .java file to read DisplayMetrics

 public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            String str_ScreenSize = "The Android Screen is: "
                        + dm.widthPixels
                        + " x "
                        + dm.heightPixels;

            TextView mScreenSize = (TextView) findViewById(R.id.strScreenSize);
            mScreenSize.setText(str_ScreenSize);
     }





Apply Theme To the Activity in AndroidManifest.xml

Android provide some predefine themes in the base package, you can change the theme by adding a code in the file AndroidManifest.xml.

Inside Application tag to take effect on whole Application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
                     package="com.exercise.AndroidTheme"
                     android:versionCode="1"
                     android:versionName="1.0">
<application android:icon="@drawable/icon" 

                     android:label="@string/app_name"
                     android:theme="@android:style/Theme.Black"
                     >
<activity android:name=".AndroidThemeActivity"
                   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>
<uses-sdk android:minSdkVersion="2" />
</manifest>

Or,
Inside Activity tag to take effect on individual Activity.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
                  package="com.exercise.AndroidTheme"
                  android:versionCode="1"
                  android:versionName="1.0">
<application android:icon="@drawable/icon"

                     android:label="@string/app_name"
                    >
<activity android:name=".AndroidThemeActivity"
                android:label="@string/app_name"
                android:theme="@android:style/Theme.Light"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>


@android:style/Theme.Black



@android:style/Theme.Light



@android:style/Theme.Translucent



Saturday, January 21, 2012

How to Show Alert Dialog in Android

Creating alert dialog is very easy. In this tutorial i will be discussing about creating different alert dialogues with one button(ok button), two buttons(yes or no buttons) and three buttons(yes, no and cancel buttons).

Android alert dialog with One button

The following code will create a simple alert dialog with one button. In the following code setTitle() method is used for set Title to alert dialog. setMessage() is used for setting message to alert dialog. setIcon() is to set icon to alert dialog.


AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
// Setting Dialog Title

alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to typicaljava.blogspot.com");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
                // Write your code here to execute after dialog closed
                Toast.makeText(getApplicationContext(), "You clicked on OK",                                          
                                                                Toast.LENGTH_SHORT).show();
                }
        });
// Showing Alert Message
alertDialog.show();


Android alert dialog with two button

The following code will create alert dialog with two button. setPositiveButton() is used to create a positive button in alert dialog and setNegativeButton() is used to invoke negative button to alert dialog.

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.delete);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
                   Toast.makeText(getApplicationContext(), "You clicked on YES", 
                                                       Toast.LENGTH_SHORT).show();
                        }
            });
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();



Android alert dialog with three button

Here setNeutralButton() is used to create a neutral cancel button

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Save File...");
// Setting Dialog Message
alertDialog.setMessage("Do you want to save this file?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.save);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User pressed YES button. Write Logic Here
Toast.makeText(getApplicationContext(), "You clicked on YES",
Toast.LENGTH_SHORT).show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User pressed No button. Write Logic Here
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
}
});
// Setting Netural "Cancel" Button
alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User pressed Cancel button. Write Logic Here
Toast.makeText(getApplicationContext(), "You clicked on Cancel",
Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();




After making the proper screenshot of this code i will be uploading on it....

Tuesday, January 17, 2012

Google release Android Design Site

Google are introducing Android Design for developers to learn about principles, building blocks, and patterns for creating world-class Android user interfaces. Whether you’re a UI professional or a developer playing that role, these docs show you how to make good design decisions, big and small. In the coming months, it will be expanded with more in-depth content.

- Android Design

Monday, January 16, 2012

How to call the asp .Net web service in android

First of all make sure that your web service is in the proper url and get that url with you.

Just like for example i use the web service of "http://www.webservicex.net/ConvertWeight.asmx" for converting the weights from one unit to another.

Now insert the external jar file of ksoap2 which can be downloaded from the following links

To make use of this library in a non-Maven project, follow the instructions in the Android Developer's Guide on how to Add an External Library to your project.

You will need to add a ksoap2-android and all required transitive dependencies to the build path. Luckily the Maven build of the project produces a nice bundle of all these jars in one big file.

The different version of these files are available at

http://code.google.com/p/ksoap2-android/source/browse/#svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/

To download a file from there, right click on "View raw file" and select "Save Link as" (this label differs for different browsers) and you will get the full jar downloaded.

The latest release artifact would be available at

http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.6.0/ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar

with a direct download url of
http://ksoap2-android.googlecode.com/svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.6.0/ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar

Some users seem to experience download problems with IE. Just try a decent browser or download with a command line tool like wget
wget http://ksoap2-android.googlecode.com/svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.6.0/ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar

Now make the java file and insert the following in that code :


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class WebserActivity extends Activity {
private final String NAMESPACE = "http://www.webserviceX.NET/";
private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
private final String METHOD_NAME = "ConvertWeight";

/** Called when the activity is first created. */
@Override

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

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

String weight = "3700";
String fromUnit = "Grams";
String toUnit = "Kilograms";

PropertyInfo weightProp =new PropertyInfo();
weightProp.setName("Weight");
weightProp.setValue(weight);
weightProp.setType(double.class);
request.addProperty(weightProp);

PropertyInfo fromProp =new PropertyInfo();
fromProp.setName("FromUnit");
fromProp.setValue(fromUnit);
fromProp.setType(String.class);
request.addProperty(fromProp);

PropertyInfo toProp =new PropertyInfo();
toProp.setName("ToUnit");
toProp.setValue(toUnit);
toProp.setType(String.class);
request.addProperty(toProp);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {

    androidHttpTransport.call(SOAP_ACTION, envelope);
    SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
    Log.i("myApp", response.toString());
    
    TextView tv = new TextView(this);
     tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
     setContentView(tv);

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

    }
}




Now make an xml file named main.xml and insert the following code into it :

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

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


And finally manifest file should be looks like this : 



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.sencide"
      android:versionCode="1"
      android:versionName="1.0">

    <application android:label="@string/app_name">
        <activity android:name=".WebserActivity"
                  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>
 
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

Friday, January 13, 2012

How to switch between Activities and pass the Data

In Android user interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.

Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java

Opening new Activity

To open new activity following startActivity() or startActivityForResult() method will be used.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);


sending parameters to new Activity

To send parameter to newly created activity putExtra() methos will be used.
i.putExtra("key", "value");
// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");

Receiving parameters on new Activity

To receive parameters on newly created activity getStringExtra() method will be used.
Intent i = getIntent();
i.getStringExtra("key");
// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");

Opening new Activity and expecting result

In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
// Function to read the result from newly created activity
@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
             // Storing result in a variable called myvar
             // get("website") 'website' is the key value result data
             String mywebsite = data.getExtras().get("result");
        }
    }

Sending result back to old activity when StartActivityForResult() is used
Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");
// Setting resultCode to 100 to identify on old activity
setResult(100,in);

Closing Activity

To close activity call finish() method
finish();

Add entry in AndroidManifest.xml

To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags
<activity android:name=".NewActivityClassName"></activity>

Let’s Start with a simple project

So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xml, screen2.xml) and two Acvities(FirstScreenActivity.java,SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this tutorial.

Now lets start by creating a simple project.

1. Create a new project File -> Android Project. While creating a new project give activity name as FirstScreenActivity.

2. Now you need to create user interface for the FirstScreenActivity.java

3. Create a new xml file in layout folder or rename the main.xml to screen1.xml

Right Click on Layout -> New -> Android XML file and name it as screen1.xml

4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.

<?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="Name: "/>
    <EditText android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email: "
        />
    <EditText android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <Button android:id="@+id/btnNextScreen"
             android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send to Next Screen"
            android:layout_marginTop="15dip"/>
</LinearLayout>



5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.
package com.example.androidswitchviews;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class FirstScreenActivity extends Activity {
    // Initializing variables
    EditText inputName;
    EditText inputEmail;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);
        inputName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
        //Listening to button event
        btnNextScreen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Starting a new Intent
                Intent nextScreen = new Intent(getApplicationContext(), SecondScreenActivity.class);
                //Sending data to another Activity
                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("email", inputEmail.getText().toString());
                Log.e("n", inputName.getText()+"."+ inputEmail.getText());
                startActivity(nextScreen);
            }
        });
    }
}
6. Create a class called SecondScreenActivity.javaRight Click on src/yourpackagefolder -> New -> Class and name it as SecondScreenActivity.java
Android creating new class

7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml.
Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the following code in screen2.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="You Entered..."
              android:textSize="25dip"
              android:gravity="center"
              android:layout_margin="15dip"/>
  <TextView android:id="@+id/txtName"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_margin="15dip"
              android:textSize="18dip"/>
  <TextView android:id="@+id/txtEmail"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_margin="15dip"
              android:textSize="18dip"/>
  <Button android:id="@+id/btnClose"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_marginTop="15dip"
              android:text="Close"/>
</LinearLayout>

8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen

package com.example.androidswitchviews;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
Button btnClose = (Button) findViewById(R.id.btnClose);

Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String email = i.getStringExtra("email");
Log.e("Second Screen", name + "." + email);

// Displaying Received data
txtName.setText(name);
txtEmail.setText(email);

// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
//Closing SecondScreen Activity
finish();
}
});

}
}


9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and 
modify the code as below


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidswitchviews"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstScreenActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Add new Activity class name here --->
<activity android:name=".SecondScreen"></activity>

</application>
</manifest>
10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You can see the application is running by switching between screens.