Search This Blog

Thursday, October 4, 2012

passing the Double values to the String

result = number1/number2
String stringdouble= Double.toString(result);
textview1.setText(stringdouble));


or you can use the nuberformate also.


Double result = number1/number2;
NumberFormat nm = NumberFormat.getNumberInstance();
textview1.setText(nm.format(result));



For 3 decimal digit
private static DecimalFormat REAL_FORMATTER = new DecimalFormat("0.###");
textview1.setText(REAL_FORMATTER.format(result));

Wednesday, June 20, 2012

DOM parsing using xml

Put the following code in the xml file.

<Books>
    <Book>
        <Name>Cryptography</Name>
        <Author>Harish</Author>
        <Price>$200</Price>
    </Book>
    <Book>
        <Name>Android</Name>
        <Author>Harish</Author>
        <Price>$250</Price>
    </Book>
</Books>


Method to parse this as the xml file and read in the method.

public HashMap doDomParsing(String strUrl, String strParent, String[] child)
{
       HashMap hmap, hmapchild = null;
       URL url;
       hmap = new HashMap();
       
       try
       {
           //url = new URL(strUrl);
           
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();

          Document doc = db.parse(new InputSource(getClass().getResourceAsStream("/res/raw/parse.xml")));
           
           NodeList nodeList = doc.getElementsByTagName("item");
           for (int i = 0; i < nodeList.getLength(); i++)
           {
               
               Node node = nodeList.item(i);
               NodeList properties = node.getChildNodes();
               
               hmapchild = new HashMap();
               
               for(int j=0 ; j < properties.getLength() ; j++)
               {
                   Node property = properties.item(j);
                   String nodename = property.getNodeName();
                   Log.e("Node NAME", nodename);
                   
                   for(int inew =0 ;inew < child.length ; inew++)
                   {
                       if(nodename.equalsIgnoreCase(child[inew]))
                       {
                           hmapchild.put(nodename, property.getFirstChild().getNodeValue());
                       }
                   }
               }
               hmap.put(i, hmapchild);
           }
       }
       catch (Exception e)
       {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       
       return  hmap;
}

Thursday, June 7, 2012

How to get the battery level And the phone number of the phone

For the bettery level of the phone we need to write the following code.


private void batteryLevel() {
             BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
                       public void onReceive(Context context, Intent intent) {
                                    context.unregisterReceiver(this);
                                    int rawlevel = intent.getIntExtra("level", -1);
                                    int scale = intent.getIntExtra("scale", -1);
                                    int level = -1;
                                    if (rawlevel >= 0 && scale > 0) {
                                                       level = (rawlevel * 100) / scale;
                                    }
             batterLevel.setText("Battery Level Remaining: " + level + "%");
         }
        };
   IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
   registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}



Here level indicates the bettery level of the phone.


For getting the phone number of the phone we have to insert the following code...


TelephonyManager phoneManager = (TelephonyManager) getApplicationContext()                            
                                                                     .getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = phoneManager.getLine1Number();

Here phoneNumber indicates the number of the current phone.


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.