Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Thursday, 19 April 2012

Count How many times your application has run on device

Count howmany time your application has opened on device using shared preference.
put following code in your Main activity.




        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);
        
        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);
        
        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");
        
        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important


YOUR CODE WILL LOOK LIKE FOLLOWING,



package com.AppOpenedCount;


import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;


public class CountAppOpenedActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);
        
        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);
        
        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");
        
        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important
    }
        
    
}

Monday, 16 April 2012

Simple XML Parsing in android


ToolsActivity.java  (Main activity )

Package ....
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


public class ToolsActivity extends Activity {
    /** Called when the activity is first created. */

    private List<String> RankData = new ArrayList<String>();
    private List<String> AlexaData = new ArrayList<String>();
    private List<String> CompeteData = new ArrayList<String>();

   
    TextView tv_PageRnk, tv_PageAlx, tv_CompeteRnk;
    EditText et_url;
    Button check;
    String UrlValue;
   
    private AdView adView;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

              
        tv_PageAlx = (TextView) findViewById(R.id.tv_PageAlexa);
        tv_PageRnk = (TextView) findViewById(R.id.tv_PageRank);
        tv_CompeteRnk = (TextView) findViewById(R.id.tv_CompeteRank);
        et_url = (EditText) findViewById(R.id.editText1);
        check = (Button) findViewById(R.id.button1);

        // UrlValue = et_url.getText().toString();
        Log.d("URL value : ", String.valueOf(UrlValue));

        check.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                ParseXml();
                et_url.setText("");
            }
        });

    }
   
     public boolean onCreateOptionsMenu(Menu menu) {
       
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.my_options_menu, menu);
            return true;
        }
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.about:
            startActivity(new Intent(this, About.class));
            return true;
            case R.id.help:
            startActivity(new Intent(this, Help.class));
            return true;
            default:
            return super.onOptionsItemSelected(item);
            }
        }

    public void ParseXml() {

        try {
// DONT USE THIS LINK IT WILL NO WORK USE YOUR OWN LINK
            URL rssUrl = new URL("http://els.in/EMS/rank.php?url="
                    + et_url.getText().toString());
            SAXParserFactory mySAXParserFactory = SAXParserFactory
                    .newInstance();
            SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
            XMLReader myXMLReader = mySAXParser.getXMLReader();
            RSSHandler myRSSHandler = new RSSHandler();
            myXMLReader.setContentHandler(myRSSHandler);
            InputSource myInputSource = new InputSource(rssUrl.openStream());
            myXMLReader.parse(myInputSource);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        tv_PageRnk.setText(String.valueOf(RankData).replace("[", "")
                .replace("]", ""));
        Log.d("Parsing", "Page Rank : " + String.valueOf(RankData));

        // tv_PageAlx.setText(String.valueOf(AlexaData));
        tv_PageAlx.setText(String.valueOf(AlexaData).replace("[", "")
                .replace("]", ""));
        Log.d("Parsing", "Page Alexa : " + String.valueOf(AlexaData));

        tv_CompeteRnk.setText(String.valueOf(CompeteData).replace("[", "")
                .replace("]", ""));
        Log.d("Parsing", "Compete Rank : " + String.valueOf(CompeteData));

        RankData.clear();
        AlexaData.clear();
        CompeteData.clear();
    }

    private class RSSHandler extends DefaultHandler {
        final int stateUnknown = 0;
        final int statesRankview = 1;
        final int statesAlexaview = 2;
        final int statesCompeteview = 3;

        int state = stateUnknown;

        @Override
        public void startDocument() throws SAXException {
        }

        @Override
        public void endDocument() throws SAXException {
        }

        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            if (localName.equalsIgnoreCase("pagerank"))
                state = statesRankview;

            else if (localName.equalsIgnoreCase("alexa"))
                state = statesAlexaview;

            else if (localName.equalsIgnoreCase("compete"))
                state = statesCompeteview;
            else
                state = stateUnknown;
        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            state = stateUnknown;
        }

        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            String strCharacters = new String(ch, start, length);
            if (state == statesRankview)
                RankData.add(strCharacters);

            else if (state == statesAlexaview)
                AlexaData.add(strCharacters);

            else if (state == statesCompeteview)
                CompeteData.add(strCharacters);

        }

    }
}
   

main.xml file
Put views according to requirement


Integrate AdMob in Android

How to Integrate AdMob in android device??

First of all open project.Properties file and set target to 15

# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "ant.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-15


Now download GoogleAdMobAdsSdk-4.3.1.jar file and copy & paste it into your project.
Then Select your project--> Right Click-- > Properties --> Java Build path --> Libraries --> Add JARs --> select your project from list and select that GoogleAdMobAdsSdk-4.3.1.jar fiel --> ok


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:id="@+id/linearLayout2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

   
    <LinearLayout
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:id="@+id/mainLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>


In AndroidMenifest.xml file Provide Internet and Network_state permission and add com.google.ads.AdActivity activity (See following code)


  <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AdvertisementActivity"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.google.ads.AdActivity"          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
    </application>

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


In AdvertisementActivity.java (Main Activity)

package com.advetise.ads;

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

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class AdvertisementActivity extends Activity {
    /** Called when the activity is first created. */
   
    private AdView adView;

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

        DisplayAds();
    }

    public void DisplayAds() {
        // Create the adView
        adView = new AdView(this, AdSize.BANNER, "YOUR_KEY_HERE");
        // adView .setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
        // LayoutParams.WRAP_CONTENT));

        // Lookup your LinearLayout assuming it’s been given
        // the attribute android:id="@+id/mainLayout"
        LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);

        // Add the adView to it
        layout.addView(adView);
        AdRequest re = new AdRequest();
        re.setTesting(false);// this must be false when apps is released in the
                                // market
        // Initiate a generic request to load it with an ad
        adView.loadAd(new AdRequest());

    }

    @Override
    public void onDestroy() {
        if (adView != null) {
            adView.destroy();
        }
        super.onDestroy();
    }

}

Thanks a lot...
Ronak Pandya....

Create Option Menu for Android device

We are going to create option menu when user touches option on device one menu will displayed like, Help and about Us.

DeviceOptionsMenuActivity.java (Main activity)

package pkg.DeviceOptionsMenu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;

public class DeviceOptionsMenuActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
    }
   
    public boolean onCreateOptionsMenu(Menu menu) {
       
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.my_options_menu, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.about:
        startActivity(new Intent(this, About.class));
        return true;
        case R.id.help:
        startActivity(new Intent(this, Help.class));
        return true;
        default:
        return super.onOptionsItemSelected(item);
        }
    }
}


AboutUs.java

package pkg.DeviceOptionsMenu;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class About extends Activity {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.about);
    }
   

}
 
Help.java

package pkg.DeviceOptionsMenu;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class Help extends Activity {
   

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.help);
    }
}
 
Dont change main.xml keep it as it is..we dont need that one for our example.


Now Create about.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" >

   
        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="fill_parent"
            android:layout_height="280dp"
            android:layout_weight="0.19" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="139dp"
                android:textSize="9pt"
                android:text="This Application is sponsored by"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#717C40" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView1"
                android:layout_below="@+id/textView1"
                android:textSize="8pt"
                android:text="Ronak Pandya"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#717C40" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView2"
                android:layout_below="@+id/textView2"
                android:textSize="8pt"
                android:text="You are free to use it."
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#717C40" />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView3"
                android:layout_centerVertical="true"
                android:textSize="8pt"
                android:text="Please contact us at,"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#772020" />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView4"
                android:layout_below="@+id/textView4"
                android:textSize="8pt"
                android:text="support@support.com"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0F53FF" />
        </RelativeLayout>
 
</LinearLayout>


help.xml (Write whatever content you want to write....)

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

</LinearLayout>


Now Create a dir called menu--> in that create xml file called my_options_menu.xml in
i.e res/menu/my_options_menu.xml

my_options_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/about"
android:title="About" />
<item android:id="@+id/help"
android:title="Help" />
</menu>

Finally Add Both activities Help and about.java to AndroidMenifiest.xml file 

Run it...