Thursday, May 16, 2013

Android Edit Text With Different shapes


The code for different edit shapes like rounded corner , oval shape etc can be created using shapes attributes

The code for below can be downloaded from here


http://stackoverflow.com/questions/3646415/how-to-create-edittext-with-rounded-corners

http://letustech.wordpress.com/category/android/

Wednesday, May 15, 2013

Android Slide Toggle button

Android Speech Buuble

Android View Pager

Android custom view pager for disabling default switch activity

Step 1.
PageViewActivity.java



import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.util.Log;
import android.view.View;

public class PageViewActivity extends FragmentActivity {
    MyPageAdapter pageAdapter;
    int pageId=0;
    CustomViewPager pager;
    PageListener pageListener;
    int currentPage=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      List<Fragment> fragments = getFragments();
      pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
      pager =(CustomViewPager)findViewById(R.id.viewpager);
      pager.setAdapter(pageAdapter);
      pager.setPagingEnabled(false);
     
      pageListener = new PageListener();
      pager.setOnPageChangeListener(pageListener);
     
    }
   
    private List<Fragment> getFragments(){
     List<Fragment> fList = new ArrayList<Fragment>();
   
     fList.add(MyFragment.newInstance("Fragment 1"));
     fList.add(MyFragment.newInstance("Fragment 2"));
     fList.add(MyFragment.newInstance("Fragment 3"));
     return fList;
    }
   
    public void next(View v){
    if(pageId<=2)
    {
    pager.setCurrentItem(pageId);
    }
    pageId++;
   
    }
   
    private class PageListener extends SimpleOnPageChangeListener{
        public void onPageSelected(int position) {
            Log.i("test", "onPageSelected " + position);
            currentPage = position;
         }
        //Called when the scroll state changes.
        public void onPageScrollStateChanged(int state)
        {
       
        }
       
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
        {
        Log.i("test", "onPageScrolled " + position);
            currentPage = position;
        }
    }
   

  }


Step 2.
MyPageAdapter .java


import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

class MyPageAdapter extends FragmentPagerAdapter {
 private List<Fragment> fragments;

 public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
   super(fm);
   this.fragments = fragments;
 }
 @Override
 public Fragment getItem(int position) {
   return this.fragments.get(position);
 }

 @Override
 public int getCount() {
   return this.fragments.size();
 }
}

Step 3.
MyFragment.java


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";

public static final MyFragment newInstance(String message)
{
  MyFragment f = new MyFragment();
  Bundle bdl = new Bundle(1);
  bdl.putString(EXTRA_MESSAGE, message);
  f.setArguments(bdl);
  return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {
  String message = getArguments().getString(EXTRA_MESSAGE);
  View v = inflater.inflate(R.layout.myfragment_layout, container, false);
  TextView messageTextView = (TextView)v.findViewById(R.id.textView);
  messageTextView.setText(message);

  return v;
}
}

Step 4.
CustomViewPager.java


import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class CustomViewPager extends android.support.v4.view.ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
         super(context, attrs);
         this.enabled = true;
    }

@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
        return super.onTouchEvent(event);
}

return false;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.enabled) {
                return super.onInterceptTouchEvent(event);
        }

        return false;
}

/**
 * Custom implementation to enable or not swipe :)
 *
 * @param enabled
 *            true to enable swipe, false otherwise.
 */
public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
}

}

Step 5.
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" >

   <com.example.viewpagerdemo.CustomViewPager
     android:id="@+id/viewpager"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent" />

</RelativeLayout>

Step 6.
myfragment_layout.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"
  android:orientation="vertical" >
  <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    />
  <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Next"
      android:onClick="next"
      />

</RelativeLayout>

http://architects.dzone.com/articles/android-tutorial-using
http://blog.evoxmusic.fr/content/android-how-disable-viewpager-page-switch

Android GSON parsing


Step 1.
Download the Gson library from http://code.google.com/p/google-gson/ and add it to your java build path in eclipse.

Step 2.
Create a php file and paste the following json data into it

{"as_of":"Thu, 25 Feb 2010 11:30:17 +0000","trends"
:[{"name":"#nowplaying",
"url":"http://search.twitter.com/search?q=%23nowplaying"}
,{"name":"#nothingworsethan",
"url":"http://search.twitter.com/search?q=%23nothingworsethan"},
{"name":"Dubai Mall",
"url":"http://search.twitter.com/search?q=%22Dubai+Mall%22"},
{"name":"iPad Gets",
"url":"http://search.twitter.com/search?q=%22iPad+Gets%22"},
{"name":"#SuperJuniorTrot",
"url":"http://search.twitter.com/search?q=%23SuperJuniorTrot"},
{"name":"Justin Bieber",
"url":"http://search.twitter.com/search?q=%22Justin+Bieber%22"},
{"name":"Click",
"url":"http://search.twitter.com/search?q=Click"},
{"name":"Jaebum",
"url":"http://search.twitter.com/search?q=Jaebum"},
{"name":"#tosavemoney",
"url":"http://search.twitter.com/search?q=%23tosavemoney"},
{"name":"Protection",
"url":"http://search.twitter.com/search?q=Protection"}]}

Step 3.
Create the following two classes to hold the information of the json data

TwitterTrend .java

public class TwitterTrend {
    public String name;
    public String url;
}

TwitterTrends .java

public class TwitterTrends {

    public String as_of;
    public List<TwitterTrend> trends;
    
    public String getAs_Of() {
        return as_of;
    }
    public void setAs_Of(String asOf) {
        as_of = asOf;
    }
    public List<TwitterTrend> getTrends() {
        return trends;
    }
    public void setTrends(List<TwitterTrend> trends) {
        this.trends = trends;
    }
   
}

Step 4. create the main activity 
MainActivity.java


public class MainActivity extends Activity {

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



public InputStream getJSONData(String url){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri;
        InputStream data = null;
        try {
            uri = new URI(url);
            HttpGet method = new HttpGet(uri);
            HttpResponse response = httpClient.execute(method);
            data = response.getEntity().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return data;
    }

public void runJSONParser(){
        try{
        Log.i("MY INFO", "Json Parser started..");
        Gson gson = new Gson();
        Reader r = new InputStreamReader(getJSONData("http://10.0.2.2/gsonTest/index.php"));
        Log.e("MY INFO", r.toString());
        TwitterTrends objs = gson.fromJson(r, TwitterTrends.class);
        Log.e("MY INFO", ""+objs.getTrends().size());
        for(TwitterTrend tr : objs.getTrends()){
            Log.e("TRENDS", tr.name + " - " + tr.url);
        }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

}

step 5.
Add the following lines into the xml file
 <uses-permission android:name="android.permission.INTERNET" /> 

Step 6.
run the app , u will see the following log


05-15 22:01:54.623: I/MY INFO(1796): Json Parser started..
05-15 22:01:54.733: E/MY INFO(1796): java.io.InputStreamReader@43e55058
05-15 22:01:54.773: E/MY INFO(1796): 10
05-15 22:01:54.773: E/TRENDS(1796): #nowplaying - http://search.twitter.com/search?q=%23nowplaying
05-15 22:01:54.773: E/TRENDS(1796): #nothingworsethan - http://search.twitter.com/search?q=%23nothingworsethan
05-15 22:01:54.773: E/TRENDS(1796): Dubai Mall - http://search.twitter.com/search?q=%22Dubai+Mall%22
05-15 22:01:54.773: E/TRENDS(1796): iPad Gets - http://search.twitter.com/search?q=%22iPad+Gets%22
05-15 22:01:54.773: E/TRENDS(1796): #SuperJuniorTrot - http://search.twitter.com/search?q=%23SuperJuniorTrot
05-15 22:01:54.773: E/TRENDS(1796): Justin Bieber - http://search.twitter.com/search?q=%22Justin+Bieber%22
05-15 22:01:54.773: E/TRENDS(1796): Click - http://search.twitter.com/search?q=Click
05-15 22:01:54.773: E/TRENDS(1796): Jaebum - http://search.twitter.com/search?q=Jaebum
05-15 22:01:54.773: E/TRENDS(1796): #tosavemoney - http://search.twitter.com/search?q=%23tosavemoney
05-15 22:01:54.773: E/TRENDS(1796): Protection - http://search.twitter.com/search?q=Protection

http://www.softwarepassion.com/android-series-parsing-json-data-with-gson/

Sunday, May 12, 2013

Send Xml Data From Android to PHP server


package com.example.sendxmltest;

import java.io.IOException;

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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost("http://10.0.2.2/server_log/index.php");

   try {
       StringEntity se = new StringEntity( "<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8);
       se.setContentType("text/xml");
       httppost.setEntity(se);

       HttpResponse httpresponse = httpclient.execute(httppost);
       HttpEntity resEntity = httpresponse.getEntity();
       Log.e("test",EntityUtils.toString(resEntity));
       //tvData.setText(EntityUtils.toString(resEntity));

   } catch (ClientProtocolException e) {
       // TODO Auto-generated catch block
    Log.e("test",e.getMessage());
       e.printStackTrace();
   } catch (IOException e) {
       // TODO Auto-generated catch block
    Log.e("test",e.getMessage());
    e.printStackTrace();
   }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


PHP code to receive xml data 

<?php
  /*
   * XML Server.
   */
  // We use php://input to get the raw $_POST results.
  $xml_post = file_get_contents('php://input');
  // If we receive data, save it.
  if ($xml_post) {
    $xml_file = 'received_xml_' . date('Y_m_d-H-i-s') . '.xml';
    $fh       = fopen($xml_file, 'w') or die();
    fwrite($fh, $xml_post);
    fclose($fh);
    // Return, as we don't want to cause a loop by processing the code below.
echo "data xml --".$xml_post;
  }
 // print_r($_SERVER);
  
  return;
?>


Saturday, May 4, 2013

Android CutomArrayAdapter with CheckBox

Contact.java


package com.example.testandroid;

public class Contact {
    public String name;
    public String phone;
    public Boolean selected;
    public Contact()
    {
   
    }
    public Contact(String name,String phone){
    this.name=name;
    this.phone=phone;
    this.selected=false;
    }
}

ContactsAdapter.java


package com.example.testandroid;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class ContactsAdapter extends ArrayAdapter<Contact>{

    Context context;
    int layoutResourceId,temp;  
    ArrayList<Contact> data;
   
    public ContactsAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ContactHolder holder = null;
        Contact contact = data.get(position);
        final int pos=position;
        temp=position;
        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
           
            holder = new ContactHolder();
            holder.name = (TextView)row.findViewById(R.id.name);
            holder.phone = (TextView)row.findViewById(R.id.mobile);
            holder.chkBox = (CheckBox)row.findViewById(R.id.chk_sel);
            holder.chkBox.setOnClickListener( new View.OnClickListener() {
                public void onClick(View v) {
                 CheckBox cb = (CheckBox) v ;
                 //Contact contact = (Contact) cb.getTag();
                 Toast.makeText(context,"Clicked on Checkbox: " + data.get(pos).name +" is " + cb.isChecked(),Toast.LENGTH_LONG).show();
                 data.get(pos).selected=cb.isChecked();
                 }
               });
            row.setTag(holder);
        }
        else
        {
            holder = (ContactHolder)row.getTag();
        }
       
       
        holder.name.setText(contact.name);
        holder.phone.setText(contact.phone);
       
        return row;
    }
   
    static class ContactHolder
    {
    TextView name;
        TextView phone;
        CheckBox chkBox;
    }
}

MainActivity.java


package com.example.testandroid;

import java.util.ArrayList;
import java.util.ListIterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    ArrayList<Contact> mContacts;
    ListView listView1;
    ContactsAdapter adapter;
    String mAction;
    ListIterator<Contact> litr ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContacts=new ArrayList<Contact>();

for(int i=0;i<10;i++)
{
Contact c=new Contact("name"+i,"9748544"+i);
mContacts.add(c);
}

adapter = new ContactsAdapter(this,R.layout.container, mContacts);
               
        listView1 = (ListView)findViewById(R.id.lisstview);
     
        listView1.setAdapter(adapter);
}

// Initiating Menu XML file (menu.xml)
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menu, menu);
        return true;
    }
   
    public void add_edit_dialog(String title,String action){
    mAction=action;
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.add_edit_dialog, null);
        Dialog d= new AlertDialog.Builder(MainActivity.this)
            .setTitle(title)
            .setView(textEntryView)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                String name,phoneno;
                EditText et_name,et_phone;
                et_name=(EditText)textEntryView.findViewById(R.id.name_edit);
                et_phone=(EditText)textEntryView.findViewById(R.id.mobile_edit);
                name=et_name.getText().toString();
                phoneno=et_phone.getText().toString();
                if(mAction.equals("add"))
                {
                Contact c=new Contact(name,phoneno);
                mContacts.add(c);
                listView1.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                }
                else if(mAction.equals("edit"))
                {
                Toast.makeText(getApplicationContext(), "mae="+name, Toast.LENGTH_LONG).show();
                litr = mContacts.listIterator();
                while (litr.hasNext()) {
                Contact element = litr.next();
                         if(element.selected==true)
                      {
                          element.name=name;
                          element.phone=phoneno;
                      }
                Log.e("test","name is "+element.name);
               
                }
                listView1.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                }
                    /* User clicked OK so do some stuff */
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked cancel so do some stuff */
                }
            })
            .create();
        d.show();
    }
   
    /**
     * Event Handling for Individual menu item selected
     * Identify single menu item by it's id
     * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
       
        switch (item.getItemId())
        {
        case R.id.menu_add:
            // Single menu item is selected do something
            // Ex: launching new activity/screen or show alert message
            Toast.makeText(MainActivity.this, "Add is Selected", Toast.LENGTH_SHORT).show();
            add_edit_dialog("Add Contact","add");
            return true;

        case R.id.menu_edit:
            Toast.makeText(MainActivity.this, "Edit is Selected", Toast.LENGTH_SHORT).show();
            add_edit_dialog("Edit Contact","edit");
            return true;

        case R.id.menu_del:
            Toast.makeText(MainActivity.this, "del is Selected", Toast.LENGTH_SHORT).show();
            litr = mContacts.listIterator();
            while (litr.hasNext()) {
           Contact element = litr.next();
           if(element.selected==true)
        {
            litr.remove();
        }
         
            }
            /* for(int i=0;i<mContacts.size();i++)
            {
            if(mContacts.get(i).selected==true)
            {
            mContacts.remove(i);
            }
            }*/
            listView1.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }  

}


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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/lisstview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
         />

</RelativeLayout>

add_edit_dialog.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="wrap_content"
    android:orientation="vertical">

    <TextView 
        android:id="@+id/name_view"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:text="Name"
        android:gravity="left"
        android:textAppearance="?android:attr/textAppearanceMedium" />
            
    <EditText
        android:id="@+id/name_edit"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:scrollHorizontally="true"
        android:autoText="false"
        android:capitalize="none"
        android:gravity="fill_horizontal"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/mobile_view"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:text="Mobile no"
        android:gravity="left"
        android:textAppearance="?android:attr/textAppearanceMedium" />
            
    <EditText
        android:id="@+id/mobile_edit"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:scrollHorizontally="true"
        android:autoText="false"
        android:capitalize="none"
        android:gravity="fill_horizontal"
        android:password="true"
        android:textAppearance="?android:attr/textAppearanceMedium" />
        
</LinearLayout>

container.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:weightSum="4"
    android:layout_height="match_parent">
<LinearLayout
   android:layout_height="wrap_content"
   android:layout_width="0dp"
   android:orientation="vertical"
   android:layout_weight="3">
   <TextView
       android:id="@+id/name"
       android:text="Name"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </TextView>
   <TextView
       android:paddingLeft="10dp"
       android:id="@+id/mobile"
       android:text="Mobile"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </TextView>
    </LinearLayout>
    <LinearLayout
   android:layout_height="wrap_content"
   android:layout_width="0dp"
   android:gravity="center"
   android:layout_weight="1">
   <CheckBox
        android:id="@+id/chk_sel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />
    </LinearLayout>

    

</LinearLayout>


menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_add"
          android:title="Add" />
 
    <item android:id="@+id/menu_del"
          android:title="Delete" />
 
    <item android:id="@+id/menu_edit"
          android:title="Edit" />
   
</menu>