13/11/2013

Learn Android Site

1. http://learnandroideasily.blogspot.in

2. http://androidsurya.blogspot.in

3. http://www.tutorialspoint.com/android
 

05/11/2013

Selected Listener in Button and Listview Background color

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_pressed"
          android:state_focused="true"
          android:state_pressed="true"></item>
    <item android:drawable="@drawable/btn_default"
          android:state_focused="true"
          android:state_pressed="false"></item>
    <item android:drawable="@drawable/btn_pressed"
          android:state_focused="false"
          android:state_pressed="true"></item>
    <item android:drawable="@drawable/btn_default"></item>

</selector>

29/07/2013

Android Shared Preferences




public class MainActivity extends Activity
{
    Button btnSignedIn, btnClearData;
    CheckBox chkSignedIn;
    EditText etUsername, etPassword;

    private static final String PREFRENCES_NAME = "myprefrences";

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

        etUsername = (EditText) findViewById(R.id.etusername);
        etPassword = (EditText) findViewById(R.id.etpass);
        chkSignedIn = (CheckBox) findViewById(R.id.chksingin);

        SharedPreferences settings = getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
        String name = settings.getString("name", "");
        String password = settings.getString("pwd", "");

        etUsername.setText(name);
        etPassword.setText(password);

        btnSignedIn = (Button) findViewById(R.id.btnsignin);
        btnSignedIn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String strName = etUsername.getText().toString();
                String strPass = etPassword.getText().toString();

                if (null == strName || strName.trim().length() == 0)
                {
                    etUsername.setError("Enter Your Name");
                    etUsername.requestFocus();
                }
                else if (null == strPass || strPass.trim().length() == 0)
                {
                    etPassword.setError("Enter Your Password");
                    etPassword.requestFocus();
                }
                else
                {
                    if (chkSignedIn.isChecked())
                    {

                        showToast("User Name and Password Saved!!!");
                        SharedPreferences settings = getSharedPreferences(PREFRENCES_NAME, Context.MODE_PRIVATE);
                        settings.edit().putString("name", strName).putString("pwd", strPass).commit();
                       
                    }
                    else
                    {
                        showToast("Tick keep me logged in!!!");

                    }

                }
            }
        });

        btnClearData = (Button) findViewById(R.id.btnclear);
        btnClearData.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v)
            {
                etUsername.setText("");
                etUsername.requestFocus();
                etPassword.setText("");
                chkSignedIn.setChecked(false);

                SharedPreferences settings = getSharedPreferences(PREFRENCES_NAME, Context.MODE_PRIVATE);
                settings.edit().clear().commit();
            }
        });

    }

    private void showToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();

    }
}

Click Sample Source Code Link

28/07/2013

Android Simple Sqlite Program

main.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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Android Advance SQLite Tutorial"
        android:textSize="18dp"
        android:text />

    <Button
        android:id="@+id/btn_add"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Add Products"
        android:text />

    <Button
        android:id="@+id/btn_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="View Products"
        android:text />

</LinearLayout>




  - We have to create two buttons for database operation.

AndroidAdvanceSqliteActivity.java


public class AndroidAdvanceSqliteActivity extends Activity implements
        OnClickListener {

    private Button btn_add, btn_view;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_view = (Button) findViewById(R.id.btn_view);
        btn_add.setOnClickListener(this);
        btn_view.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_add:
            Intent addintent = new Intent(AndroidAdvanceSqliteActivity.this,
                    AddRecord.class);
            startActivity(addintent);
            break;

        case R.id.btn_view:
            Intent viewintent = new Intent(AndroidAdvanceSqliteActivity.this,
                    ViewRecord.class);
            startActivity(viewintent);
            break;
        default:
            break;
        }

    }
}

Click Code Link:

http://androiddevelopmentworld.blogspot.in/2013/04/android-sqlite-tutorial.html
 

27/07/2013

Splash Sample

package com.muthu.splashscreen;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class MainActivity extends Activity
{
    private static final int SPLASH_TIME = 2 * 1000;// 3 seconds

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try
        {
        new Handler().postDelayed(new Runnable()
        {

            public void run() {
               
                Intent intent = new Intent(MainActivity.this,MainForm.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
           
           
        }, SPLASH_TIME);
       
        new Handler().postDelayed(new Runnable() {
              public void run() {
                     }
                }, SPLASH_TIME);
        } catch(Exception e){}
    }

   
    @Override
    public void onBackPressed()
    {
        this.finish();
        super.onBackPressed();
    }
}

fade_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true">
     <alpha android:fromAlpha="0.0"
            android:toAlpha="1.0"
            android:duration="5000"/> //Time in milliseconds
</set>
fade_out.cml

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true">
     <alpha android:fromAlpha="1.0"
            android:toAlpha="0.0"
            android:duration="5000"/> //Time in milliseconds
</set>

26/07/2013

25/07/2013

Android Simple Json Listview

MainActivity.Java

package com.example.jjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
ListView lv;
final static String INTENT_CATEGORY = "category";
final static String INTENT_CATEG = "category";

public static final String url = "http://products.p41techdev.net/p41insangh/category.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv= (ListView)findViewById(R.id.listView1);
        parser s = new parser();
        s.execute(url);
       
       
    }
public class parser extends AsyncTask<String,String,String>
{
    String page;
    private final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute()
    {
        progressDialog.setCancelable(true);
       
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Loading...");
       
        progressDialog.show();
    }
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        String uu = params[0];
        InputStream is;

       
       
        HttpClient ht = new DefaultHttpClient();
        HttpPost hp = new HttpPost(uu);
        try {
            HttpResponse res = ht.execute(hp);
            HttpEntity en = res.getEntity();
            is= en.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder("");
            String line ="";
            while((line = reader.readLine())!=null)
            {
                sb.append(line +"/n");
            }
            is.close();
           
             page=sb.toString(); 

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
        return page;
    }

    @Override
    protected void onPostExecute(String result) {
   
        String val=null;
        super.onPostExecute(result);
        ArrayList<String> obj = new ArrayList<String>();
        try {
            JSONArray jso = new JSONArray(result);
            for(int i =0;i < jso.length();i++)
            {
                JSONObject js = jso.getJSONObject(i);
       
                String OrginalValue=js.getString("category"); 
                 obj.add(OrginalValue);
               
            }
           
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        final ArrayAdapter<String> oo=new ArrayAdapter<String>(MainActivity.this,android.R.layout.activity_list_item,android.R.id.text1,obj);



            lv.setAdapter(oo);
            lv.setOnItemClickListener(new OnItemClickListener()
            {

                @Override
                public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
                   
                Intent i = new Intent(MainActivity.this, Thirdactivity.class);
                String seltext=oo.getItem(position);
                i.putExtra(INTENT_CATEGORY, seltext);
           
                    Toast.makeText(getApplicationContext(), seltext, Toast.LENGTH_LONG).show();
                    startActivity(i);
                   
                }
            });
    }
}
}

SubCategory .Java


package com.example.jjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SubCategory extends Activity
{
    ListView lv ;
     String str1;
    final static String INTENT_CATEGORY = "category";
    final static String INTENT_CATE = "category";
    public static final String url = "http://products.p41techdev.net/p41insangh/category.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.submain);
        lv=(ListView)findViewById(R.id.listView1);
       
   
         parser s = new parser();
            s.execute(url);
           
    }
public  class parser extends AsyncTask<String,String,String>
{
    String page;
   
    @Override
    protected String doInBackground(String... params) {
        String uu = params[0];
        InputStream is;
        HttpClient ht = new DefaultHttpClient();
        HttpPost hp = new HttpPost(uu);
        try {
            HttpResponse res = ht.execute(hp);
            HttpEntity en = res.getEntity();
            is= en.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder("");
            String line ="";
            while((line = reader.readLine())!=null)
            {
                sb.append(line +"/n");
               
               
            }
            is.close();

             page=sb.toString();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return page;
   
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        ArrayList<String> con = new ArrayList<String>();
        try {
            JSONArray jso = new JSONArray(result);
            for(int i =0;i < jso.length();i++)
            {
                JSONObject js = jso.getJSONObject(i);
               
                String OrginalValue=js.getString("category");
                String[] SplitValues=OrginalValue.split("~");
                Intent myLocalIntent = getIntent();
                   Bundle myBundle = myLocalIntent.getExtras();
                   str1 = myBundle.getString(MainActivity.INTENT_CATEGORY);
                 //  Log.d("str1",str1);
                  
                   if(str1.equals(SplitValues[0]))
                     {
                            con.add(SplitValues[1]);
                     }
            }
           
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
   
        final ArrayAdapter<String> oo=new ArrayAdapter<String>(SubCategory.this,android.R.layout.activity_list_item,android.R.id.text1,con);
        lv.setAdapter(oo);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position,
                    long arg3) {
               
                Intent i = new Intent(SubCategory.this,Thirdactivity.class);
                String stext  = oo.getItem(position);
                i.putExtra("sub",stext);
                i.putExtra("category", str1);
                startActivity(i);                    
            }
        });       
    }       
}
}


Thirdactivity .Java

package com.example.jjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class Thirdactivity extends Activity{
ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.third);
        lv = (ListView)findViewById(R.id.listView1);
       
        Intent myLocalIntent = getIntent();
   
          String str1 = (String) myLocalIntent.getExtras().get("category");
         
          str1=str1.replace(" ","%20");
   
          
           String url = "http://products.p41techdev.net/p41insangh/products.php?category="+str1;
          Log.d("Final url",url);
           parser pp = new parser();
           pp.execute(url);
          
    }
    public  class parser extends AsyncTask<String,String,String>
    {
        String page;
       
        @Override
        protected String doInBackground(String...  params) {
            String uu = params[0];
            InputStream is;
            HttpClient ht = new DefaultHttpClient();
            HttpPost hp = new HttpPost(uu);
            try {
                HttpResponse res = ht.execute(hp);
                HttpEntity en = res.getEntity();
                is= en.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder("");
                String line ="";
                while((line = reader.readLine())!=null)
                {
                    sb.append(line +"/n");
                }
                is.close();

                 page=sb.toString();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return page;
        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            ArrayList<ItemDTO> obj = new ArrayList<ItemDTO>();
            try {
                JSONArray jars = new JSONArray(result);
                for(int i=0;i<jars.length();i++)
                {

                JSONObject jso =  jars.getJSONObject(i);
                ItemDTO nn = new ItemDTO();
                nn.setId(jso.getString("id"));
                nn.setTitle(jso.getString("title"));
                //nn.setImgurl(jso.getInt("imgurl"));
                nn.setPrice(jso.getString("price"));
                obj.add(nn);
                Log.d("Array[]", obj.toString());
               
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
       
            ListBaseAdapter adapter = new ListBaseAdapter(obj,getLayoutInflater());

            lv.setAdapter(adapter);

        }        
    }

}


ListBaseAdapter .Java
package com.example.jjson;

import java.util.ArrayList;

import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListBaseAdapter extends BaseAdapter{
    private ArrayList<ItemDTO> list;
    private LayoutInflater inf;
    private Bitmap[]mis_fotos;
   
    public ListBaseAdapter(ArrayList<ItemDTO> obj, LayoutInflater inff) {
        // TODO Auto-generated constructor stub
    this.list=obj;
    this.inf=inff;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent) {
        Holder ho;
        if(v==null)
        {
            ho = new Holder();
            v= inf.inflate(R.layout.thirdsub,null);
            ho.tvid = (TextView)v.findViewById(R.id.textView1);
            ho.tvtitle = (TextView)v.findViewById(R.id.textView2);
            ho.tvprice = (TextView)v.findViewById(R.id.textView3);
            ho.imgg=(ImageView)v.findViewById(R.id.imageView1);
            v.setTag(ho);
           
        }
        else
        {
            ho =(Holder)v.getTag();
           
        }
        ho.tvid.setText(list.get(position).getId());
        ho.tvtitle.setText(list.get(position).getTitle());
        ho.tvprice.setText(list.get(position).getPrice());
        ho.imgg.setImageResource(list.get(position).getImgurl());
        return v;
    }
    public class Holder
    {
        TextView tvid,tvtitle,tvprice;
        ImageView imgg;
    } 

}
 



ItemDTO.Java

package com.example.jjson;


public class ItemDTO
{
    String id,title,price;
    int imgurl;


    public int getImgurl() {
        return imgurl;
    }

    public void setImgurl(int imgurl) {
        this.imgurl = imgurl;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }   

}


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" >

    <RelativeLayout
        android:id="@+id/RelativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </RelativeLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >

    </ListView>

</RelativeLayout>

Adapterlayout:thirdsub.xml

<?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/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

 







21/06/2013

GalleryView With Pinch Zoom

ImageGalleryExample.Java

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class ImageGalleryExample extends Activity implements AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory
{
    static int po;
   
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.gallery);

        mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));

        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setOnItemSelectedListener(this);
    }

    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
        mSwitcher.setImageResource(mImageIds[position]);
        po=position;
    }

    public void onNothingSelected(AdapterView<?> parent) {
    }

    public View makeView() {
        ImageView i = new ImageView(this);
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        i.setOnClickListener(new OnClickListener() {
           
            public void onClick(View position) {
                // TODO Auto-generated method stub
               
                Intent i=new Intent(getApplicationContext(),ZoomView1.class);
                i.putExtra("image", mImageIds[po]);
                startActivity(i);
            }
        });
       // return i;
        return i;
    }

    private ImageSwitcher mSwitcher;

    public class ImageAdapter extends BaseAdapter  {
        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);

            i.setImageResource(mThumbIds[position]);
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            i.setBackgroundResource(R.drawable.page);
         
            return i;
        }

        private Context mContext;

    }

    private Integer[] mThumbIds = {
            R.drawable.sm1,
            R.drawable.sm2,
            R.drawable.sm3, };

    private Integer[] mImageIds = {
              R.drawable.sm1,
              R.drawable.sm2,
              R.drawable.sm3, };

}

gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <ImageSwitcher android:id="@+id/switcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
    />
    
    <Gallery android:id="@+id/gallery"
        android:background="#55000000"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        
        android:gravity="center_vertical"
        android:spacing="16dp"
    />

</RelativeLayout>

anim Folder

fade_in.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/res/anim/fade_in.xml
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@anim/decelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="@android:integer/config_longAnimTime" />

fade_out.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/res/anim/fade_out.xml
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->

<alpha xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@anim/accelerate_interpolator"
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:duration="@android:integer/config_mediumAnimTime"
/>

ZoomView1.Java
package p41.android.sanghamam;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.ImageView;

public class ZoomView1 extends Activity implements OnTouchListener {
    ImageView image;
    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;
    // Remember some things for zooming
        PointF start = new PointF();
        PointF mid = new PointF();
        float oldDist = 1f;
       
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_full_imagezoom);

       
        //Bundle bundle = getIntent().getExtras();
        //String   key = bundle.getString("key"); 
       
       
   
        Intent i = getIntent();

        //Selected image id
        int position = i.getExtras().getInt("image"); 
       
       /* ImageAdapter imageAdapter = new ImageAdapter();
        GalleryAdapter galleryadapter=new GalleryAdapter(this);
        */
        image = (ImageView) findViewById(R.id.myview);
       
        image.setImageResource(position);
       
        //if(views.equals("grid"))
        //{
           
            //image.setImageResource(imageAdapter.mThumbIds[position]);
        //    BitmapFactory.Options  options=new BitmapFactory.Options();
         //   options.inSampleSize=4;
            // Bitmap bitmap=BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() +url);
         //   Bitmap bitmap=BitmapFactory.decodeFile(url);
         //.setImageBitmap(bitmap);
       /* }
        else
        {
           
            BitmapFactory.Options  options=new BitmapFactory.Options();
            options.inSampleSize=4;
             Bitmap bitmap=BitmapFactory.decodeFile( url);
             image.setImageBitmap(bitmap);
       
        }
         */
       
        image.setOnTouchListener(this);
    }

    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
       
        ImageView view = (ImageView) v;

        // Handle touch events here...
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());

            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            oldDist = spacing(event);

            if (oldDist > 10f) {
                savedMatrix.set(matrix);
                midPoint(mid, event);
                mode = ZOOM;
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;

            break;
        case MotionEvent.ACTION_MOVE:
            if (mode == DRAG) {
                System.out.println("Moving");
                matrix.set(savedMatrix);
                matrix.postTranslate(event.getX() - start.x, event.getY()
                        - start.y);
            } else if (mode == ZOOM) {
                float newDist = spacing(event);

                if (newDist > 10f) {
                    matrix.set(savedMatrix);
                    float scale = newDist / oldDist;
                    matrix.postScale(scale, scale, mid.x, mid.y);
                }
            }
            break;
        }

        view.setImageMatrix(matrix);
       
        return true; // indicate event was handled
    }

    /** Determine the space between the first two fingers */
   
    @SuppressLint("NewApi")
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }

    /** Calculate the mid point of the first two fingers */
    @SuppressLint("NewApi")
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }
   
}




18/06/2013

Android Using Database Inset,Delete,View

Layout:

create_layout.xml :

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Register Student...."
            android:layout_marginLeft="60dp"
            android:layout_marginTop="20dp"
            android:textSize="@dimen/wel_admin"
            />
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

    <TextView
            android:id="@+id/t1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stud id: "
            android:layout_marginLeft="20dp"
            android:layout_marginTop="40dp"
            android:textSize="@dimen/form_ele"/>
    <EditText
        android:id="@+id/accid"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_marginTop="40dp"
        android:layout_toRightOf="@id/t1"
        android:layout_marginLeft="30dp"/>
    </RelativeLayout>

    <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

        <TextView
                android:id="@+id/t2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Name: "
                android:layout_marginLeft="20dp"
                android:layout_marginTop="40dp"
                android:textSize="@dimen/form_ele"/>
        <EditText
                android:id="@+id/name"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:layout_marginTop="40dp"
                android:layout_toRightOf="@id/t2"
                android:layout_marginLeft="10dp"/>
    </RelativeLayout>

    <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

        <TextView
                android:id="@+id/t3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Class: "
                android:layout_marginLeft="20dp"
                android:layout_marginTop="40dp"
                android:textSize="@dimen/form_ele"/>
        <EditText
                android:id="@+id/classes"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:layout_marginTop="40dp"
                android:layout_toRightOf="@id/t3"
                android:layout_marginLeft="60dp"/>
    </RelativeLayout>
    <Button
        android:id="@+id/bCreate"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="130dp"
        android:text="Create"
        android:background="@drawable/admin_design"/>
</LinearLayout>

del_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete Student Id...."
            android:layout_marginLeft="60dp"
            android:layout_marginTop="20dp"
            android:textSize="@dimen/wel_admin"
            />
    <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
        <TextView
                android:id="@+id/d1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stud Id: "
                android:layout_marginLeft="20dp"
                android:layout_marginTop="60dp"
                android:textSize="@dimen/form_ele"/>
        <EditText
                android:id="@+id/acciddel"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:layout_marginTop="60dp"
                android:layout_toRightOf="@id/t1"
                android:layout_marginLeft="110dp"/>
    </RelativeLayout>
    <Button
        android:id="@+id/bdel"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginTop="80dp"
        android:layout_marginLeft="130dp"
        android:text="Delete"
        android:background="@drawable/admin_design"/>
</LinearLayout>

view_layout.xml:

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

Create.Java:

package com.example.databaseproject;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Create extends Activity {
    Button b;
    EditText t1;
    EditText t2;
    EditText t3;
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_layout);
       
        b=(Button)findViewById(R.id.bCreate);
        t1=(EditText)findViewById(R.id.accid);
        t2=(EditText)findViewById(R.id.name);
        t3=(EditText)findViewById(R.id.classes);
       
        final Context context=this;
       
        try
        {
          db=openOrCreateDatabase("student",SQLiteDatabase.CREATE_IF_NECESSARY,null);        
          db.execSQL("CREATE TABLE stud (id integer PRIMARY KEY, name text, Class text)");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
       
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String s=t1.getText().toString();
                String s1=t2.getText().toString();
                String s2=t3.getText().toString();

                ContentValues values=new ContentValues();
               
                values.put("id",s);
                values.put("name",s1);
                values.put("Class",s2);
               
                if((db.insert("stud",null,values))!= -1)
                {
                    Toast.makeText(Create.this, "Inserted...", 2000).show();
                }
                else
                {
                    Toast.makeText(Create.this,"Already taken this Id..",2000).show();
                }
                t1.setText("");
                t2.setText("");
                t3.setText("");
                Intent i=new Intent(context,Admin.class);
                startActivity(i);
            }
        });
    }

}
Delete.Java:
package com.example.databaseproject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Del extends Activity
{
    Button b;
    EditText e;
    SQLiteDatabase db;
    SQLiteOpenHelper d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.del_layout);
       

        b=(Button)findViewById(R.id.bdel);
        e=(EditText)findViewById(R.id.acciddel);
       
        final Context context=this;
       
        try
        {
           
            db=openOrCreateDatabase("student",SQLiteDatabase.CREATE_IF_NECESSARY,null);


        }
        catch(SQLiteException e)
        {
          e.printStackTrace();
          System.out.print("ERROR.............");
        }
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                String t=(e.getText().toString());
               
               try
                {
               String d="DELETE FROM stud WHERE id="+t;
               db.execSQL(d);
               String idt="id";
                }
                catch(Exception e)
                {
                   System.out.print("Error..................");
                }              
                e.setText("");
                Toast.makeText(Del.this, "Deleted...", 2000).show();
                Intent i=new Intent(context,Admin.class);
                startActivity(i);

            }
        });
    }

}
View.Java
package com.example.databaseproject;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.widget.TextView;



public class ViewAcc extends Activity
{
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_layout2);
        try
        {

            db=openOrCreateDatabase("student",SQLiteDatabase.CREATE_IF_NECESSARY,null);
            Cursor c= db.rawQuery("SELECT * FROM stud",null);

            TextView v=(TextView)findViewById(R.id.v);
            c.moveToFirst();

            String temp="";
           
            while(! c.isAfterLast())
            {
                String s2=c.getString(0);
                String s3=c.getString(1);
                String s4=c.getString(2);
               
                temp=temp+"\n Id:"+s2+"\tname:"+s3+"\tClass:"+s4;
               
                c.moveToNext();
            }
            v.setText(temp);


        }
        catch(SQLiteException e)
        {

        }
    }

}
Color.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="txt">#FFFFFF</color>
    <color name="bg">#454545</color>
</resources>

Dimens.xml:

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="wel_admin">30dp</dimen>
    <dimen name="form_ele">20dp</dimen>
</resources>

String.xml:

<string name="admin">Admin</string>
    <string name="admintxt">Welcome Admin...</string>