Monday, July 1, 2013

Calculate UTC in Android

Hello Readers,

After A long Time I am restart My Blogging and add one more Tutorial about UTC.
OK first we have to know about utc and how it works. for That you have to visit the following page 
about UTC 

Now We Move to Android Side and see that how android calculate UTC.

first of all I assume that u have A basic Knowledge of Android Programming , Eclipse and all its related Stuff.

And Below you see the some images of final out put of your application.



and Related Code I pasted below




  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package com.example.utctime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	static final String DATEFORMAT = "yyyy-MM-dd HH:mm";
	private EditText mDateDisplay;
	private Button calImage;
	private int mYear;
	private int mMonth;
	private int mDay;
	private Spinner hhSpinner, mmSpinner;
	private EditText etUtc;
	private Spinner spTimeZone;
	private static final int DATE_DIALOG_ID = 1;
	private String selectedZone;
	private String selectedHours;
	private String selectedMinute;
	private String selectedDate;
	private Date date1 = null;

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

		mDateDisplay = (EditText) findViewById(R.id.etDateTime);
		etUtc = (EditText) findViewById(R.id.etUtc);
		calImage = (Button) findViewById(R.id.imgCal);

		calImage.setOnClickListener(this);

		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		spTimeZone = (Spinner) findViewById(R.id.spTimeZone);
		hhSpinner = (Spinner) findViewById(R.id.spHH);
		hhSpinner.setOnItemSelectedListener(new hhItemSelectedListener());
		hhSpinner.requestFocus();

		mmSpinner = (Spinner) findViewById(R.id.spMM);
		mmSpinner.setOnItemSelectedListener(new mmItemSelectedListener());
		mmSpinner.requestFocus();

		String[] TZ = TimeZone.getAvailableIDs();
		TZ[0] = "Select Time Zone";
		ArrayAdapter<String> Timeadapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, TZ);

		Timeadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// ArrayList<String> TZ1 = new ArrayList<String>();
		// for (int i = 0; i < TZ.length; i++) {
		// if (!(TZ1.contains(TimeZone.getTimeZone(TZ[i]).getDisplayName()))) {
		// TZ1.add(TimeZone.getTimeZone(TZ[i]).getDisplayName());
		// }
		// }
		// TZ1.add(0, "Select Time Zone");
		// for (int i = 0; i < TZ1.size(); i++) {
		// Timeadapter.add(TZ1.get(i));
		// }

		spTimeZone.setAdapter(Timeadapter);
		spTimeZone
				.setOnItemSelectedListener(new timeZoneItemSelectedListener());
		spTimeZone.requestFocus();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imgCal:
			showDialog(DATE_DIALOG_ID);
			break;

		default:
			break;
		}
	}

	// create date Dialog
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {

		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			break;
		}
	}

	private void updateDisplay() {
		mDateDisplay.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(mYear).append("-").append(mMonth + 1).append("-")
				.append(mDay).append(" "));
		selectedDate = mDateDisplay.getText().toString();

	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	// Hours Spinner

	public class hhItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			selectedHours = parent.getItemAtPosition(pos).toString();
			// showToast(selected);
		}

		public void onNothingSelected(AdapterView parent) {
		}

	}

	// minute spinner
	public class mmItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			selectedMinute = parent.getItemAtPosition(pos).toString();
			// showToast(selected);

		}

		public void onNothingSelected(AdapterView parent) {
		}
	}

	// minute spinner
	public class timeZoneItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			selectedZone = parent.getItemAtPosition(pos).toString();
			if (selectedHours.equalsIgnoreCase("hh")
					|| selectedMinute.equalsIgnoreCase("mm")
					|| selectedZone.equalsIgnoreCase("Select Time Zone")) {
				System.out.println("Please Select time and date and time zone");
			} else {
				String dateTime = selectedDate + selectedHours + ":"
						+ selectedMinute;
				System.out.println("old Date time - " + dateTime);

				String startTime = dateTime;
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm");

				try {
					date1 = dateFormat.parse(startTime);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("Formatted Date time - " + date1);
				date1 = GetUTCdatetimeAsDate();

				// String utcDate = GetUTCdatetimeAsString();

				System.out.println("UTC DATE  => " + date1);

				etUtc.setText(date1.toString());
			}

		}

		public void onNothingSelected(AdapterView parent) {
		}
	}

	public Date GetUTCdatetimeAsDate() {
		// note: doesn't check for null
		return StringDateToDate(GetUTCdatetimeAsString());
	}

	public String GetUTCdatetimeAsString() {
		final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
		if (selectedZone.equalsIgnoreCase("Select Time Zone")) {
			System.out.println("Selecte Time Zone Please");
			Toast.makeText(MainActivity.this, "Selecte Time Zone Please", Toast.LENGTH_LONG).show();
		} else {
			sdf.setTimeZone(TimeZone.getTimeZone(selectedZone));
		}
		final String utcTime = sdf.format(date1);

		return utcTime;

	}

	public Date StringDateToDate(String StrDate) {
		Date dateToReturn = null;
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);

		try {
			dateToReturn = (Date) dateFormat.parse(StrDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return dateToReturn;
	}

	@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;
	}
In Above Code Line number 69 is important
- Timezone : Most applications will use getDefault() which returns a TimeZone based on the time zone where the program is running.
- TimeZone.getAvailableIDs Returns the system's installed time zone IDs. Any of these IDs can be passed to getTimeZone(String) to lookup the corresponding time zone instance.

If you wish to download complete source code. you can download from below link
UTC Calculator


Sunday, September 23, 2012

Android Chat Application

In Today's Smart Phone Life Mobile Chat is very popular and In this  Article I will explain about android chat application.Not a whole scenario but some part of the chatting application like how we can add a emoticon in to your edittext and displayed in to the screen.

end of the document i post a download full source code.Here Below some Java file and screen shots is available
MainActivity.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.example.mysmiley;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Selection;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {
 EditText display, writeboard;
 Button submit, select,clear;

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

  initUiElement();
  
  submit.setOnClickListener(this);
  select.setOnClickListener(this);
  clear.setOnClickListener(this);
 }

 private void initUiElement() {
  display = (EditText) findViewById(R.id.display);
  writeboard = (EditText) findViewById(R.id.writeboard);
  submit = (Button) findViewById(R.id.btnsubmit);
  select = (Button) findViewById(R.id.btnselect);
  clear = (Button)findViewById(R.id.btnclear);
 }

 CharSequence cs;
 CustomEmojis emojis;
 int index;

 @Override
 protected void onRestart() {
  super.onRestart();
  emojis = new CustomEmojis(this);

  SharedPreferences preferences = this.getSharedPreferences("pref",
    this.MODE_WORLD_READABLE);
  index = preferences.getInt("smiley", 0);
  System.out.println("smiley index is---> " + index);

  ImageGetter imageGetter = new ImageGetter() {

   @Override
   public Drawable getDrawable(String source) {
    Drawable d = getResources().getDrawable(emojis.images[index]);
    d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    return d;
   }
  };
  cs = Html.fromHtml(
    "<img src ='"
      + getResources().getDrawable(emojis.images[index])
      + "'/>", imageGetter, null);
  writeboard.setText(cs);
  int position = writeboard.length();
  Editable editable = writeboard.getText();
  Selection.setSelection(editable, position);
 }

 @Override
 public void onClick(View v) {
  switch (v.getId()) {
  case R.id.btnsubmit:
   display.setText(display.getText().append(writeboard.getText()));
   writeboard.setText("");
   break;
  case R.id.btnselect:
   Intent i = new Intent(MainActivity.this, EmojiSelection.class);
   startActivity(i);
   break;
  case R.id.btnclear:
   display.setText("");
   break;
  
  default:
   break;
  }

 }

}

After main file creation you need to create another activity EmojiSelection Activity. in this activity you show that how the emoji will selected using shared preference.

EmojiSelection.java





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.example.mysmiley;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class EmojiSelection extends Activity {
 public static final String TAG = "EmojiSelection";

 GridView gridView;
 CustomEmojis customEmojis;

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

  initUIElement();

  customEmojis = new CustomEmojis(this);
  gridView.setAdapter(customEmojis);

  gridView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> arg0, View arg1,
     int position, long arg3) {

    Log.i(TAG, "U are in OnItemSelected");
    SharedPreferences preferences = EmojiSelection.this
      .getSharedPreferences("pref", MODE_WORLD_READABLE);
    SharedPreferences.Editor editor = preferences.edit();

    editor.putInt("smiley", position);
    System.out.println("Selected emojis ---> " + position);

    // dont forgot to commit preference
    editor.commit();

    finish();
   }
  });
 }

 private void initUIElement() {
  gridView = (GridView) findViewById(R.id.gridview1);

 }

}

in my example i am create custom gridview class for the displaying the emojis. In below code you can see.
CustomEmojis.java



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.example.mysmiley;

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.ImageView;

public class CustomEmojis extends BaseAdapter {
 private Activity activity;
 private static LayoutInflater inflater = null;

 public final int[] images = new int[] { R.drawable.a, R.drawable.b,
   R.drawable.c, R.drawable.d, R.drawable.e, R.drawable.f,
   R.drawable.g, R.drawable.h, R.drawable.j, R.drawable.k,
   R.drawable.l, R.drawable.m, R.drawable.n, R.drawable.o,
   R.drawable.p, R.drawable.q, R.drawable.r, R.drawable.s,
   R.drawable.t, R.drawable.u, R.drawable.v, R.drawable.w,
   R.drawable.x, R.drawable.y, R.drawable.z, R.drawable.aa,
   R.drawable.bb, R.drawable.cc, R.drawable.dd, R.drawable.ee,
   R.drawable.ff, R.drawable.gg, R.drawable.hh, R.drawable.ii,
   R.drawable.jj, R.drawable.kk, R.drawable.ll, R.drawable.mm,
   R.drawable.nn, R.drawable.oo, };

 public CustomEmojis(Activity act) {
  activity = act;
  inflater = (LayoutInflater) activity
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 @Override
 public int getCount() {
  return images.length;
 }

 @Override
 public Object getItem(int position) {
  return position;
 }

 @Override
 public long getItemId(int position) {
  return position;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  ViewHolder holder;
  if (convertView == null) {
   holder = new ViewHolder();
   convertView = inflater.inflate(R.layout.grid_row, null);
   holder.imageView = (ImageView) convertView
     .findViewById(R.id.imageView1);
   convertView.setTag(holder);
  } else {
   holder = (ViewHolder) convertView.getTag();
  }
  holder.imageView.setImageResource(images[position]);
  return convertView;
 }

 public static class ViewHolder {
  public ImageView imageView;
 }

}

above i post a 3 useful file for project.now its up to YOU how you can made a chat application in android Now after completion of the project you can see the below screens in you project


you can download a full source code here 

Monday, September 17, 2012

Exapand - Collapse Android TextView.

Hello,
Here I want to share some knowledge about android textview. Android Textview is a very Useful element in your application.
If you want to make functionality like expand - collapse of textview it is easy after end of this article you can make this functionality.

I guess,you have a basic knowledge of Android technology. Than you can easily grasp this article

e.g. If you want to expand or collapse your textview like in  below is image of Play store app.



Here I am only describe that how more/less button functionality are work. 
first of all in your activity_main.xml file paste below code.
activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/description_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="5"
            android:text="@string/desc_content" />

        <ImageButton
            android:id="@+id/show"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/description_text"
            android:background="@drawable/arrow_down"
            android:clickable="true" />

        <View
            android:id="@+id/view1"
            android:layout_width="wrap_content"
            android:layout_height="2dp"
            android:layout_below="@+id/description_text"
            android:layout_marginTop="5dp"
            android:layout_toLeftOf="@+id/show"
            android:background="#000" />

        <ImageButton
            android:id="@+id/hide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/description_text"
            android:background="@drawable/arrow_up"
            android:clickable="true"
            android:visibility="invisible" />
    </RelativeLayout>

</ScrollView>


now open your main java file and paste below code
MainActivity.java

package com.example.expand.textview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView descText;
ImageButton show, hide;

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

descText = (TextView) findViewById(R.id.description_text);
show = (ImageButton) findViewById(R.id.show);
show.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
System.out.println("Show button");
show.setVisibility(View.INVISIBLE);
hide.setVisibility(View.VISIBLE);
descText.setMaxLines(Integer.MAX_VALUE);

}
});
hide = (ImageButton) findViewById(R.id.hide);
hide.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
System.out.println("Hide button");
hide.setVisibility(View.INVISIBLE);
show.setVisibility(View.VISIBLE);
descText.setMaxLines(5);

}
});

}

}

and finally change your string.xml file
string.xml

<resources>

    <string name="app_name">Expand TextView</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="desc_content">    Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It\'s the largest installed base of any mobile platform and growing fast—every day another million users power up their Android devices for the first time and start looking for apps, games, and other digital content.

Android gives you a world-class platform for creating apps and games for Android users everywhere, as well as an open marketplace for distributing to them instantly.
</string>

</resources>

and run your Project It will give you below output.