Sunday, 2 December 2012
Saturday, 1 December 2012
XML Parsing in Android
XML Parsing in Android
Xml stands for extensible markup language.There are  types of parsing methods in android
1 SaxPullparser
2 DOM parser
Here we are using SaxPullparser ,because it is more efficient that any other parser in android.
Following is a example for XML parsing using  SaxPullparser 
CustomXML.java
package fortyonepost.com.cx;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import teste.com.teste.R;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CustomXML extends Activity 
{
 //this object will store a reference to the Activity's resources
 private Resources resources;
 //this integer will store the XMLResourceParser events
 private int event;
 //a boolean that will tell if it's the tag we are looking for
 private boolean isCorrectTag = false;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //get the application's resources
        resources = this.getResources();
        try 
        {
         GetAttributes("tutorial");
         GetAttributes("level1");
  } 
        catch (XmlPullParserException e) 
  {
         //Display a toast message.
   Toast.makeText(this, "Could not retrieve the current parser event", Toast.LENGTH_SHORT);
  } 
        catch (IOException e) 
  {
         //Display a toast message.
   Toast.makeText(this, "Could not read XML file", Toast.LENGTH_SHORT);
  }
    }
    public void GetAttributes(String tagName) throws XmlPullParserException, IOException
 {
     //get a XmlResourceParser object to read contents of the 'custom.xml' file
  XmlResourceParser parser = resources.getXml(R.xml.custom);
  //get the initial parser event
  event = parser.getEventType();
  //while haven't reached the end of the XML file 
     while (event != XmlPullParser.END_DOCUMENT) 
     {
      //get the type of the event
      event = parser.getEventType();
      //if parser finds a new tag and its name equals 'tagName'
            if (event == XmlPullParser.START_TAG && parser.getName().contentEquals(tagName)) 
            {
             //print the attribute values at LogCat
             //print the ID
             Log.i("CustomXML", "id:" + parser.getIdAttribute());
             //print the difficulty
             float difficulty = parser.getAttributeFloatValue(null, "difficulty", 0.0f);
             Log.i("CustomXML", "difficulty:" + Float.toString(difficulty));
             //print the number of enemies
             int enemies = parser.getAttributeIntValue(null, "enemies", 0);
             Log.i("CustomXML", "enemies:" + Integer.toString(enemies));
             //Found the tag, set the boolean to true
             isCorrectTag = true;
            } 
            else if (event == XmlPullParser.TEXT && isCorrectTag)
            {
             //Print the tag's content
             Log.i("CustomXML", parser.getText());
             //set isCorrectTag to false;
             isCorrectTag = false;
             //break the loop, we already found what we were looking for
             break;
            }
            //go to the next tag
            parser.next();
     }
     //Release resources associated with the parser
     parser.close();
 }
}
place a xml file in res-xm1-custom.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
 <tutorial id="level" difficulty="1.5" enemies="3">The tutorial.</tutorial>
 <level1 id="level" difficulty="2.6" enemies="10">The first level.</level1>
</resources>
check the logcat in your emulator for output  
Android Custom Spinner with Intent
Android Custom Spinner with Intent
 Following is a example program for custom spinner in android and user can select a particular item and leads to specific activity.
NewspinnerActivity.java
package adsdfd.ghgh;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class NewspinnerActivity extends Activity {
    String[] strings = {"CoderzHeaven","Google",
            "Microsoft", "Apple", "Yahoo","Samsung"};
    String[] subs = {"Heaven of all working codes ","Google sub",
            "Microsoft sub", "Apple sub", "Yahoo sub","Samsung sub"};
    int arr_images[] = { R.drawable.icon,
                         R.drawable.icon, R.drawable.icon,
                         R.drawable.icon, R.drawable.icon, R.drawable.icon};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
        mySpinner.setAdapter(new MyAdapter(NewspinnerActivity.this, R.layout.row, strings));
    }
    public class MyAdapter extends ArrayAdapter<String>{
        public MyAdapter(Context context, int textViewResourceId,   String[] objects) {
            super(context, textViewResourceId, objects);
        }
        @Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
          System.out.println("abcdddddddddddd"+position);
          Intent i=new Intent(getApplicationContext(),abcd.class);
          startActivity(i);
            return getCustomView(position, convertView, parent);
        }
        public View getCustomView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.row, parent, false);
            TextView label=(TextView)row.findViewById(R.id.company);
            label.setText(strings[position]);
            TextView sub=(TextView)row.findViewById(R.id.sub);
            sub.setText(subs[position]);
            ImageView icon=(ImageView)row.findViewById(R.id.image);
            icon.setImageResource(arr_images[position]);
            return row;
            }
        }
   }
then following are the xml  file and in 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"
      android:background="@drawable/icon"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
    android:prompt="@string/prompt"
    />
</LinearLayout>
then the row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
    <ImageView
         android:id="@+id/image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/icon"/>
    <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="3dip"
         android:layout_marginTop="2dip"
         android:textColor="@drawable/red"
         android:textStyle="bold"
         android:id="@+id/company"
         android:text="CoderzHeaven"
         android:layout_marginLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="2dip"
         android:textColor="@drawable/darkgrey"
         android:layout_marginLeft="5dip"
         android:id="@+id/sub"
         android:layout_below="@+id/company"
         android:text="Heaven of all working codes"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</RelativeLayout>
abcd.class
package adsdfd.ghgh;
import android.app.Activity;
import android.os.Bundle;
public class abcd extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);
 }
}
use hex color codes instead of color names in Java
use hex color codes instead of color names in Java
  paint.setColor(Color.parseColor("#9d4807"));
click here
How to start a Activity from Service in Android
How to start a Activity from Service in Android
within the service
Intent dialogIntent = new Intent(getBaseContext(), tone1.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dialogIntent);
Wednesday, 21 November 2012
marquee Example in Android
marquee Example in Android<?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" > <TextView android:id="@+id/MarqueeText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:freezesText="true" android:marqueeRepeatLimit="marquee_forever" android:textSize="30dp" android:scrollHorizontally="true" android:singleLine="true" android:text="hai friends Distance is aaaaaaaaaaaa aaaaaaaaa" > </TextView> </LinearLayout>
Saturday, 10 November 2012
Set an onClickListner method to MapActivity
Set an onClickListner method to MapActivity
1) 
First do the setContentView, after that the Button is findable. The system could not find your Button now, so that's why it is a null. Your MapView map also would be a null in your code. 2) If you define an object within {} it is only available within that {} You probably going to need the Object "but" later, so make it a private variable of the class. 3) Classname should start with a capital. 4) Visit anddev.org or some site like that for coding problems, xda seems to be more focused on system/firmware issues, not application code. So, this should work: public class MainActivity extends MapActivity { final Button but; final MapView map; @Override public boolean isRouteDisplayed() { return false; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); but = (Button) findViewById(R.id.gpsButton); but.setOnClickListener(new View.OnClickListener() { public void onClick(View v){ } }); map = (MapView) findViewById(R.id.myMap); } }  | |
remove title bar in Android
How to remove title bar in Android
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jithu.c"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
   
   
<activity android:name=".PlacefinderdemoActivity"
     
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:required="true" android:name="com.google.android.maps"></uses-library>
<activity android:name=".alm.alarm"></activity>
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jithu.c"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<activity android:name=".PlacefinderdemoActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:required="true" android:name="com.google.android.maps"></uses-library>
<activity android:name=".alm.alarm"></activity>
</application>
</manifest>
Wednesday, 26 September 2012
Asynchronous tasks in Android applications
Asynchronous tasks in Android applications
When we are writing an application and we want to perform a heavy background operation we have to start a new thread that will handle this operation and then publish the results on the UI thread for further processing. Having to manipulate threads can very often lead to complex pieces of code and it is pretty easy to mess things up really fast!
Android provides a class that enables proper and easy use of the UI thread and makes our life really easy. AsychTask is a class that allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called
AsyncTask must be subclassed to be used and the subclass must override at least one method (
Android provides a class that enables proper and easy use of the UI thread and makes our life really easy. AsychTask is a class that allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called
Params, Progress and Result, and 4 steps (functions), calledonPreExecute, doInBackground, onProgressUpdate and onPostExecute.AsyncTask must be subclassed to be used and the subclass must override at least one method (
doInBackground), and most often will override a second one ( onPostExecute). Now let's take a look at the three types used by an asynchronous task:Params: The type of the parameters sent to the task upon execution.Progress: The type of the progress units published during the background computation.Result: The type of the result of the background computation.
- onPreExecute: Invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
 - doInBackground: Invoked on a background thread after onPreExecute finishes executing. This function is used to perform background operations/computations that can take a long time. In this function we can use publishProgress to publish one or more units of progress. These values are published on the UI thread, in the
onProgressUpdatestep. - onProgressUpdate: Invoked on the UI thread after a call to publishProgress.Usually it is used to animate a progress bar.
 -  
onPostExecute: Invokedon the UI threadafter doInBackground finishes executing.The result of the background computation is passed to this step as a parameter. 
package a.b;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class Ayntaskdemo1Activity extends Activity {
    /** Called when the activity is first created. */
 private ProgressBar mProgressBar;
 private Button mCalculationButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        mCalculationButton = (Button) findViewById(R.id.calculation);
        mCalculationButton.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    CalculationTask task = new CalculationTask();
    task.execute();
   }
  });
    }
    /** Task that handles the procedure to store a route on the local database */
    private class CalculationTask extends AsyncTask<Void, Integer, Long> {
     @Override
     protected void onPreExecute() {
      // Initialize bar
      mProgressBar.setProgress(0);
     }
     @Override
     protected Long doInBackground(Void... data) {
      // Store route
      long counter = 0;
      for(int i = 1; i <= 10000000; i++) {
       counter += i;
       if(i % 100000 == 0) {
        publishProgress((int) i/100000);
       }
      }
      return counter;
     }
     @Override
     protected void onProgressUpdate(Integer... progress) {
      mProgressBar.setProgress(progress[0]);
        }
     @Override
     protected void onPostExecute(Long result) {
      Class gallery;
         try
         {
          gallery=Class.forName("a.b.gallery");
          Intent i=new Intent(Ayntaskdemo1Activity.this,gallery);
       //     startActivityForResult(i,PICK_EXISTING_PHOTO_RESULT_CODE);
                 startActivity(i);
         }
         catch(ClassNotFoundException e)
         {
          e.printStackTrace();
         }
      // Publish result
      Toast.makeText(getApplicationContext(), "Counter is " + result, Toast.LENGTH_LONG).show();
     }
    }
}
Tuesday, 25 September 2012
JSON parsing example 1
JSON parsing example 1
package a.b;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class Jsonparsedemo1Activity extends Activity {
TextView tv1,tv2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
// {"id":12,"name":12,"status":"ok","volumes":[{"id":17592,"name":"root","status":"ok"}]}
final String customJSON = "{\"id\":12,\"name\":12,\"status\":\"ok\",\"volumes\":[{\"id\":17592,\"name\":\"root\",\"status\":\"ok\"}]}"; // tv1.setText(customJSON);
try
{
JSONObject jobj=new JSONObject(customJSON);
String id=jobj.getString("id");
String myname=jobj.getString("name");
String status1=jobj.getString("status");
String result1="id1="+id+"\n"+"name1="+myname+"\n"+"status1"+status1;
tv1.setText(result1);
JSONArray jarray=jobj.getJSONArray("volumes");
JSONObject myobj=jarray.getJSONObject(0);
String id2=myobj.getString("id");
String myname2=myobj.getString("name");
String status2=myobj.getString("status");
String result="id2="+id2+"\n"+"name2="+myname2+"\n"+"status2"+status2;
tv2.setText(result);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(Jsonparsedemo1Activity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Friday, 7 September 2012
Android Animation Example 2
Android Animation Example 2
SurfaceActivity.java
package a.b;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class SurfaceActivity extends Activity  implements OnTouchListener {
 Myview abc;
 float x,y;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        abc=new Myview(this);
        abc.setOnTouchListener(this);
        setContentView(abc);
        x=0;
        y=0;
    }
 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  abc.pause();
 }
 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  abc.resume();
 }
 @Override
 public boolean onTouch(View arg0, MotionEvent event) {
  // TODO Auto-generated method stub
  x=event.getX();
  y=event.getY();
  return false;
 }
 public class Myview extends SurfaceView implements Runnable{
  SurfaceHolder myholder;
  Thread t=null ;
  boolean isRunning=false;
  public Myview(Context context) {
   // TODO Auto-generated constructor stub
   super(context);
   myholder=getHolder();
  }
  public void pause()
  {
   isRunning=false;
   while(true)
   {
   try {
    t.join();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   break;
   }
   t=null;
  }
  public void resume()
  {
   isRunning=true;
   t=new Thread(this);
   t.start();
  }
  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(isRunning)
   {
    if(!myholder.getSurface().isValid())
     continue;
    Canvas canvas=myholder.lockCanvas();
    canvas.drawRGB(02, 02, 1);
    if(x !=0 && y !=0)
    {
     Bitmap test=BitmapFactory.decodeResource(getResources(),R.drawable.f);
     canvas.drawBitmap(test,x,y,null);
    }
    myholder.unlockCanvasAndPost(canvas);
   }
  }
 }
}
set theme in manifest
set theme in manifest
android:theme="@android:Style/Theme.Wallpaper.NoTitleBar"
Thursday, 6 September 2012
Introduction to Animation In Android
Introduction to Animation In Android
AninmationdemoActivity.java
package a.b;
import android.app.Activity;
import android.os.Bundle;
public class AninmationdemoActivity extends Activity {
Myanimation anim;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
anim=new Myanimation(this);
setContentView(anim);
}
}
Myanimation .java
package a.b;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
public class Myanimation extends View {
Bitmap img,img1,img2,img3;
float changey;
public Myanimation(Context context) {
super(context);
// TODO Auto-generated constructor stub
img=BitmapFactory.decodeResource(getResources(), R.drawable.r);
img1=BitmapFactory.decodeResource(getResources(), R.drawable.b);
changey = 0;
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(img, (canvas.getWidth()/2),changey,null);
canvas.drawBitmap(img1, (canvas.getWidth()/8),changey,null);
if(changey < canvas.getHeight())
{
changey +=5;
}else
{
changey =0;
}
invalidate();
}
}
Subscribe to:
Comments (Atom)
