Search This Blog

Tuesday, March 27, 2012

Display a Random Number in android on button click

To generate random number in Android, class java.util.Random can be used.

This class java.util.Random provides methods that generates pseudo-random numbers of different types, such as int, long, double, and float.

It support two public constructor:
Random() - Construct a random generator with the current time of day in milliseconds as the initial state.
Random(long seed) - Construct a random generator with the given seed as the initial state.


Put the following code in the main.xml.

<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Generate Random number"
android:id="@+id/generate"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/generatenumber"
/>
</LinearLayout>


RandomNumber.java

import java.util.Random;

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

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

                        final Random myRandom = new Random();

                        Button buttonGenerate = (Button)findViewById(R.id.generate);
                        final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);

                        buttonGenerate.setOnClickListener(new OnClickListener(){

                                 @Override
                                 public void onClick(View v) {
                                      // TODO Auto-generated method stub
                                      textGenerateNumber.setText(String.valueOf(myRandom.nextInt()));
                                  }
                      });
       }
}

Monday, March 26, 2012

Android Text to Speech

TextToSpeech is the great feature of Android. Text to Speech (TTS) which speaks the text in different languages usually selected by the user or you can also put the default user language for the TTS.
First of all make the xml file with the one EditText and Button. And make the following code working in your java file for the TTS. You need to implement the Interface of the TTS TextToSpeech.OnInitListener.

import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */

private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

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

                       tts = new TextToSpeech(this, this);
                       btnSpeak = (Button) findViewById(R.id.btnSpeak);
                       txtText = (EditText) findViewById(R.id.txtText);

                       // button on click event
                       btnSpeak.setOnClickListener(new View.OnClickListener() {

                                            @Override
                                            public void onClick(View arg0) {
                                                             TTS();
                                             }

                        });
                }

           @Override
           public void onDestroy() {
                     // Don't forget to shutdown tts!
                     if (tts != null) {
                     tts.stop();
                     tts.shutdown();
            }
            super.onDestroy();
            }

            @Override
            public void onInit(int status) {

                           if (status == TextToSpeech.SUCCESS) {
                           int result = tts.setLanguage(Locale.US);
                           if (result == TextToSpeech.LANG_MISSING_DATA
                                                 || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                                                 Log.e("TTS", "This Language is not supported");
                            }

                            else
                           {
                                           btnSpeak.setEnabled(true);
                                           TTS();
                            }

                      }
                      else 
                      {
                                Log.e("TTS", "Initilization Failed!");
             }

        }

        private void TTS() {

                   String text = txtText.getText().toString();

                   tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
          }
}



You can change the language by the oneline code 

tts.setLanguage(Locale.CHINESE);
tts.setLanguage(Locale.GERMANY);

You can select the speed of the speaking via putting the setPitch() method.Default value is 1.0 of the pitch rate.You can select the pitch rate higher or lower according to the requirement.

tts.setPitch(0.6);
The speed rate can be set using setSpeechRate(). This also will take default of 1.0 value. You can double the speed rate by setting 2.0 or make half the speed level by setting 0.5.

tts.setSpeechRate(1.5);

Thursday, March 8, 2012

Creating the Options Menu and Itemselected methods in android

You can use the following code inside the 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="s"
android:title="menu1 title"
/>
<item
android:id="@+id/menu2"
android:alphabeticShortcut="t"
android:title="menu2 title"
/>
</menu>

now the two methods for the invoking the menu and function which is to be called on the item selected.

@override
public boolean onCreateOptionsMenu (Menu menu){
super.onCreateOptionsMenu(menu);
//menu.add(R.menu.main_menu);
//menu.add(Menu.NONE, 101,Menu.FIRST,this.getResources().getString(R.string.Title));
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.main_menu, menu);
return true;
}




you can use the both the method of invoking the menu. First one by the menu.add and second one by the inflating the menu.xml file Now on the itemselectedlistner is used by the following code.

public boolean onOptionsItemSelected(MenuItem item){
              switch(item.getItemId()){
                       case R.id.menu1:
                       // your code here
                       case R.id.menu2:
                       // your code here
               }
     return false;
}



just pass the id in switch-case and do whatever you want by selecting the those menu.

Maintaining the state of the User in Android application throughout


you can use the Application class in you activity. By extending the Application class you can maintain the stat in android throughout the application. It means you can call those variables in the application in all the activity.

public class SampleApplication extends Application {

private static String username;
private static String password;

@Override
public void onCreate() {
super.onCreate();
username="";
password="";
}

public static String getUsername() {
return username;
}

public static void setUsername(String username) {
SampleApplication.username = username;
}

public static String getPassword() {
return password;
}

public static void setPassword(String password) {
SampleApplication.password = password;
}


}


By using this code you can set and get the username and password in any activity. And maintain the state of your username and password. Just you need to add the class name in the manifest.xml like this way.

<application
android:name=".SampleApplication"
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SampleApp"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

You can access you application variables with static getters and setters from any activity or service.:

SampleApplication.setUsername("");
String currentUserName=SampleApplication.getUsername();
SampleApplication.setPassword("");
String currentPassword=SampleApplication.getPassword();





By this you can maintain the stat of the user in all over the application.

Checking the network Availability

You can check the network is available or not in your android device.

public boolean isNetworkAvailable() 
{
   ConnectivityManager cm=                        
                 (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
   // if no network is available networkInfo will be null, otherwise check if we are connected 

   if (networkInfo != null && networkInfo.isConnected()) 
   { 
             return true; 
    }
 return false; 
}


OR





package com.network.availibility;


import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;


public class NetworkAvailibilityActivity extends Activity {
    /** Called when the activity is first created. */
private boolean isconnected;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        TextView tx = (TextView)findViewById(R.id.ischeking);
        
        
        isconnected = isConnected(NetworkAvailibilityActivity.this);
        
        if(isconnected == true){
        tx.setText("You are connected to the internet");
        }
        else{
        tx.setText("Please connect your phone to internet");
        }
        
        
    }
    public static boolean isConnected(Context context) {
    
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);


    NetworkInfo wifiNetwork =
    cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
    NetworkInfo mobileNetwork =
    cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (wifiNetwork.isAvailable()) {
    return wifiNetwork.isConnectedOrConnecting();
    }


    
    else if (mobileNetwork.isAvailable()) {
    return mobileNetwork.isConnectedOrConnecting();
    }


    
    else if(activeNetwork.isAvailable()) {
    return activeNetwork.isConnectedOrConnecting();
    }
    else{
    return false;
    }
 }
}

You just need to give the permission of the INTERNET and  ACCESS_NETWORK_STATE.

Run the ProgresBar using the Handler

First of all create tha main.xml file 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" >
 <ProgressBar android:id="@+id/progressBar1" style="?       
          android:attr/progressBarStyleHorizontal" 
          android:layout_width="match_parent" 
          android:layout_height="wrap_content" 
          android:indeterminate="false" 
          android:max="10" 
          android:padding="4dip" >
 </ProgressBar>
      <Button android:id="@+id/button1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:onClick="startProgress" 
        android:text="Start Progress" > 
</Button> 
</LinearLayout>

Now make an java file and insert the following code into it.

public class ProgressBar extends Activity { 
                             private Handler handler; 
                             private ProgressBar progress;
/** Called when the activity is first created. */ 
                @Override  
                 public void onCreate(Bundle savedInstanceState) { 
                     super.onCreate(savedInstanceState); 
                     setContentView(R.layout.main); 
                     progress = (ProgressBar) findViewById(R.id.progressBar1); 
                     handler = new Handler(); 
             } 

    public void startProgress(View view) { 
                 // Do something long 
                 Runnable runnable = new Runnable() { 
                           @Override public void run() 
                            { 
                                    for (int i = 0; i <= 10; i++) { 
                                             final int value = i; 
                                             try { 
                                                   Thread.sleep(2000); 
                                                   }
                                             catch (InterruptedException e) { 
                                                     e.printStackTrace(); 
                                              }
                  handler.post(new Runnable() { 
                                @Override public void run() { 
                                                 progress.setProgress(value); 
                                     } 
                            }); 
                        }
                   } 
               }; 
                    new Thread(runnable).start(); 
               }
}

Run your application. Once you press your button the ProgressBar will get updated from the background thread.

Tuesday, March 6, 2012

Implement Android Browser using simple webview

Here i am posting the creating browser api with simple built in browser functionality in android using WebView.


First of all make an xml file and put the following code here.

<?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"
/>
<WebView android:id="@+id/wv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

</LinearLayout>


Now make an java file and enter the following code here.


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

                      String myURL = "http://typicaljava.blogspot.com";
                      WebView browser=(WebView)findViewById(R.id.mybrowser);

                      browser.getSettings().setJavaScriptEnabled(true);
                      browser.loadUrl(myURL);
                   }
     }


We just need to add the permission in the menifest file.


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