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>