private String[] arrListCity;
arrListCity = getResources().getStringArray(R.array.list_city_new);
public void prepareArrayLits()
{
itemList = new ArrayList<Object>();
for(int i=0; i< arrListCity.length; i++)
{
Log.w(">>>>>>>>>>> test array", arrListCity[i]);
AddObjectToList(R.drawable.arrow, arrListCity[i], "Kim Tuyến run rẩy khi chụp ảnh với nhện - VN's Next Top Model");
}
}
Wednesday, November 2, 2011
Wednesday, October 26, 2011
Shared Preferences button back splash with android exam
//Splash
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = app_preferences.getInt("check", 1);
}
//
protected void onResume() {
// TODO Auto-generated method stub
if(check==1){
newTimerCounter(3);
}else {
finish();
}
super.onResume();
}
//Activity Main
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
SplashActivity.check = 0;
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = app_preferences.getInt("check", 1);
}
//
protected void onResume() {
// TODO Auto-generated method stub
if(check==1){
newTimerCounter(3);
}else {
finish();
}
super.onResume();
}
//Activity Main
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
SplashActivity.check = 0;
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
send Bundle value intent with android exam
//Activity 1
public void onClick(View arg0) {
long value;
if (tinhthanh == 0) {
value = 1;
}
else {
value = 0;
}
Bundle sendBundle = new Bundle();
sendBundle.putLong("value", value);
Intent i = new Intent(VNTaxiCallActivity.this, ListTaxi.class);
i.putExtras(sendBundle);
startActivity(i);
overridePendingTransition( R.anim.slide_in_left, R.anim.slide_out_left );
}
//Activity 2
Bundle receiveBundle = this.getIntent().getExtras();
final long int_tinhthanh = receiveBundle.getLong("value");
lblHeader = (TextView) findViewById(R.id.lblHeaderCity);
if(int_tinhthanh==1){
Taxi_HaNoi();
} else if (int_tinhthanh==2) {
Taxi_DaNang();
} else if (int_tinhthanh==3) {
Taxi_HCM();
}else {
Taxi_CanTho();
}
public void onClick(View arg0) {
long value;
if (tinhthanh == 0) {
value = 1;
}
else {
value = 0;
}
Bundle sendBundle = new Bundle();
sendBundle.putLong("value", value);
Intent i = new Intent(VNTaxiCallActivity.this, ListTaxi.class);
i.putExtras(sendBundle);
startActivity(i);
overridePendingTransition( R.anim.slide_in_left, R.anim.slide_out_left );
}
//Activity 2
Bundle receiveBundle = this.getIntent().getExtras();
final long int_tinhthanh = receiveBundle.getLong("value");
lblHeader = (TextView) findViewById(R.id.lblHeaderCity);
if(int_tinhthanh==1){
Taxi_HaNoi();
} else if (int_tinhthanh==2) {
Taxi_DaNang();
} else if (int_tinhthanh==3) {
Taxi_HCM();
}else {
Taxi_CanTho();
}
sort abc listview adapter android exam
java.util.Arrays.sort(arrListCity, java.text.Collator.getInstance(new Locale("vi")));
Friday, October 21, 2011
exit app android exam
private void quitApplication() {
try {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> process = manager
.getRunningAppProcesses();
int pid = 0;
for (RunningAppProcessInfo runningAppProcessInfo : process) {
if (runningAppProcessInfo.processName
.equals(this.getPackageName())) {
pid = runningAppProcessInfo.pid;
break;
}
}
android.os.Process.killProcess(pid);
} catch (Exception e) {
Log.e(TAG, TAG + e);
}
}
try {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> process = manager
.getRunningAppProcesses();
int pid = 0;
for (RunningAppProcessInfo runningAppProcessInfo : process) {
if (runningAppProcessInfo.processName
.equals(this.getPackageName())) {
pid = runningAppProcessInfo.pid;
break;
}
}
android.os.Process.killProcess(pid);
} catch (Exception e) {
Log.e(TAG, TAG + e);
}
}
Thursday, October 13, 2011
ListViewAdapter android exam
/*public void initComponent()
{
lblHeader = (TextView)findViewById(R.id.lblHeaderCity);
lvCity = (ListView)findViewById(R.id.lvCity);
arrListCity = getResources().getStringArray(R.array.list_city_central);
lblHeader.setText(R.string.central);
ListViewAdapter adapter = new ListViewAdapter(this, arrListCity);
lvCity.setAdapter(adapter);
}*/
{
lblHeader = (TextView)findViewById(R.id.lblHeaderCity);
lvCity = (ListView)findViewById(R.id.lvCity);
arrListCity = getResources().getStringArray(R.array.list_city_central);
lblHeader.setText(R.string.central);
ListViewAdapter adapter = new ListViewAdapter(this, arrListCity);
lvCity.setAdapter(adapter);
}*/
Labels:
AbsoluteLayout,
Android Button Status test
Monday, October 3, 2011
Android: Quickly building a menu for an application
After creating an Android Project in Eclipse called “AndroidMenus” I
then set about creating a new XML file in a folder (you need to create
this folder) called “menu” under the “res” (parent) folder. I named the
xml file “mymenu.xml” and added this:
As you can see we need to make sure we have some icons for the menu
as well as some menu item strings in the strings.xml file which is
located in the “res/values” folder. Here is my modified strings.xml
file:
The “main.xml” file can be left just as the project wizard created it
however you need to modify the “AndroidMenus.java” file to override the
onCreateOptionsMenu method.
You also need to create some icons and place them into the appropriate folders as seen below:
Once you’ve got this done you can run the project. In the emulator press the “Menu” button to trigger the menu.
Results:
Yes its pretty ugly but like I said I’m not a graphics person. If you click on the menu items nothing happens, lets change this now by adding some Java code to the “AndroidMenus.java” file. For this we need to override the onOptionsItemSelected method.
You can see with the code depending what choice is made is reflected with a quick toast notification.
Results:
Full download
<? xml version = "1.0" encoding = "utf-8" ?> < menu xmlns:android = "http://schemas.android.com/apk/res/android" > < item android:id = "@+id/menuItem1" android:icon = "@drawable/menu_item1" android:title = "@string/menu_item1" /> < item android:id = "@+id/menuItem2" android:icon = "@drawable/menu_item2" android:title = "@string/menu_item2" /> </ menu > |
<? xml version = "1.0" encoding = "utf-8" ?> < resources > < string name = "hello" >Hello World, AndroidMenus!</ string > < string name = "app_name" >Android Menus</ string > < string name = "menu_item1" >Item 1</ string > < string name = "menu_item2" >Item 2</ string > </ resources > |
package com.giantflyingsaucer; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; public class AndroidMenus extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.mymenu, menu); return true ; } } |
Once you’ve got this done you can run the project. In the emulator press the “Menu” button to trigger the menu.
Results:
Yes its pretty ugly but like I said I’m not a graphics person. If you click on the menu items nothing happens, lets change this now by adding some Java code to the “AndroidMenus.java” file. For this we need to override the onOptionsItemSelected method.
package com.giantflyingsaucer; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; public class AndroidMenus extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.mymenu, menu); return true ; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menuItem1: Toast.makeText(AndroidMenus. this , "Menu Item 1 was pressed" , 3000 ).show(); return true ; case R.id.menuItem2: Toast.makeText(AndroidMenus. this , "Menu Item 2 was pressed" , 3000 ).show(); return true ; default : return super .onOptionsItemSelected(item); } } } |
Results:
Full download
Using SQLite with Android to power an AutoComplete textbox
Like my previous Android article make sure you have the Android SDK and Eclipse tools for Android all setup and configured.
I created a new Android Project in Eclipse and called it “UsingSQLite”. I used Android 1.6 as my target but you can use a newer version of Android if you wish.
The first thing to do is create a new file called “list_item.xml” inside of the “layout” folder.
Add the following XML to it:
That file contains the TextView that will be used to hold the autocomplete data.
Now go into the “main.xml” file and modify it like so:
That gives you a label (well a textview really) that says “Country”
and the autocomplete textview. You might also notice I’m pulling some
data from the string resources so you need to update the “strings.xml”
(located in the “values” folder) to this:
That it for the XML we need to add and edit. We can move onto the
class that will do most of the heavy lifting as far as using the SQLite
database. Keep in mind I’ve tailored this class to be specific to
simply loading and storing the “Countries” data. You can broaden out
the code when your comfortable with it and improve on it and make it
more generic if you wish. For now all I want is the ability to put in
some country names and get them back to populate the autocomplete
textview.
Here is the code for “SQLiteCountryAssistant.java”:
The SQLite database table is very simple. An auto-incrementing id
field and a text field to hold the country name. Because I extend
SQLiteOpenHelper I also needed to implement the onCreate and onUpgrade
methods. The “onCreate” function simply creates the database if it
doesn’t exist.
Note: The logging will show up in the “DDMS” perspective in Eclipse under the “LogCat” tab.
Then there are the standard methods to accomplish DB work such as “insertCountry”, “removeCountry”, “updateCountry”, and finally “getAllCountries”. Most of this should be pretty straight forward and I’ve tried to make it as easy to understand as possible even being more verbose than required for the sake of clarity.
Finally going back to the main activity class “UsingSQLite.java”:
We start off creating an instance of the the “SQLiteCountryAssistant”
class and then plug some default countries into it. You’ll also notice
there is some commented out code you can fiddle with the test out the
remove and update functionality. I print the returned countries out to
the log and then pass them onto the AutoComplete TextView via an ArrayAdapter.
Before you run the project make sure to go into the run configuration and make the following changes as this will clear the database each time you run the Android emulator.
Now you can run the project and hopefully see something like this if all went well.
I created a new Android Project in Eclipse and called it “UsingSQLite”. I used Android 1.6 as my target but you can use a newer version of Android if you wish.
The first thing to do is create a new file called “list_item.xml” inside of the “layout” folder.
Add the following XML to it:
<? xml version = "1.0" encoding = "utf-8" ?> < TextView xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:padding = "10dp" android:textSize = "16sp" android:textColor = "#000" > </ TextView > |
Now go into the “main.xml” file and modify it like so:
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:padding = "5dp" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "@string/COUNTRY_LABEL" /> < AutoCompleteTextView android:id = "@+id/autocompleteCountry" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:layout_marginLeft = "5dp" /> </ LinearLayout > |
<? xml version = "1.0" encoding = "utf-8" ?> < resources > < string name = "hello" >Hello World, UsingSQLite!</ string > < string name = "app_name" >Using SQLite</ string > < string name = "COUNTRY_LABEL" >Country</ string > </ resources > |
Here is the code for “SQLiteCountryAssistant.java”:
package com.giantflyingsaucer; import android.database.*; import android.database.sqlite.*; import android.content.ContentValues; import android.content.Context; import android.util.Log; public class SQLiteCountryAssistant extends SQLiteOpenHelper { private static final String DB_NAME = "usingsqlite.db" ; private static final int DB_VERSION_NUMBER = 1 ; private static final String DB_TABLE_NAME = "countries" ; private static final String DB_COLUMN_1_NAME = "country_name" ; private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME + " (_id integer primary key autoincrement, country_name text not null);)" ; private SQLiteDatabase sqliteDBInstance = null ; public SQLiteCountryAssistant(Context context) { super (context, DB_NAME, null , DB_VERSION_NUMBER); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO: Implement onUpgrade } @Override public void onCreate(SQLiteDatabase sqliteDBInstance) { Log.i( "onCreate" , "Creating the database..." ); sqliteDBInstance.execSQL(DB_CREATE_SCRIPT); } public void openDB() throws SQLException { Log.i( "openDB" , "Checking sqliteDBInstance..." ); if ( this .sqliteDBInstance == null ) { Log.i( "openDB" , "Creating sqliteDBInstance..." ); this .sqliteDBInstance = this .getWritableDatabase(); } } public void closeDB() { if ( this .sqliteDBInstance != null ) { if ( this .sqliteDBInstance.isOpen()) this .sqliteDBInstance.close(); } } public long insertCountry(String countryName) { ContentValues contentValues = new ContentValues(); contentValues.put(DB_COLUMN_1_NAME, countryName); Log.i( this .toString() + " - insertCountry" , "Inserting: " + countryName); return this .sqliteDBInstance.insert(DB_TABLE_NAME, null , contentValues); } public boolean removeCountry(String countryName) { int result = this .sqliteDBInstance.delete(DB_TABLE_NAME, "country_name='" + countryName + "'" , null ); if (result > 0 ) return true ; else return false ; } public long updateCountry(String oldCountryName, String newCountryName) { ContentValues contentValues = new ContentValues(); contentValues.put(DB_COLUMN_1_NAME, newCountryName); return this .sqliteDBInstance.update(DB_TABLE_NAME, contentValues, "country_name='" + oldCountryName + "'" , null ); } public String[] getAllCountries() { Cursor cursor = this .sqliteDBInstance.query(DB_TABLE_NAME, new String[] {DB_COLUMN_1_NAME}, null , null , null , null , null ); if (cursor.getCount() > 0 ) { String[] str = new String[cursor.getCount()]; int i = 0 ; while (cursor.moveToNext()) { str[i] = cursor.getString(cursor.getColumnIndex(DB_COLUMN_1_NAME)); i++; } return str; } else { return new String[] {}; } } } |
Log.i( "onCreate" , "Creating the database..." ); sqliteDBInstance.execSQL(DB_CREATE_SCRIPT); |
Then there are the standard methods to accomplish DB work such as “insertCountry”, “removeCountry”, “updateCountry”, and finally “getAllCountries”. Most of this should be pretty straight forward and I’ve tried to make it as easy to understand as possible even being more verbose than required for the sake of clarity.
Finally going back to the main activity class “UsingSQLite.java”:
package com.giantflyingsaucer; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; public class UsingSQLite extends Activity { private SQLiteCountryAssistant sqlliteCountryAssistant; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocompleteCountry); sqlliteCountryAssistant = new SQLiteCountryAssistant(UsingSQLite. this ); sqlliteCountryAssistant.openDB(); // Insert a few countries that begin with "C" sqlliteCountryAssistant.insertCountry( "Cambodia" ); sqlliteCountryAssistant.insertCountry( "Cameroon" ); sqlliteCountryAssistant.insertCountry( "Canada" ); sqlliteCountryAssistant.insertCountry( "Cape Verde" ); sqlliteCountryAssistant.insertCountry( "Cayman Islands" ); sqlliteCountryAssistant.insertCountry( "Chad" ); sqlliteCountryAssistant.insertCountry( "Chile" ); sqlliteCountryAssistant.insertCountry( "China" ); //sqlliteCountryAssistant.removeCountry("Chad"); //sqlliteCountryAssistant.updateCountry("Canada", "Costa Rica"); String[] countries = sqlliteCountryAssistant.getAllCountries(); // Print out the values to the log for ( int i = 0 ; i < countries.length; i++) { Log.i( this .toString(), countries[i]); } ArrayAdapter<String> adapter = new ArrayAdapter<String>( this , R.layout.list_item, countries); textView.setAdapter(adapter); } public void onDestroy() { super .onDestroy(); sqlliteCountryAssistant.close(); } } |
Before you run the project make sure to go into the run configuration and make the following changes as this will clear the database each time you run the Android emulator.
Now you can run the project and hopefully see something like this if all went well.
Android: Displaying a status bar notification message
First, I created an Android project called “AndroidNotifications”.
The code is fairly simple so I’ll dump it here in it’s complete form:
The NOTIFICATION_ID allows you to grab the notification and remove it via your code if needed. Using a TimerTask
I made it so that the notification shows up after 3 seconds from when
the button is clicked. The real magic happens in the
“triggerNotification()” method. The code is not complex and is pretty
much the most minimal example I could come up with and keeping it pretty
clear.
Here is the main.xml:
Keep in mind you can also make the LED lights, play a sound or use
the vibration feature to also notify the user. Just make sure not to
let your Android app get “annoying”. Better yet in your application let
the user choose how they want to be notified via custom settings or
default settings, etc.
Here is the final result:
The code is fairly simple so I’ll dump it here in it’s complete form:
package com.giantflyingsaucer; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class AndroidNotifications extends Activity { private final int NOTIFICATION_ID = 1010 ; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button)findViewById(R.id.createNotificationButton); btn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { triggerNotification(); } }; timer.schedule(timerTask, 3000 ); } }); } private void triggerNotification() { CharSequence title = "Hello" ; CharSequence message = "Hello, Android!" ; NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon, "A New Message!" , System.currentTimeMillis()); Intent notificationIntent = new Intent( this , AndroidNotifications. class ); PendingIntent pendingIntent = PendingIntent.getActivity( this , 0 , notificationIntent, 0 ); notification.setLatestEventInfo(AndroidNotifications. this , title, message, pendingIntent); notificationManager.notify(NOTIFICATION_ID, notification); } } |
Here is the main.xml:
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > < Button android:id = "@+id/createNotificationButton" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Create Notification" android:padding = "10dp" /> </ LinearLayout > |
Here is the final result:
TextView font size color layout interface andoid exam
I created a new Android Project in Eclipse called “AndroidFonts”:
From here I modified the “main.xml” file in the layout folder.
When I run the project I get this result in the emulator:
As you can see from the code I used the fonts: sans, serif, and monospace. Then I showed off how to make a string bold and italic:
Then a string utilizing the shadowing effect:
Colors are as simple as adding:
Pretty easy!
From here I modified the “main.xml” file in the layout folder.
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "MonoSpace Font:" android:textSize = "16sp" android:paddingLeft = "5sp" /> < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:paddingLeft = "5sp" android:typeface = "monospace" android:text = "Hello Red Monospace" android:textSize = "16sp" android:textColor = "#ff0000" /> < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "Sans Font:" android:textSize = "16sp" android:paddingLeft = "5sp" /> < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:paddingLeft = "5sp" android:typeface = "sans" android:text = "Hello Blue Sans" android:textSize = "16sp" android:textColor = "#0000ff" /> < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "Serif Font:" android:textSize = "16sp" android:paddingLeft = "5sp" /> < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:paddingLeft = "5sp" android:paddingRight = "2sp" android:typeface = "serif" android:text = "Hello Green Serif" android:textSize = "16sp" android:textColor = "#00ff00" /> < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:paddingLeft = "5sp" android:paddingTop = "15sp" android:typeface = "normal" android:text = "I'm normal font but I'm also bold and italic" android:textSize = "16sp" android:textStyle = "bold|italic" android:textColor = "#ffffff" /> < TextView android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:paddingLeft = "5sp" android:paddingTop = "15sp" android:paddingBottom = "15sp" android:typeface = "normal" android:text = "I'm normal (bold) font but I have a shadow" android:textSize = "16sp" android:textStyle = "bold" android:shadowColor = "#0f0f0f" android:shadowRadius = "1.6" android:shadowDx = "1.5" android:shadowDy = "1.3" android:textColor = "#000000" android:background = "#ffffff" /> </ LinearLayout > |
As you can see from the code I used the fonts: sans, serif, and monospace. Then I showed off how to make a string bold and italic:
android:textStyle="bold|italic" |
android:shadowColor ="#0f0f0f" android:shadowRadius="1.6" android:shadowDx="1.5" android:shadowDy="1.3" |
android:textColor="#ff0000" |
Subscribe to:
Posts (Atom)