Tuesday, 10 December 2013

Add reminder to default Calender from our Application

MainActivity.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * To display the given data as notification at particular date and time
 *
 * @author Harshal Kalavadiya
 */

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

    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;
    static final int DATE_DIALOG_ID = 1;
    static final int TIME_DIALOG_ID = 0;
    private Calendar c;  
    private EditText nameEdit;
    private EditText descEdit;
    private Context mContext;  
    private boolean dateFlag = false;
    private boolean timeFlag = false;
    private String time;
    private String contentTitle;
    private String contentText;
    public static int notificationCount;
    public Button dateButton;
    public Button timeButton;
    public Button reminButton;
    public TextListener textListener;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        mContext = this;
        textListener = new TextListener();
        dateButton= (Button)findViewById(R.id.dateButton);
        timeButton= (Button)findViewById(R.id.timeButton);
        reminButton= (Button)findViewById(R.id.reminderButton);
        dateButton.setEnabled(false);
  timeButton.setEnabled(false);
  reminButton.setEnabled(false);
        nameEdit = (EditText)findViewById(R.id.nameEditText);
        nameEdit.addTextChangedListener(textListener);
        descEdit = (EditText)findViewById(R.id.DescEditText);
        descEdit.addTextChangedListener(textListener);  
        c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
    }
 
    public class TextListener implements TextWatcher{

   @Override
  public void afterTextChanged(Editable s) {
   // TODO Auto-generated method stub
  }

   @Override
  public void beforeTextChanged(CharSequence s, int start, int count,
    int after) {
   // TODO Auto-generated method stub
  }

   @Override
  public void onTextChanged(CharSequence s, int start, int before,
    int count) {
   // TODO Auto-generated method stub
   if(descEdit.getText().length()==0 | nameEdit.getText().length()==0){
    dateButton.setEnabled(false);
    timeButton.setEnabled(false);
    reminButton.setEnabled(false);
   }
   else if(descEdit.getText().length()>0 & nameEdit.getText().length()>0){
    dateButton.setEnabled(true);
    timeButton.setEnabled(true);
    reminButton.setEnabled(true);
   }
  }  
    }
 
    public void onReminderClicked(View view){      
     if(dateFlag & timeFlag == true){
      notificationCount  = notificationCount+1;
      dateFlag = false;
      timeFlag = false;
      time = mYear+"-"+mMonth+"-"+mDay+" "+mHour+"-"+mMinute;                              
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh-mm");
            Date dt = null;
   try {
    dt = df.parse(time);
   } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }                                      
            long when = dt.getTime();              
            contentTitle = nameEdit.getText().toString();
            contentText = descEdit.getText().toString();      
         AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
         Intent notificationIntent = new Intent(mContext, ReminderAlarm.class);
         notificationIntent.putExtra("Name",contentTitle );
            notificationIntent.putExtra("Description",contentText );
            notificationIntent.putExtra("NotifyCount",notificationCount );
         PendingIntent pi = PendingIntent.getBroadcast(mContext, notificationCount, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
         mgr.set(AlarmManager.RTC_WAKEUP,when, pi);
         Toast.makeText(mContext, "Your Reminder Activated", Toast.LENGTH_LONG).show();
            contentTitle = "";
         contentText = "";
         descEdit.setText("");
         nameEdit.setText("");
     }
     else if(dateFlag == false | timeFlag == false){
      Toast.makeText(mContext, "Please choose Date & Time", Toast.LENGTH_SHORT).show();
     }
    }
 
    public void onTimeClicked(View view){  
     showDialog(TIME_DIALOG_ID);
    }
    public void onDateClicked(View view){  
     showDialog(DATE_DIALOG_ID);  
    }
 
    @Override
    protected Dialog onCreateDialog(int id) {
     // TODO Auto-generated method stub
     switch (id) {
      case TIME_DIALOG_ID:
         return new TimePickerDialog(this,
              mTimeSetListener, mHour, mMinute, false);
      case DATE_DIALOG_ID:
          return new DatePickerDialog(this,
                      mDateSetListener,
                      mYear, mMonth, mDay);
      }
     return super.onCreateDialog(id);
    }
 
    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear+1;
                mDay = dayOfMonth;              
                dateFlag = true;
            }
    };
     
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                timeFlag = true;
            }
    };

}

ReminderAlarm.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Trigger Status bar Notification alert at particular date and time
 *
 * @author Kumaresan Palanisamy
 */
public class ReminderAlarm  extends BroadcastReceiver{
 private NotificationManager mNotificationManager;
 private Notification notification;

  @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub    
      mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      CharSequence from = intent.getStringExtra("Name");
      CharSequence message = intent.getStringExtra("Description");
      PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
      notification = new Notification(R.drawable.ic_launcher,"Notification", System.currentTimeMillis());
      notification.setLatestEventInfo(context, from, message, contentIntent);
      mNotificationManager.notify(Integer.parseInt(intent.getExtras().get("NotifyCount").toString()), notification);      
      Toast.makeText(context, "New Notification Received", Toast.LENGTH_LONG).show();
 }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"    
     >
 <LinearLayout    
     android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/nameLayout">
      <TextView
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="@string/Name"/>  
      <EditText
          android:id="@+id/nameEditText"
          android:hint="Enter Name "              
          android:layout_height="45dp"        
          android:layout_width="200dp" />  
    </LinearLayout>  
 <LinearLayout  
     android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/descLayout"
       android:layout_below="@id/nameLayout">
      <TextView
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="@string/Desc"/>  
      <EditText
          android:id="@+id/DescEditText"
          android:hint="Enter Description"          
          android:layout_height="45dp"        
          android:layout_width="200dp" />  
    </LinearLayout>    
 <LinearLayout
     android:layout_marginTop="20dp"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal"
     android:layout_below="@id/descLayout"  
     android:gravity="center_horizontal"
     >  
  <Button
      android:id="@+id/dateButton"
      android:layout_width="100sp"
      android:layout_height="wrap_content"
      android:text="@string/Date"
      android:onClick="@string/DateClick"
      />
     <Button
         android:id="@+id/timeButton"
      android:layout_width="100sp"
       android:layout_height="wrap_content"
      android:text="@string/Time"
      android:onClick="@string/Timeclick"/>
     <Button
         android:id="@+id/reminderButton"
      android:layout_width="100sp"
      android:layout_height="wrap_content"
      android:text="@string/Reminder"
      android:onClick="@string/ReminderClick"/>
 </LinearLayout>

</RelativeLayout>

Friday, 6 December 2013

Gridview inside ScrollView in android

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;

public class NestedGridView extends GridView {
boolean expanded = true;
public NestedGridView(Context context) {
super(context);
}
public NestedGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NestedGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// HACK! TAKE THAT ANDROID!
if (isExpanded()) {
// Calculate entire height by providing a very large height hint.
// View.MEASURED_SIZE_MASK represents the largest height possible.
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setIsExpanded(boolean expanded) {
this.expanded = expanded;
}

}

Thursday, 5 December 2013

Custom Gridview With Checkbox in Android

public class Check extends Activity {
     
//    List <String> ImageList;
    ArrayList<ParserCategory>mList;
    DatabaseConnectionAPI mApi;
    ImageAdapter mAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        /*** Get Images from SDCard ***/
//        ImageList = getSD();
       
        // gridView1
        mApi=new DatabaseConnectionAPI(getApplicationContext());
        try {
            mApi.createDataBase();
              mApi.openDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     
        mList=mApi.getCategoryData();
        final GridView gView1 = (GridView)findViewById(R.id.gridView1);
           
        mAdapter=new ImageAdapter(Check.this, mList);
        gView1.setAdapter(mAdapter);
       

        // Check All
        Button btnCheckAll = (Button) findViewById(R.id.btnCheckAll);
        btnCheckAll.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                int count = gView1.getAdapter().getCount();
                for (int i = 0; i < count; i++) {
                    LinearLayout itemLayout = (LinearLayout)gView1.getChildAt(i); // Find by under LinearLayout
                    CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
                    checkbox.setChecked(true);
                } 
            }
        });
       
        // Clear All
        Button btnClearAll = (Button) findViewById(R.id.btnClearAll);
        btnClearAll.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                int count = gView1.getAdapter().getCount();
                for (int i = 0; i < count; i++) {
                    LinearLayout itemLayout = (LinearLayout)gView1.getChildAt(i); // Find by under LinearLayout
                    CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
                    checkbox.setChecked(false);
                } 
            }
        });
       
        // Get Item Checked
        Button btnGetItem = (Button) findViewById(R.id.btnGetItem);
        btnGetItem.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
//                int count = gView1.getAdapter().getCount();
                int count =  gView1.getChildCount();

                System.out.println("Count "+count);
                for (int i = 0; i < count; i++) {
                    ViewGroup gridChild = (ViewGroup) gView1.getChildAt(i);
//                    LinearLayout itemLayout = (LinearLayout)gView1.getChildAt(i); // Find by under LinearLayout
//                    System.out.println("itemLayout "+itemLayout);
                    CheckBox checkbox = (CheckBox)gridChild.findViewById(R.id.checkBox1);
                    if(checkbox.isChecked())
                    {
                        Log.d("Item "+String.valueOf(i), checkbox.getTag().toString());
                        System.out.println("ITEEMERM  "+String.valueOf(i)+checkbox.getTag().toString());
                        Toast.makeText(Check.this,checkbox.getTag().toString() ,2000).show(); 
                    }
                } 
            }
        });
     
    }

//    private List <String> getSD()
//    {
//        List <String> it = new ArrayList <String>();
//        File f = new File ("/mnt/sdcard/picture");
//        File[] files = f.listFiles ();
//       
//        for (int i = 0; i <files.length; i++)
//        {
//            File  file = files[i];
//            Log.d("Count",file.getPath());
//            it.add (file.getPath());
//        }
//        return it;
//    }
   
    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<ParserCategory> lis;
       
        public ImageAdapter(Context c, ArrayList<ParserCategory> mList)
        {
            //
            context = c;
            lis = mList;
        }

        public int getCount() {
            //
            return lis.size();
        }

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

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

        public View getView(int position, View convertView, ViewGroup parent) {
            //
           
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
       
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.showimage, null);
                }
               
                TextView textView = (TextView) convertView.findViewById(R.id.textView1);
                String strPath = lis.get(position).toString();
               
                // Get File Name
                String fileName=lis.get(position).getCname();
//                String fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length() );
                textView.setText(lis.get(position).getCname());
               
                // Image Resource
                ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
                // CheckBox
                CheckBox Chkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
                Chkbox.setTag(fileName);
       
                return convertView;
               
        }
    }
   
   

}

Custom Gridview with Multiple radiobutton with Single Selection in Android

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

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_height="wrap_content"
         />

    <TextView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/radioButton1"
         />

</RelativeLayout>





MainActivity.Java

 package com.example.china;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Adapter gAdapter;
    private GridView gBankLogo;
    private int lastPosition = -1;
    private View lastView;
  
    ArrayList<ParserCategory>mList;
    DatabaseConnectionAPI mApi;
    Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gBankLogo = (GridView)findViewById(R.id.gridView1);
        mButton=(Button)findViewById(R.id.btn);
        mButton.setOnClickListener(new View.OnClickListener() {
          
            @Override
            public void onClick(View v) {
              
                int count =  gBankLogo.getChildCount();

                System.out.println("Count "+count);
                for (int i = 0; i < count; i++) {
                    ViewGroup gridChild = (ViewGroup) gBankLogo.getChildAt(i);
                    RadioButton checkbox = (RadioButton)gridChild.findViewById(R.id.radioButton1);
                    if(checkbox.isChecked())
                    {
                        Log.d("Item "+String.valueOf(i), checkbox.getTag().toString());
                        System.out.println("ITEEMERM  "+String.valueOf(i)+checkbox.getTag().toString());
                        Toast.makeText(MainActivity.this,checkbox.getTag().toString() ,2000).show();
                    }
                }
            }
        });
        mApi=new DatabaseConnectionAPI(getApplicationContext());
        try {
            mApi.createDataBase();
              mApi.openDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        mList=mApi.getCategoryData();
      
      
        gAdapter = new Adapter(this,mList);
      //TEST
        for (int i = 0; i < mList.size(); i++) {
             String bank = "";
             gAdapter.addObject("bank"+i, bank);
        }    
        gBankLogo.setAdapter(gAdapter);
        gBankLogo.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (lastPosition == position)
                    return;
                if (lastPosition != position) {
                    if (lastPosition == -1) {
                        RadioButton tmp = (RadioButton) view.findViewById(R.id.radioButton1);
                        tmp.setChecked(true);
                        lastView = view;
                        lastPosition = position;
                    } else {
                        RadioButton tmp = (RadioButton) view.findViewById(R.id.radioButton1);
                        tmp.setChecked(true);
                        RadioButton tmp1 = (RadioButton) lastView.findViewById(R.id.radioButton1);
                        tmp1.setChecked(false);
                        lastView = view;
                        lastPosition = position;
                    }
                }
            }
        });     
    }
}
 Adapter.Java
 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;

public class Adapter extends BaseAdapter {
    private ViewHolder holder;
    private LayoutInflater mLayoutInflater;
    private static Map<String, Object> M = new HashMap<String, Object>();
    private static List<String> L = new ArrayList<String>();
    ArrayList<ParserCategory>mList;
    Activity mActivity;  
    public Adapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);

    }

    public Adapter(MainActivity mainActivity, ArrayList<ParserCategory> mList) {
        // TODO Auto-generated constructor stub
        mActivity=mainActivity;
        this.mList=mList;
    }

    public void addObject(String key, String bank) {
        if (!L.contains(key)) {
            L.add(key);
        }
        M.put(key, bank);
        this.notifyDataSetChanged();
    }

    public void removeObject(String key) {
        M.remove(key);
        L.remove(key);
        this.notifyDataSetChanged();
    }

    public void removeAllObject() {
        if (getCount() != 0) {
            M.clear();
            L.clear();
            this.notifyDataSetChanged();
        }
    }

    public void removeAllSelect() {
        if (getCount() != 0) {
            holder.rSelect.setChecked(false);
            this.notifyDataSetChanged();
        }
    }

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

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

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (convertView == null) {
            holder = new ViewHolder();
          
            LayoutInflater inflater = (LayoutInflater) mActivity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        
        
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.item_msgbanklogo, null);
                }
//            convertView = mLayoutInflater.inflate(R.layout.item_msgbanklogo,null);
            holder.mTextView = (TextView) convertView
                    .findViewById(R.id.imageView1);
            holder.rSelect = (RadioButton) convertView
                    .findViewById(R.id.radioButton1);
            holder.mTextView.setText(mList.get(position).getCname());
             holder.rSelect.setTag(mList.get(position).getCname());
            holder.mTextView.setClickable(false);
            holder.rSelect.setClickable(false);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        return convertView;
    }
}
 ViewHolder.java

public class ViewHolder {
    TextView mTextView;
    RadioButton rSelect;
}





Monday, 9 September 2013

ScrollView Inside Another Scrollview in Android

Layout File 

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

    <ScrollView
        android:id="@+id/activity_main_parent_scroll"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:focusableInTouchMode="true" >

        <LinearLayout
            android:id="@+id/activity_main_linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <ScrollView
                android:id="@+id/activity_main_child_scroll"
                android:layout_width="fill_parent"
                android:layout_height="@dimen/widthsize100"
                android:focusable="true"
                android:focusableInTouchMode="true" >

                <TextView
                    android:id="@+id/activity_main_activity_main_text_description"
                    style="@style/Textview" />
            </ScrollView>

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_3"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_4"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_5"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_6"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_7"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_8"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_9"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_10"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_11"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_12"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_13"
                style="@style/Textview"
                 />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_14"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_15"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_16"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_17"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_18"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_19"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_20"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_21"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_22"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_23"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_24"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_25"
                style="@style/Textview" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

style.xml

<style name="Textview">
        <item  name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:scrollbars">vertical</item>
        <item name="android:text">@string/text</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">@dimen/textsize12</item>
        <item name="android:padding">@dimen/padding5</item>
        </style>

string.xml

    <string  name="text">sdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfh</string>

dimen.xml

    <dimen name="textsize12">12dip</dimen>
    <dimen name="padding5">5dip</dimen>
    <dimen name="widthsize100">100dp</dimen>



MainActivity.java


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

public class MainActivity extends Activity {
   
    ScrollView mScrollViewParent;
    ScrollView mScrollViewChild;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScrollViewParent=(ScrollView)findViewById(R.id.activity_main_parent_scroll);
        mScrollViewChild=(ScrollView)findViewById(R.id.activity_main_child_scroll);
       
        mScrollViewParent.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                Log.v("A","PARENT TOUCH");
//             findViewById(R.id.child_scroll).getParent().requestDisallowInterceptTouchEvent(false);
                mScrollViewParent.getParent().requestDisallowInterceptTouchEvent(false);
                return false;
            }
        });
        mScrollViewChild.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event)
            {
                Log.v("B","CHILD TOUCH");
               // Disallow the touch request for parent scroll on touch of child view
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
    }

    @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;
    }

}

Saturday, 22 June 2013

Localization Example in Android

LocalActivity.java
package com.local;

import java.util.Locale;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class LocalActivity extends Activity {
    /** Called when the activity is first created. */
Button mButton;
TextView mTextView;
String language ="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mButton=(Button)findViewById(R.id.button);
        mTextView=(TextView)findViewById(R.id.txt);
     
        mButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

       Locale locale = null;
       if (language.equalsIgnoreCase("en")) {
           locale = new Locale("en");
       } else if (language.equalsIgnoreCase("es")) {
           locale = new Locale("es");
       }
       Locale.setDefault(locale);
       Configuration config = new Configuration();
       config.locale = locale;
       getBaseContext().getResources().updateConfiguration(config, null);
       mTextView.setText(getString(R.string.app_name));
//        mButton.setText(getString(R.string.app_name));
}
});
       
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu , menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.english:
            language="en";
              break;
              case R.id.spanish:
             language="es";
             break;
        default:
              return super.onOptionsItemSelected(item);
        }
        return true;
}
}
In values folder string.xml
string.xml files
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Application Name</string>
</resources>
-----------------------------------------------------------------
in values-es folder string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, LocalActivity!</string>
    <string name="app_name">nombre de la aplicación</string>
</resources>

in Device select menu option for change language.



Saturday, 25 May 2013

Database Connection in Android


package com.android.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseConnectionAPI extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private final static String DB_PATH = "/data/data/com.android.database/databases/";

private final static String DB_NAME = "demo.sqlite";

private final Context myContext;

private static SQLiteDatabase db;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DatabaseConnectionAPI(Context context)
{

super(context, DB_NAME, null, 1);
this.myContext = context;
}

/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException
{

boolean dbExist = checkDataBase();

if(dbExist)
{
//do nothing - database already exist
}
else
{

//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();

try
{
copyDataBase();
}
catch (IOException e)
{

throw new Error("Error copying database");
}
}
}

/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){

SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{

//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[2048];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

public void openDataBase() throws SQLException{
try
{
db.close();
}
catch(Exception e)
{
System.out.println("no database connected to close");
}
//Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}

@Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
/**
* Use this function to set the value of a particular column
*
* @param columnName The column name whose value is to be changed
* @param newColumnValue The value to be replaced in the column
* @param whereColumnName The column name to be compared with the where clause
* @param whereColumnValue The value to be compared in the where clause
*/
void onUpdateSet(String columnName, String newColumnValue, String[] whereColumnName, String[] whereColumnValue){
String expanded_ColumnNames = new String(whereColumnName[0]);
String expanded_ColumnValues = new String(whereColumnValue[0]);
for(int i=1;i {
expanded_ColumnNames = expanded_ColumnNames+","+whereColumnName[i];
expanded_ColumnValues = expanded_ColumnValues+","+whereColumnValue[i];
}
try
{
openDataBase();
db.execSQL("update recipe set \""+columnName+"\" = \""+newColumnValue+"\" where \""+expanded_ColumnNames+"\" = \""+expanded_ColumnValues+"\"");
}
catch(Exception e)
{
System.out.println("Update couldnt complete "+e);
}

}

/**
* Query the given table, returning a Cursor over the result set.
*
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will return all columns,
* which is discouraged to prevent reading data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted
* as an SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they appear
* in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an
* SQL GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the
* cursor, if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause all
* row groups to be included, and is required when row grouping is
* not being used.
* @param orderBy How to order the rows, formatted as an SQL
* ORDER BY clause (excluding the ORDER BY itself). Passing
* null will use the default sort order, which may be unordered.
* @return A Cursor object, which is positioned before the first entry
*/
Cursor onQueryGetCursor(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
{
Cursor query = null;
try
{
openDataBase();
query = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
System.out.println("@@@@@ Query is :"+query);
}
catch(Exception e)
{
System.out.println("Query couldnt complete "+e);
}
return query;
}
/**
* Use this method to search a particular String in the provided field.
*
*
* @param columns The array of columns to be returned
* @param table The table name
* @param whereColumn The where clause specifying a particular columns
* @param keyword The keyword which is to be searched
*
* @return The cursor containing the result of the query
*/
Cursor onSearchGetCursor(String[] columns, String table, String[] whereColumn, String keyword)
{
String expColumns = new String(columns[0]);
Cursor rawquery=null;
for(int i=1;i expColumns = expColumns+","+columns[i];
try
{
openDataBase();
rawquery = db.rawQuery("SELECT "+expColumns+" from "+table+" where "+whereColumn[0]+" like \"%"+keyword+"%\" or "+whereColumn[1]+" like \"%"+keyword+"%\" or "+whereColumn[2]+" like \"%"+keyword+"%\"", null);
}
catch(Exception e)
{
System.out.println("Raw Query couldnt complete "+e);
}
return rawquery;
}
}