4 May 2012

Date and time Dialog in Android


Android Date Picker allows you to select the date consisting of day, month and year in your custom user interface. For this functionality android provides DatePicker and DatePickerDialog components

OUTPUT SCREEN :



Here is the way to implement DatePicker in application :

Here it the code declare variable and date format as well.

private static final int DIALOG_DATE = 1;
       private static final int DIALOG_TIME = 2;      

       private Calendar dateTime = Calendar.getInstance();
       private SimpleDateFormat dateFormatter = new SimpleDateFormat(
                     "MMMM dd yyyy");
       private SimpleDateFormat timeFormatter = new SimpleDateFormat(
                     "hh:mm a");

Set data to the date and time text view

       txtstdate.setText(dateFormatter.format(dateTime.getTime()));  
       txtAddtime.setText(timeFormatter.format(dateTime.getTime()));

On calling this showDialog method, another method called onCreateDialog gets automatically called. So we have to override that method too. Its syntax is given below:

       @Override
       protected Dialog onCreateDialog(int id)
       {
              switch (id)
              {
              case DIALOG_DATE:
                     return new DatePickerDialog(this, new OnDateSetListener()
                     {

                           @Override
                           public void onDateSet(DatePicker view, int year,
                                         int monthOfYear, int dayOfMonth)
                           {
                           dateTime.set(year, monthOfYear, dayOfMonth);                                  txtstdate.setText(dateFormatter.format(dateTime.getTime()));                                  txtAdddate.setText(dateFormatter.format(dateTime.getTime()));
                           }
                     }, dateTime.get(Calendar.YEAR),
                     dateTime.get(Calendar.MONTH),
                     dateTime.get(Calendar.DAY_OF_MONTH));

              case DIALOG_TIME:
                     return new TimePickerDialog(this, new OnTimeSetListener()
                     {

                           @Override
                           public void onTimeSet(TimePicker view, int hourOfDay,
                                         int minute)
                           {
                                  dateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                  dateTime.set(Calendar.MINUTE, minute);
                                  txtsttime.setText(timeFormatter.format(dateTime.getTime()));
                                  txtAddtime.setText(timeFormatter.format(dateTime.getTime()));
                           }
                     }, dateTime.get(Calendar.HOUR_OF_DAY),
                     dateTime.get(Calendar.MINUTE), false);

              }
              return null;
       }


}

Call dialog :

In order to show DatePickerDialog , you have to pass the DatePickerDialog id to showDialog(id) method.

       showDialog(DIALOG_DATE); 
       showDialog(DIALOG_TIME);



Show Current Date and Time Format with Continuously update on text view: 

       private void Start_Timer()
{  
       timer1 = new Timer();
       timer1.schedule(new UpdateTimeTask(), 1000,1000);
}
class UpdateTimeTask extends TimerTask
{

       public void run()
       {         
              Calendar cal = Calendar.getInstance();
              SimpleDateFormat dateFormatter = new SimpleDateFormat(
                           "EEEE, MMMM d, yyyy");
              dt=dateFormatter.format(cal.getTime());

              if(Chk_DateFormate.isChecked())
              {
                     SimpleDateFormat timeFormatter = new SimpleDateFormat("H:mm");
                     time=timeFormatter.format(cal.getTime());
              }
              else
              {
                     SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm a"); 
                     time=timeFormatter.format(cal.getTime());
              }     
              setTimertext(time);  
       }
}

public void setTimertext(String strValue)
{  

       runOnUiThread(new Runnable()
       {
              public void run()
              {
                     String[]time1=time.split(" ");
                     if(time.endsWith("M"))
                     {
                           txt_time.setText(""+time1[0]);
                           txt_AMPM.setText(""+time1[1]);
                     }
                     else
                     {
                           txt_time.setText(time);
                           txt_AMPM.setText("");
                     }
                     txt_date.setText(dt);

              }
       }); 


Date Format :

Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());

SimpleDateFormat df1 = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate1 = df1.format(c.getTime());

SimpleDateFormat df2 = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate2 = df2.format(c.getTime());

SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());

System.out.println("=========> Date 1 => "+formattedDate1);
System.out.println("=========> Date 2 => "+formattedDate2);
System.out.println("=========> Date 3 => "+formattedDate3);

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)


JSON Parsing in android | JSON parsing android Example

Hello Friends,

In this tutorial we are going to learn how to parse JSON in android.
JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server.


Here is the response from server in JSON format , Now let working on this parsing....

JSONParser.java

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class JSONParser 
{
 public JSONParser() 
 {}

 public String performGet_String(String url) 
 {
  String responce = null;
  try 
  {
   DefaultHttpClient client = new DefaultHttpClient();
   URI uri = new URI(url);
   HttpGet method = new HttpGet(uri);
   HttpResponse res = client.execute(method);
   InputStream data = res.getEntity().getContent();

   StringBuilder stringBuilder = new StringBuilder();
   int b;
   while ((b = data.read()) != -1)
   {
    stringBuilder.append((char) b);
   }
   responce = stringBuilder.toString();
   
  } catch (ClientProtocolException e) {
   
  } catch (IOException e) {   
   e.printStackTrace();
  } catch (URISyntaxException e) {
   
  }

  return responce;
 }
}

Main Activity.java

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends ListActivity 
{
 
 private static String url = "Your JSON URL here....";

 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  new ProgressTask(MainActivity.this).execute();
 }

 private class ProgressTask extends AsyncTask<String, Void, Boolean> 
 {
  private ProgressDialog dialog; 

  public ProgressTask(ListActivity activity) 
  {
   context = activity;
   dialog = new ProgressDialog(context);
  }

  private Context context;

  protected void onPreExecute() 
  {
   this.dialog.setMessage("Progress start");
   this.dialog.show();
  }

  @Override
  protected void onPostExecute(final Boolean success) 
  {
   if (dialog.isShowing()) 
   {
    dialog.dismiss();
   }
  }

  @TargetApi(Build.VERSION_CODES.KITKAT)
  protected Boolean doInBackground(final String... args) 
  {
   JSONParser jParser = new JSONParser();

   // get JSON data from URL
   String Responce = jParser.performGet_String(url);
   Log.i("Responce=", Responce);
   try 
   {
    JSONObject jsonObject=new JSONObject(Responce);
    JSONArray array=jsonObject.getJSONArray("QuestionList");
    Log.e("array size=", ""+array.length());
    
    
    for (int i = 0; i < array.length(); i++) 
    {
     JSONObject jsonObject2=array.getJSONObject(i);
     Log.i("question_id=", jsonObject2.optString("question_id"));
     
     JSONArray array2=jsonObject2.getJSONArray("AnswerText");     
     for (int j = 0; j < array2.length(); j++) 
     {
      JSONObject jsonObject3=array2.getJSONObject(j);
      Log.i("answer_text=", jsonObject3.optString("answer_text"));
     }
    }
   }
   catch (JSONException e) 
   {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   return null;
  }
 }
}

More Reference Link :

http://www.coderzheaven.com/2012/04/26/parsing-json-objects-in-android/
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.

Thank you :)