Monday, May 15, 2017

Android Material Date picker Dialog

May 15, 2017

Welcome to this post.

In this post, we are going to create a material date picker.

Date picker Dialog helps you to pick the date for your application.
If you have an option for user pick their date then you can use it. This popup in your layout. SO it's won't take place on your layout. In this post, we learn about how we can use Date picker Dialog and pick our date.

Ok, let's started.
First, you need to create a class name here DatePickerFragment and extend to DialogFragment and implement DatePickerDialog.OnDateSetListener

Let me show-
public class DatePickerFragment extends DialogFragment implements
  DatePickerDialog.OnDateSetListener {

}

now override two methods named onCreateDialog and onDateSet. in onCreateDialog, we add a calendar and get current date from our calendar and return those values-

@Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {

  Calendar c = Calendar.getInstance();

  int startYear = c.get(Calendar.YEAR);
  startMonth = c.get(Calendar.MONTH);
  int startDay = c.get(Calendar.DAY_OF_MONTH);

  return new DatePickerDialog(getActivity(),this,startYear,startMonth,startDay);
  }

Note: in this methods, you can set you desire date if you want to show to your user. For this, you can first set date on the calendar the before getting data.

A quick look-
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
  try {
  String dateStr = "1/5/2017";
  Date date = format.parse(dateStr);
  c.setTime(date);
  } catch (ParseException e) {
  e.printStackTrace();
  }

Note: here I formatted a string into date and set it to the calendar. But you can add directly like this way-

Calendar calendar =Calendar.getInstance();
        
calendar.set(Calendar.YEAR, 2017);
calendar.set(Calendar.MONTH, 2);
calendar.set(Calendar.DAY_OF_MONTH, 17);

when user set the date then onDateSet will be executed. the code is your wish. you get all in an integer. here I save it on shared preference.

@Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

  String dateStr = dayOfMonth+"/"+month+"/"+year;
  SharedPreferences preferences = getActivity().getSharedPreferences("TimeDate", Context.MODE_PRIVATE);
  
  SharedPreferences.Editor editor = preferences.edit();
  editor.putString("Date",dateStr);
  editor.apply();

  }

Ok. we created our DatepickerDialog.java class. Now we use it on on button listener.

dateTvLabel.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  DatePickerFragment datePickerFragment = new DatePickerFragment();
  datePickerFragment.show(getFragmentManager(), "Date Picker");
  }
  });

and That's it. Now you can use this Date Picker Dialog and customize your project.

datePicker


 Happy coding.

Read More

Android Material Time Picker Dialog

May 15, 2017

Time picker Dialog helps you to pick the time for your application. If you have an option for user pick their time then you can use it. This popup in your layout. SO it's won't take place on your layout. In this post, we learn about how we can use time picker Dialog and pick our time. First, you need to create a class name here TimePickerFragment and extend to DialogFragment and implement TimePickerDialog.OnTimeSetListener ok, Let's start -

public class TimePickerFragment extends DialogFragment implements
  TimePickerDialog.OnTimeSetListener {

}

now override two methods named onCreateDialog and onTimeSet. in onCreateDialog, we add a calendar and get the current time from our calendar and return those values-

@Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {

  //Use the current time as the default values for the time picker
  final Calendar c = Calendar.getInstance();

  int hour = c.get(Calendar.HOUR_OF_DAY);
  int minute = c.get(Calendar.MINUTE);

  //Create and return a new instance of TimePickerDialog
  return new TimePickerDialog(getActivity(), this, hour, minute,
  DateFormat.is24HourFormat(getActivity()));
  }

Note if you want to set a specific time then set on it calendar first and get date same as we do on DatePickerDiolog Ok, let's show again-

SimpleDateFormat format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);

String timeStr = "10:12 PM"

try {
Date time = format.parse(timeStr);
c.setTime(time);
} catch (ParseException e) {
e.printStackTrace();
}

Note: here I formatted a string into date and set it to the calendar. But you can add directly like this way-

Calendar calendar =Calendar.getInstance();
  
calendar.set(Calendar.HOUR_OF_DAY, 22);
calendar.set(Calendar.MINUTE, 22);

when user set the date then onDateSet will be executed. code is your wish. you get all in an integer. here I save it on shared preference.

@Override
  public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
  String time=hourOfDay+":"+minute;
  SharedPreferences preferences = getActivity().getSharedPreferences("TimeDate", 
                                           Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = preferences.edit();
  editor.putString("Time",time);
  editor.apply();
  }

That's it. we finished up TimePiclerDialog Class. But one this if you want to 12 our clock that's show AM or PM. Then you should modify this code. Because here hourOfDay is shown 24 hours format. Ok now modify the code. If our hourOfDay is greater than 11 then it's must be PM. so we add pm on the string. and subtract from 12 then we get again 12 hours format. Let's move on code-

//Get the AM or PM for current time
        String aMpM = "AM";
        if (hourOfDay > 11) {
            aMpM = "PM";
        }

        //Make the 24 hour time format to 12 hour time format
        int currentHour;
        if (hourOfDay > 11) {
            currentHour = hourOfDay - 12;
        } else {
            currentHour = hourOfDay;
        }

        String time = String.valueOf(currentHour)
                + ":" + String.valueOf(minute) + " " + aMpM;

Not enough for understanding then full methods-

@Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        //Get the AM or PM for current time
        String aMpM = "AM";
        if (hourOfDay > 11) {
            aMpM = "PM";
        }

        //Make the 24 hour time format to 12 hour time format
        int currentHour;
        if (hourOfDay > 11) {
            currentHour = hourOfDay - 12;
        } else {
            currentHour = hourOfDay;
        }

        String time = String.valueOf(currentHour)
                + ":" + String.valueOf(minute) + " " + aMpM;

        Log.e("TIME is set", time);
        SharedPreferences preferences = getActivity().getSharedPreferences("TimeDate", 
                                                 Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("Time",time);
        editor.apply();
    }

Ok, that's great. Now we use it on on button listener or Click listener on any view.

//set time
        timeTvLabel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerFragment pickerDialog = new TimePickerFragment();
          
                pickerDialog.show(getFragmentManager(), "Time Pick");
            }
        });

That's it. We finish our today coding. Hope it's working.

time picker


 Happy coding.

Read More

Saturday, May 13, 2017

Android Custom Dialog with Material Design

May 13, 2017

Hello, reader.
Welcome to my blog.
How about your day?

In this post, we will make a custom dialog with user input option.

we also use material edit text. Edit text has a floating hint option. we can use it on login option or feedback option. But I am using for feedback option.

So we are going to add a custom dialog so we have to add a layout file.
Our dialog will show exactly what we will design in our layout XML file. In our layout XML file, we have 3 Edit text. Because we need to get three information from our user. Need username and user email address and user feedback.

Add 3 Edit text-

  • Name EditText
  • Email EditText
  • Message EditText


Enough Intro. Let's start.

At first, you need to check that's design dependence is added to your gradle file. But the android studio has already added those dependencies  If not add already then add it. Because you use Text Input layout. I am not showing how to add design dependence, I think you are quite capable of adding this.

Now create a layout File name custom_dialog.xml
We use the Constraint Layout layout as base layout. Now add the Text Input Layout as child layout of the Main layout. After that, We add our EditText as a child layout of TextInputLayout. In the edit text, we add a hint option for Edit text and that's label will float up when user will start writing.

Let's show me the code.
Below code is the full code of our custom dialog XML file.
custom_dialog.xml
<android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

  <android.support.design.widget.TextInputLayout
  android:id="@+id/addTaskNameLayout"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_marginEnd="@dimen/card_element_margin"
  android:layout_marginStart="@dimen/card_element_margin"
  android:layout_marginTop="@dimen/card_element_margin"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent">

  <EditText
  android:id="@+id/customName"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="@string/custom_name"
  android:inputType="textPersonName"
  android:padding="@dimen/main_list_universal_padding"
  android:textColorHint="?attr/colorAccent"/>
  </android.support.design.widget.TextInputLayout>

  <android.support.design.widget.TextInputLayout
  android:id="@+id/textInputLayout"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_marginEnd="@dimen/card_element_margin"
  android:layout_marginStart="@dimen/card_element_margin"
  android:layout_marginTop="8dp"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toBottomOf="@+id/addTaskNameLayout">

  <EditText
  android:id="@+id/customEmail"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="@string/custom_email"
  android:inputType="textEmailAddress"
  android:padding="@dimen/main_list_universal_padding"
  android:textColorHint="?attr/colorAccent"/>

  </android.support.design.widget.TextInputLayout>

  <android.support.design.widget.TextInputLayout
  android:id="@+id/addTaskSolLayout"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_marginEnd="@dimen/card_element_margin"
  android:layout_marginStart="@dimen/card_element_margin"
  android:layout_marginTop="8dp"
  app:layout_constraintHorizontal_bias="0.0"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toBottomOf="@+id/textInputLayout">

  <EditText
  android:id="@+id/customFeedback"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="@string/custom_feedback"
  android:inputType="textMultiLine"
  android:lines="4"
  android:maxLines="10"
  android:padding="@dimen/main_list_universal_padding"
  android:textColorHint="?attr/colorAccent"/>
  </android.support.design.widget.TextInputLayout>


</android.support.constraint.ConstraintLayout>

Note: I don't add any button on this layout. I use default button in the dialog (positive button or negative button in the dialog) but if need to add your custom design button you can add here.

You are seeing some error. Don't worry about it. it's only for String reference not find in your system. You can override it by yourself. but  I also provide my strings that strings are used for the hint as Edit text.

<!-- Custom dialog layout -->
  <!-- ***************Start************* -->
  <string name="custom_name">Your Name:</string>
  <string name="custom_email">your email:</string>
  <string name="custom_feedback">your message:</string>
  <!-- ***************FINISH************* -->

But after you add all of those strings, you also some error too. It's for dimension reference. I also provide my dimension reference. Let's take a look.

<dimen name="card_element_margin">8dp</dimen>

that's it for XML code.

Now we gonna move on JAVA code.
Let's start where you want to build dialog you can use it on fragment or Activity.
I used in MainActivity, and I created separate methods for this. But it's as like other Alert Dialog but only you should use Layout Inflator to inflate layout.xml. And Edit Text function is as like others. And get the text from edit text also same. we add positive and negative button label as Send and cancel. We get all text in the positive click listener and send it's to Email app through Intent.
Ok, see the code-
private void feedback() {

  AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
  LayoutInflater inflater = this.getLayoutInflater();
  final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
  dialogBuilder.setView(dialogView);

  final EditText name = (EditText) dialogView.findViewById(R.id.customName);
  final EditText email = (EditText) dialogView.findViewById(R.id.customEmail);
  final EditText message = (EditText) dialogView.findViewById(R.id.customFeedback);

  dialogBuilder.setTitle("Send FeedBack");
  dialogBuilder.setMessage("please send me to your feedback.");
  dialogBuilder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {
  String nameStr = name.getText().toString().trim();
  String emailStr = email.getText().toString();
  String messageStr = message.getText().toString().trim();
  
  Intent emailIntent = new Intent(Intent.ACTION_SEND);
  emailIntent.setData(Uri.parse("mailto:"));
  emailIntent.setType("message/rfc822");
  emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"Shudiptotrafder@gmail.com"});
  emailIntent.putExtra(Intent.EXTRA_CC, emailStr);
  emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Life Scheduler Feedback");
  emailIntent.putExtra(Intent.EXTRA_TEXT, nameStr + ":" + messageStr);

  if (emailIntent.resolveActivity(getPackageManager()) != null) {
  startActivity(Intent.createChooser(emailIntent, "Send Email ..."));
  } else {
  Toast.makeText(MainActivity.this, "Sorry you don't have any email app", Toast.LENGTH_SHORT).show();
  }

  }
  });
  dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {
  //pass
  }
  });

  AlertDialog b = dialogBuilder.create();
  b.show();
  }

That's it. Now run your code and use it where ever you want. If you have any queries then you can use comment option.
See the final Screen Short-
custom dialog



Hope this tutorial will help you.
It will help you to implement easily to add feedback option from your app. And if you want to add quick login option in your app, you can use this too, but you need to customize. If you have any quires then you can use the comment section.

Happy coding

Read More