Wednesday, 31 October 2012

How to parse xml file in Assert folder in Android using Dom Parser

This below example parse xml file which in assert folder of our project.
This file contains employee details this example parse xml file data and set to textview.

Data file (employeesdetails.xml) create this file assert folder .
In this example we read this file

<?xml version="1.0"?>
<employee_list>
<employee>
    <employee_id>1001</employee_id>
<employee_name>Android </employee_name>
<employee_salary>50000</employee_salary>
</employee>
<employee>
    <employee_id>1002</employee_id>
<employee_name>Surya </employee_name>
<employee_salary>60000</employee_salary>
</employee>
<employee>
    <employee_id>1003</employee_id>
<employee_name>Narayana </employee_name>
<employee_salary>40000</employee_salary>
</employee>
</employee_list>

Android UI 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="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="86dp"
        android:layout_marginTop="77dp"
        android:text="TextView" />

</RelativeLayout>

Android Activity (MainActivity.java)

package com.androidsurya.xmlparsing;

import java.io.InputStream;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView textView;
InputStream inputStream;
DocumentBuilderFactory dbFactory;
DocumentBuilder docBuilder;
Document doc;
Element element;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
try {
inputStream = getAssets().open("employeesdetails.xml");

dbFactory = DocumentBuilderFactory.newInstance();
docBuilder = dbFactory.newDocumentBuilder();
doc = docBuilder.parse(inputStream);

element = doc.getDocumentElement();
element.normalize();

NodeList nList = doc.getElementsByTagName("employee");
for (int i = 0; i < nList.getLength(); i++) {

Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
textView.setText(textView.getText() + "\nEmployee Id : "
+ getValuefromTagName("employee_id", element2) + "\n");
textView.setText(textView.getText() + "Employee Name : "
+ getValuefromTagName("employee_name", element2) + "\n");
textView.setText(textView.getText() + "Employee Salary: "
+ getValuefromTagName("employee_salary", element2) + "\n");
textView.setText(textView.getText()
+ "===========================");
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

private static String getValuefromTagName(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}

}

Register Activity in Android Manifest file

 <activity
            android:name="com.androidsurya.xmlparsing.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Output Screenshot





















Friday, 26 October 2012

Android WebView Example


View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.


Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:

Here Below example source code shows webview in Android

UI Layout(webview.xml)

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

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

Android Activity class(OpenWebView.java)

package com.androidsurya.webview;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class OpenWebView extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://androidsurya.blogspot.in/");

}
}

Note: To open webview your application should use Internet Permission

Permission in Android Manifest File

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

Register Android Activity in Android Manifest File

 <activity
            android:name="com.androidsurya.webview.OpenWebView"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Output Screenshot:






















Wednesday, 24 October 2012

Radio Button Example in Android

A radio button is a two-states button that can be either checked or unchecked. When the radio button is unchecked, the user can press or click it to check it. However, contrary to a CheckBox, a radio button cannot be unchecked by the user once checked.

Radio buttons are normally used together in a RadioGroup. When several radio buttons live inside a radio group, checking one radio button unchecks all the others.

This example shows the how to create a Radio button in Xml File...and when user choose one option from Radio Buttons. Choose button text will appear in Text View.....

UI layout(radiobutton.xml) create this xml in res/layout 

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

    <RadioGroup
        android:id="@+id/rbgroup"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/button1"
            android:checked="false"
            android:text="Android " />

        <RadioButton
            android:id="@+id/button2"
            android:checked="false"
            android:text="iphone" />
    </RadioGroup>

    <Button
        android:id="@+id/select"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Confrom selection shows in Text " >
    </Button>

</LinearLayout>


Android Activity Class(RBexample.java)

package com.androidsurya.radiobutton;

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

public class RBexample extends Activity {

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

RadioButton rbone;
RadioButton rbtwo;
TextView textView;
Button button;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radiobutton);
rbone = (RadioButton) findViewById(R.id.button1);
rbtwo = (RadioButton) findViewById(R.id.button2);
button = (Button) findViewById(R.id.select);
textView = (TextView) findViewById(R.id.textshow);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (rbone.isChecked() == true) {
textView.setText("Andriod");
}
if (rbtwo.isChecked() == true) {
textView.setText("iphone");
}
}
});
}
}

Register Android Activity in Android Manifest file

  <activity
            android:name="com.androidsurya.radiobutton.RBexample"
            android:label="@string/app_name" >

Output Screenshot






















For More information about Radio Group: Android Developers site

Wednesday, 17 October 2012

AppiRater in in Android (Rate Me dialog in Android) Example

So many people think that how to show Rate me dialog in Android (AppiRater in Iphone) . First Create a class (AppRater.java) AppRater and copy the below code.And change APP_TITLE  , APP_PNAME values according to your application.

This Rate me dialog contains 3 buttons 1  Rate me - forward request to Android Market
                                                           2  Reminder me Later -Dialog dismiss and open once again
                                                           3  No Thanks - Dialog never show again.

public class AppRater {

    private final static String APP_TITLE = "YOUR-APP-NAME";
    private final static String APP_PNAME = "YOUR-PACKAGE-NAME";
 
    private final static int DAYS_UNTIL_PROMPT = 3;
    private final static int LAUNCHES_UNTIL_PROMPT = 7;
 
    public static void app_launched(Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) { return ; }
     
        SharedPreferences.Editor editor = prefs.edit();
     
        // Increment launch counter
        long launch_count = prefs.getLong("launch_count", 0) + 1;
        editor.putLong("launch_count", launch_count);

        // Get date of first launch
        Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
        if (date_firstLaunch == 0) {
            date_firstLaunch = System.currentTimeMillis();
            editor.putLong("date_firstlaunch", date_firstLaunch);
        }
     
        // Wait at least n days before opening
        if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
            if (System.currentTimeMillis() &gt;= date_firstLaunch +
                    (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
                showRateDialog(mContext, editor);
            }
        }
     
        editor.commit();
    }
 
    public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
        final Dialog dialog = new Dialog(mContext);
        dialog.setTitle("Rate " + APP_TITLE);

        LinearLayout ll = new LinearLayout(mContext);
        ll.setOrientation(LinearLayout.VERTICAL);
     
        TextView tv = new TextView(mContext);
        tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
        tv.setWidth(240);
        tv.setPadding(4, 0, 4, 10);
        ll.addView(tv);
     
        Button b1 = new Button(mContext);
        b1.setText("Rate " + APP_TITLE);
        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
                dialog.dismiss();
            }
        });      
        ll.addView(b1);

        Button b2 = new Button(mContext);
        b2.setText("Remind me later");
        b2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        ll.addView(b2);

        Button b3 = new Button(mContext);
        b3.setText("No, thanks");
        b3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (editor != null) {
                    editor.putBoolean("dontshowagain", true);
                    editor.commit();
                }
                dialog.dismiss();
            }
        });
        ll.addView(b3);

        dialog.setContentView(ll);      
        dialog.show();      
    }
}

After copy and modify the above file u just call (AppRater) that class in your main Activity onCreate( ) method  using below code.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppRater.showRateDialog(this, null);
AppRater.app_launched(this) ;
}

Now you can see Rate Me dialog in your Application. after 3 days.









Source:androidsnippets

Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...