Pages

Thursday, April 10, 2014

Contains method in an ArrayList with custom class in android?

In this post, If we use Custom class in ArrayList<> and if want to check item already in ArrayList<> or not using Contain method.

Contain Method generally match all variable of the class See.

Now I write a code for check specific variable value already contain in ArrayList<> or not.
Just we need @Override equale() and hashcode() Method in our custom class. like below.

I have created one custom class name is student. While we call contains Method then check only Student first Name. if we want to check multiple variable then we can add like below in @Override equale() and hashcode() Method.

1. Student.java

public class Student 
{
 private int s_rollNo = 0;
 private String s_fname = "";
 private String s_lname = "";
 private String s_contactNumber = "";
 
 public Student(int rollNo, String firstName, String lastName, String contactNo) 
 {
  this.setS_rollNo(rollNo);
  this.setS_fname(firstName);
  this.setS_lname(lastName);
  this.setS_contactNumber(contactNo);
 }
 
 public Student() 
 { 
 }

 public int getS_rollNo() {
  return s_rollNo;
 }
 public void setS_rollNo(int s_rollNo) {
  this.s_rollNo = s_rollNo;
 }
 public String getS_fname() {
  return s_fname;
 }
 public void setS_fname(String s_fname) {
  this.s_fname = s_fname;
 }
 public String getS_lname() {
  return s_lname;
 }
 public void setS_lname(String s_lname) {
  this.s_lname = s_lname;
 }
 public String getS_contactNumber() {
  return s_contactNumber;
 }
 public void setS_contactNumber(String s_contactNumber) {
  this.s_contactNumber = s_contactNumber;
 }
 
 /*
 * Here Equals method code perform when we try use contain method and the check only Student first name
 * Also we can check multiple variables like below
 */
 @Override
 public boolean equals(Object object) 
 {
  boolean sameSame = false;

  if (object != null && object instanceof Student)
  {
   //for match only student rollno
   //sameSame = this.s_rollNo == ((Student) object).s_rollNo;
   
   //for match only student first name
   sameSame = this.s_fname == ((Student) object).s_fname;
   
   // also we can match both paramater here. if required 
  }

  return sameSame;
 }
 
 @Override
 public int hashCode() 
 {
  int result = 17;
  
  //hash code for checking rollno
  //result = 31 * result + (this.s_rollNo == 0 ? 0 : this.s_rollNo);
  
  //hash code for checking fname
  result = 31 * result + (this.s_fname == null ? 0 : this.s_fname.hashCode());
  
  return result;
 }
}


2. Activity class is MainActivity.java  and I have some dummy data for testing

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity 
{
 ArrayList arrStudents = new ArrayList();

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

  TextView txt = (TextView) findViewById(R.id.textView1);
 
  // here add some data in ArrayList herer
  arrStudents.add(new Student(1,"Ajay","asdasd","3215461321"));
  arrStudents.add(new Student(2,"Rahul","ghdtd","1231231231"));
  arrStudents.add(new Student(3,"Jigar","fg","9998468465"));
  arrStudents.add(new Student(4,"Megha","ldZ","1212712545"));
  arrStudents.add(new Student(5,"Ravi","eyr","1224575131"));
  arrStudents.add(new Student(6,"Rajesh","asd","3416461213"));

  // create new student for check in Arraylist Student first Name contain or not
  Student std = new Student(8,"Rajesh","adfgdfg","123123123");
  //Student std = new Student(4123,"Rajesh","123123","123123123");

  if(arrStudents.contains(std))
  {
   txt.setText(std.toString() +"\n\nNew student First Name already contain in ArrayList index no: "+arrStudents.indexOf(std));
  }
  else 
  {
   arrStudents.contains(std);
   txt.setText(std.toString() +"\n\nNew student successfully add");
  }
 }
}


3. activity_main.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example code for check Student First name in arraylist Using contains method"
        android:textSize="14sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="SampleText" />

</LinearLayout>


4. ScreenShot




This code working Perfectly. Enjoy :) Thank you..


Other Post

- Sorting ArrayList (String ArrayList and custom class)


Wednesday, April 9, 2014

DatePickerDialog in android DialogFragment?

This post I write code for display DatePickerDialog using FragmentDialog.

Generally we display DatePickerDialog using  "onCreateDialog (int id)" Method like below.

//.....
static final int DATE_DIALOG_ID = 999;

//
//

call below code to display DatePickerDialog
showDialog(DATE_DIALOG_ID);

//
//

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
       // set date picker as current date
       return new DatePickerDialog(this, datePickerListener, year, month, day);
    }
   return null;
}
//
//

//we use DatePickerDialog.OnDateSetListener Listner to get selected date like below
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener()
{
    public void onDateSet(DatePicker view, int selectedYear,  int selectedMonth, int selectedDay) {
    }
};




But now "Dialog onCreateDialog(int id)" method deprecated in API level 8. 
So now we can use DialogFragment to display DatePickerDialog and this code working to all android version. I finding DatePickerDialogFragmetn.java class from here.


1. Copy DatePickerDialogFragment.java in your application package.

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.widget.DatePicker;


public class DatePickerDialogFragment extends DialogFragment 
{    
    public static final String YEAR = "Year";
    public static final String MONTH = "Month";
    public static final String DATE = "Day";
    
    private OnDateSetListener mListener;
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mListener = (OnDateSetListener) activity;
    }
    
    @Override
    public void onDetach() {
        this.mListener = null;
        super.onDetach();
    }
    
    @TargetApi(11)
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) 
    {
        Bundle b = getArguments();
        int y = b.getInt(YEAR);
        int m = b.getInt(MONTH);
        int d = b.getInt(DATE);
            
        final DatePickerDialog picker = new DatePickerDialog(getActivity(), getConstructorListener(), y, m, d);
        
        if (hasJellyBeanAndAbove()) {
            picker.setButton(DialogInterface.BUTTON_POSITIVE, 
                    getActivity().getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DatePicker dp = picker.getDatePicker();
                    mListener.onDateSet(dp, 
                            dp.getYear(), dp.getMonth(), dp.getDayOfMonth());
                }
            });
            picker.setButton(DialogInterface.BUTTON_NEGATIVE,
                    getActivity().getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {}
            });
        }
        return picker;
    }
    
    private static boolean hasJellyBeanAndAbove() 
    {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }
    
    private OnDateSetListener getConstructorListener() {
        return hasJellyBeanAndAbove() ? null : mListener;
    }
}


2. Create MainActivity.java

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity implements OnDateSetListener
{
 private TextView tvDisplayDate;
 private Button btnChangeDate;

 private int year;
 private int month;
 private int day;

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

  setCurrentDate();
  button_clickEvent();
 }

 // display current date
 public void setCurrentDate() 
 {
  tvDisplayDate = (TextView) findViewById(R.id.tvDate);
  
  final Calendar c = Calendar.getInstance();
  year = c.get(Calendar.YEAR);
  month = c.get(Calendar.MONTH);
  day = c.get(Calendar.DAY_OF_MONTH);

  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(c.getTime());
  
  tvDisplayDate.setText(s);  
 }

 public void button_clickEvent() 
 {
  btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
  btnChangeDate.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    Bundle b = new Bundle();
    b.putInt(DatePickerDialogFragment.YEAR, year);
    b.putInt(DatePickerDialogFragment.MONTH, month);
    b.putInt(DatePickerDialogFragment.DATE, day);
    DialogFragment picker = new DatePickerDialogFragment();
    picker.setArguments(b);
    picker.show(getFragmentManager(), "fragment_date_picker");
   }
  });
 }
 
 @Override
 public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) 
 {
  this.year = year;
  this.month = monthOfYear;
  this.day = dayOfMonth;
  
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.YEAR, year);
  calendar.set(Calendar.MONTH, monthOfYear);
  calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
  
  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(calendar.getTime());
  
  tvDisplayDate.setText(s);
 }
}


3. activity_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:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Current Date (dd-MM-yyyy): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="asdasd"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Change Date" />

</LinearLayout>


4. ScreenShot





Download APK file Here

Reference link for new version DatePickerDialog issues.

- Jelly Bean DatePickerDialog — is there a way to cancel?
- android-android-4-1-emulator-invoking-ondateset-twice-from-datepicker-dialog