Introduction

In this article, you will learn how to show when a post was posted, as you see on Facebook. In Facebook, you can see the time of the status, comments and so on as "Just Now", "1 day ago", "2 months ago and so on".
For doing this we will first store the post text and its time in a database. Later, while displaying, we will determine the difference between the present time and post time and display it accordingly.
Step 1
Create a new layout file.
Right-click on layout then select "New" -> "Layout resource file". Name it "first_layout" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="vertical"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#e6b4ac">
  6. <Button
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:layout_marginTop="150dp"
  10. android:layout_marginLeft="120dp"
  11. android:text="View Post"
  12. android:id="@+id/view"
  13. android:background="@drawable/button_lay"
  14. android:paddingRight="10dp"
  15. android:paddingLeft="10dp"/>
  16. <Button
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:layout_marginTop="150dp"
  20. android:layout_marginLeft="120dp"
  21. android:text="Write Post"
  22. android:id="@+id/write"
  23. android:background="@drawable/button_lay"
  24. android:paddingRight="10dp"
  25. android:paddingLeft="10dp"/>
  26. </LinearLayout>
The layout looks like:
im1.jpg
Step 2
Open "activity_main" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:paddingLeft="@dimen/activity_horizontal_margin"
  6. android:paddingRight="@dimen/activity_horizontal_margin"
  7. android:paddingTop="@dimen/activity_vertical_margin"
  8. android:paddingBottom="@dimen/activity_vertical_margin"
  9. tools:context=".MainActivity"
  10. android:background="#b7a3ca"
  11. android:orientation="vertical">
  12. <TextView
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:text="@string/wats"
  16. android:textSize="30dp"
  17. />
  18. <EditText
  19. android:layout_height="wrap_content"
  20. android:layout_width="fill_parent"
  21. android:layout_marginLeft="10dp"
  22. android:layout_marginTop="50dp"
  23. android:layout_marginRight="10dp"
  24. android:scrollbars="vertical"
  25. android:id="@+id/postTxt"
  26. />
  27. <Button
  28. android:layout_width="wrap_content"
  29. android:layout_height="wrap_content"
  30. android:layout_marginTop="200dp"
  31. android:layout_marginLeft="120dp"
  32. android:text="POST"
  33. android:background="@drawable/button_lay"
  34. android:id="@+id/submit"
  35. />
  36. </LinearLayout>
The layout looks like:
im2.jpg
Step 3
Create a new layout file for viewing the thoughts/posts.
Right-click on layout then select "New" -> "Layout resource file". Name it as "view_layout2" and add the following code to it:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <TextView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="wrap_content"
  5. android:padding="10dp"
  6. android:textSize="20sp"
  7. android:background="#459890"
  8. >
  9. </TextView>
The layout looks like:
im3.jpg
Step 4
Open "MainActivity" and add the following code to it:
  1. package com.chhavi.posttimimgs;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.app.Activity;
  6. import android.util.Log;
  7. import android.view.Menu;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import java.sql.Date;
  11. import java.text.SimpleDateFormat;
  12. import java.util.Calendar;
  13. public class MainActivity extends Activity {
  14. Button view;
  15. Button write;
  16. final Context context=this;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.first_layout);
  21. view=(Button)findViewById(R.id.view);
  22. write=(Button)findViewById(R.id.write);
  23. view.setOnClickListener(new View.OnClickListener() {
  24. @Override
  25. public void onClick(View v) {
  26. Intent i=new Intent(context,ViewPost.class);
  27. startActivity(i);
  28. }
  29. });
  30. write.setOnClickListener(new View.OnClickListener() {
  31. @Override
  32. public void onClick(View v) {
  33. Intent i=new Intent(context,WritePost.class);
  34. startActivity(i);
  35. }
  36. });
  37. }
  38. @Override
  39. public boolean onCreateOptionsMenu(Menu menu) {
  40. // Inflate the menu; this adds items to the action bar if it is present.
  41. getMenuInflater().inflate(R.menu.main, menu);
  42. return true;
  43. }
  44. }
Step 5
Create a new Java file.
Right-click on the same package then select "New" -> "Java class". Name this "WritePost" and add the following code to it:
  1. package com.chhavi.posttimimgs;
  2. import android.app.Activity;
  3. import android.content.ContentValues;
  4. import android.database.sqlite.SQLiteDatabase;
  5. import android.os.Bundle;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.Toast;
  11. import java.util.Calendar;
  12. public class WritePost extends Activity {
  13. Button submit;
  14. EditText txt;
  15. static int count=1;
  16. private ThoughtsDataSource dataSource;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. txt=(EditText)findViewById(R.id.postTxt);
  22. submit=(Button)findViewById(R.id.submit);
  23. dataSource = new ThoughtsDataSource(WritePost.this);
  24. submit.setOnClickListener(new View.OnClickListener() {
  25. @Override
  26. public void onClick(View v) {
  27. try{
  28. dataSource.open();
  29. Calendar cal=Calendar.getInstance();
  30. ThoughtData data = new ThoughtData();
  31. data.setThought(txt.getText().toString());
  32. data.setDateTimeString(cal.getTime().toString());
  33. int date= Calendar.DAY_OF_MONTH;
  34. int hr=Calendar.HOUR_OF_DAY;
  35. int amPm=Calendar.AM_PM;
  36. int day=Calendar.DAY_OF_WEEK;
  37. if(dataSource.createThought(data)>0)
  38. {
  39. Toast.makeText(WritePost.this, "Thought posted successfully", 1000).show();
  40. finish();
  41. }
  42. }
  43. catch(Exception e)
  44. {
  45. Log.i("exception in creating.........",e+"");
  46. }
  47. }
  48. });
  49. }
  50. }
Step 6
Right-click on the same package then select "New" -> "Java class". Name this "SQLiteHelper" and add the following code to it:
  1. package com.chhavi.posttimimgs;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteDatabase.CursorFactory;
  5. import android.database.sqlite.SQLiteOpenHelper;
  6. public class SQLiteHelper extends SQLiteOpenHelper {
  7. public static final String TABLE_TIMING = "timing";
  8. public static final String COLUMN_ID = "_id";
  9. public static final String COLUMN_THOUGHT = "thought";
  10. public static final String COLUMN_DATETIME = "dateTime";
  11. private static final String DATABASE_NAME = "timingDB.db";
  12. private static final int DATABASE_VERSION = 1;
  13. private static final String DATABASE_CREATE = "create table "
  14. + TABLE_TIMING + "(" + COLUMN_ID
  15. + " integer primary key AUTOINCREMENT NOT NULL , " + COLUMN_THOUGHT
  16. + " text not null, " + COLUMN_DATETIME
  17. + " text not null);";
  18. public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {
  19. super(context, name, factory, version);
  20. // TODO Auto-generated constructor stub
  21. }
  22. public SQLiteHelper(Context context) {
  23. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  24. }
  25. @Override
  26. public void onCreate(SQLiteDatabase db) {
  27. // TODO Auto-generated method stub
  28. db.execSQL(DATABASE_CREATE);
  29. }
  30. @Override
  31. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  32. // TODO Auto-generated method stub
  33. db.execSQL("DROP TABLE IF EXISTS " + TABLE_TIMING);
  34. onCreate(db);
  35. }
  36. }
Step 7
Right-click on the same package then select "New" -> "Java class". Name this "ThoughtData" and add the following code to it:
  1. package com.chhavi.posttimimgs;
  2. public class ThoughtData {
  3. String thought;
  4. String dateTimeString;
  5. public String getThought() {
  6. return thought;
  7. }
  8. public void setThought(String thought) {
  9. this.thought = thought;
  10. }
  11. public String getDateTimeString() {
  12. return dateTimeString;
  13. }
  14. public void setDateTimeString(String dateTimeString) {
  15. this.dateTimeString = dateTimeString;
  16. }
  17. }
Step 8
Right-click on the same package then select "New" -> "Java class". Name this "ThoughtDataSource" and add the following code to it:
  1. package com.chhavi.posttimimgs;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import android.content.ContentValues;
  5. import android.content.Context;
  6. import android.database.Cursor;
  7. import android.database.SQLException;
  8. import android.database.sqlite.SQLiteDatabase;
  9. public class ThoughtsDataSource {
  10. private SQLiteDatabase database;
  11. private SQLiteHelper dbHelper;
  12. private String[] allColumns = { SQLiteHelper.COLUMN_ID,
  13. SQLiteHelper.COLUMN_THOUGHT, SQLiteHelper.COLUMN_DATETIME };
  14. public ThoughtsDataSource(Context context) {
  15. dbHelper = new SQLiteHelper(context);
  16. }
  17. public void open() throws SQLException {
  18. database = dbHelper.getWritableDatabase();
  19. }
  20. public void close() {
  21. dbHelper.close();
  22. }
  23. public long createThought(ThoughtData data) {
  24. ContentValues values = new ContentValues();
  25. values.put(SQLiteHelper.COLUMN_THOUGHT, data.getThought());
  26. values.put(SQLiteHelper.COLUMN_DATETIME, data.getDateTimeString());
  27. long insertId = database.insert(SQLiteHelper.TABLE_TIMING, null,
  28. values);
  29. return insertId;
  30. }
  31. public void deleteThought(long id) {
  32. database.delete(SQLiteHelper.TABLE_TIMING, SQLiteHelper.COLUMN_ID
  33. + " = " + id, null);
  34. }
  35. public void deleteAllThoughts() {
  36. database.delete(SQLiteHelper.TABLE_TIMING, "", null);
  37. }
  38. public ArrayList<ThoughtData> getAllResources() {
  39. ArrayList<ThoughtData> resources = new ArrayList<ThoughtData>();
  40. Cursor cursor = database.query(SQLiteHelper.TABLE_TIMING,allColumns, null, null, null, null, null);
  41. cursor.moveToFirst();
  42. while (!cursor.isAfterLast()) {
  43. try {
  44. ThoughtData data;
  45. data = cursorToResourceData(cursor);
  46. resources.add(data);
  47. } catch (Exception e) {
  48. // TODO Auto-generated catch block
  49. e.printStackTrace();
  50. }
  51. cursor.moveToNext();
  52. }
  53. cursor.close();
  54. return resources;
  55. }
  56. private ThoughtData cursorToResourceData(Cursor cursor) throws Exception {
  57. ThoughtData resourceData = new ThoughtData();
  58. resourceData.setThought(cursor.getString(1));
  59. resourceData.setDateTimeString(cursor.getString(2));
  60. return resourceData;
  61. }
  62. }
Step 9
Right-click on the same package then select "New" -> "Java class". Name this "ViewPost" and add the following code to it:
  1. package com.chhavi.posttimimgs;
  2. import android.app.Activity;
  3. import android.app.ListActivity;
  4. import android.content.Context;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.os.Bundle;
  8. import android.util.Log;
  9. import android.view.View;
  10. import android.widget.AdapterView;
  11. import android.widget.ArrayAdapter;
  12. import android.widget.ListAdapter;
  13. import android.widget.ListView;
  14. import android.widget.SimpleAdapter;
  15. import java.text.DateFormat;
  16. import java.text.SimpleDateFormat;
  17. import java.util.ArrayList;
  18. import java.util.Calendar;
  19. import java.util.Date;
  20. import java.util.GregorianCalendar;
  21. import java.util.HashMap;
  22. import java.util.Locale;
  23. import java.util.concurrent.TimeUnit;
  24. public class ViewPost extends ListActivity
  25. {
  26. final Context context=this;
  27. ListView lv ;
  28. ArrayList<String> allPost= new ArrayList<String>();
  29. private ThoughtsDataSource dataSource;
  30. @Override
  31. protected void onCreate(Bundle savedInstanceState) {
  32. super.onCreate(savedInstanceState);
  33. Calendar cal=Calendar.getInstance();
  34. Date now=cal.getTime();
  35. dataSource = new ThoughtsDataSource(ViewPost.this);
  36. try{
  37. dataSource.open();
  38. ArrayList<ThoughtData> allData = new ArrayList<ThoughtData>();
  39. allData = dataSource.getAllResources();
  40. ThoughtData data;
  41. for (int i = 0; i < allData.size(); i++) {
  42. data = allData.get(i);
  43. Log.i("Value of i......",i+"");
  44. String time=data.getDateTimeString();
  45. Log.i("time.............",time);
  46. DateFormat df=new SimpleDateFormat("E MMM d HH:mm:ss Z yyyy");// M d HH:mm:ssZ yyyy
  47. Date postTime=df.parse(time);
  48. Log.i("Only date.........****...", postTime + "");
  49. //system time
  50. Log.i("System time........",now.toString());
  51. long diff=(now.getTime()-postTime.getTime())/1000;
  52. Log.i("difference in sec...........", diff+"");
  53. Log.i("time only for now.........",now.getTime()+"");
  54. Log.i("time only for postTime.........",postTime.getTime()+"");
  55. //for months
  56. Calendar calObj = Calendar.getInstance();
  57. calObj.setTime(postTime);
  58. int m=calObj.get(Calendar.MONTH);
  59. Log.i("post time month............", m+"");
  60. Calendar calObjNow = Calendar.getInstance();
  61. calObj.setTime(now);
  62. int mNow=calObj.get(Calendar.MONTH);
  63. Log.i("now month............", mNow+"");
  64. String disTime="";
  65. if(diff<15)
  66. {
  67. disTime="\nJust Now";
  68. }
  69. else if(diff<60)
  70. {
  71. disTime="\n"+diff+" seconds ago";
  72. }
  73. else if(diff<3600) // until 1 hr
  74. {
  75. long temp=diff/60;
  76. if(temp==1)
  77. disTime="\n"+temp+" min ago";
  78. else
  79. disTime="\n"+temp+" mins ago";
  80. }
  81. else if(diff<(24*3600)) // until 24 hrs
  82. {
  83. long temp=diff/3600;
  84. if(temp==1)
  85. disTime="\n"+temp+" hr ago";
  86. else
  87. disTime="\n"+temp+" hrs ago";
  88. }
  89. else if(diff<(24*3600*7)) //until 7 days
  90. {
  91. long temp=diff/(3600*24);
  92. if (temp==1)
  93. disTime="\nyesterday";
  94. else
  95. disTime="\n"+temp+" days ago";
  96. }
  97. else if(diff<((24*3600*365))) // no. of months.. until 1 yr
  98. {
  99. //long temp=diff/(3600*24;
  100. if(diff<=1)
  101. {
  102. if(diff<1)
  103. {
  104. long weeks=diff/7;
  105. if(weeks<1)
  106. disTime="last week";
  107. else
  108. disTime=weeks+" weeks ago";
  109. }
  110. else
  111. disTime="1 month ago";
  112. }
  113. else
  114. {
  115. int diffMonth=mNow-m;
  116. disTime="\n"+diffMonth+" months ago";
  117. }
  118. }
  119. else
  120. {
  121. disTime="\n"+data.dateTimeString;
  122. }
  123. allPost.add(data.thought + "\n" + disTime);
  124. }
  125. setListAdapter(new ArrayAdapter<String>(this, R.layout.view_layout2,allPost));
  126. ListView listView = getListView();
  127. listView.setTextFilterEnabled(true);
  128. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  129. @Override
  130. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  131. }
  132. });
  133. }
  134. catch(Exception e)
  135. {
  136. e.printStackTrace();
  137. // Log.i("Exception in db....", e + "");
  138. }
  139. }
  140. }
In the code above, "diff" is the difference between the two dates (the date on which the thought was posted and current date) in seconds. "disTime" gives the time that will be displayed, for example: "Just Now" will be displayed for thought posted "15 sec ago", time in seconds will be displayed for thought posted less than a minute ago and so on.
Step 10
Do the following changes in "AndroidManifest.xml":
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.chhavi.posttimimgs"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk
  7. android:minSdkVersion="8"
  8. android:targetSdkVersion="17" />
  9. <application
  10. android:allowBackup="true"
  11. android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name"
  13. android:theme="@style/AppTheme" >
  14. <activity
  15. android:name="com.chhavi.posttimimgs.MainActivity"
  16. android:label="@string/app_name" >
  17. <intent-filter>
  18. <action android:name="android.intent.action.MAIN" />
  19. <category android:name="android.intent.category.LAUNCHER" />
  20. </intent-filter>
  21. </activity>
  22. <activity
  23. android:name="com.chhavi.posttimimgs.ViewPost"
  24. android:label="@string/app_name" >
  25. </activity>
  26. <activity
  27. android:name="com.chhavi.posttimimgs.WritePost"
  28. android:label="@string/app_name" >
  29. </activity>
  30. </application>
  31. </manifest>
Output snapshots:
im4.jpg
Selecting "Write Post" will give you:
im5.jpg
Selecting "View Post" will give you:
im6f.jpg