Android - Tips

From XennisWiki
Jump to: navigation, search

This article shows some tips for developing Android apps.

Basic

Create log messages

Further information: Android Guide - Log

public static final String TAG = "MyTag";

[...]

Log.i(TAG, "my info message");
Log.d(TAG, "my debug message");
Log.w(TAG, "my warn message");
Log.e(TAG, "my error message");

String with variable integer

res/values/strings.xml

<resources>
    [...]
    <string name="radius_output">Radius: %1$dm</string>
</resources>

res/layout/fragment_main.xml

        [...]
        <TextView
            android:id="@+id/seekBarProgressOutput"
            android:text="@string/radius_output" />
        [...]

src/.../MainActivity.java

[...]
TextView form_radius_output = (TextView) rootView.findViewById(R.id.seekBarProgressOutput);
// Set text to: Radius: 200m
form_radius_output.setText(String.format(rootView.getResources().getString(R.string.radius_output), 200));
[...]

Get assets files

Code snippet, that prints all files from the assets folder:

AssetManager aw = getApplicationContext().getAssets();
try {
	String[] files = aw.list("");
        Log.d(TAG, "files: " + Arrays.toString(files));
} catch (IOException e) {
	e.printStackTrace();
}

Advanced

Asynchronous task

see Android Guide - AsyncTask

Write data into file

String filename = "myFile.txt";
OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(filename, Context.MODE_PRIVATE)
osw.write("HelloWorld");
osw.close();

// Get this file
File myFile = new File(getFilesDir(), filename);
Log.i(TAG, myFile.getAbsolutePath() + ", " + myFile.length() / 1000 + " MB");

SQL database

DatabaseHelper.java

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
	 
    // Tag
	public static final String TAG = "DatabaseHelper";
 
    // Database Version
    private static final int DATABASE_VERSION = 1;
 
    // Database Name
    private static final String DATABASE_NAME = "my_db";
 
    // Table Names
    private static final String TABLE_CARS = "cars";
 
    // Common column names
    private static final String KEY_ID = "id";
 
    // INKS Table - column names
	private static final String KEY_MODEL = "modell";
    private static final String KEY_TEXT = "text";
 
    // Table Create Statements
    // Inks table create statement
    private static final String CREATE_TABLE_CARS = "CREATE TABLE "
            + TABLE_CARS + "("
    		+ KEY_ID + " INTEGER PRIMARY KEY,"
    		+ KEY_MODEL + " DATE,"
    		+ KEY_TEXT + " TEXT)";
  
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
 
/*  @Override
    public void onOpen(SQLiteDatabase db) {
        int iversion = db.getVersion();
        if (iversion == 1) {
            onUpgrade(db, 1, 2);
        }
    }    
  */  
    @Override
    public void onCreate(SQLiteDatabase db) {
    	Log.w(this.getClass().getName(), "create db");
        // creating required tables
        db.execSQL(CREATE_TABLE_CARS);
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CARS);
 
        // create new tables
        onCreate(db);
    }
    
    // closing database
    public void closeDB() {
        SQLiteDatabase db = this.getReadableDatabase();
        if (db != null && db.isOpen())
            db.close();
    }    
    
	/**
	 * Inserts a car into the database.
	 * 
	 * @param ink
	 *            Ink
	 * @return True, if insert was successful
	 */
    public boolean insertInk(int id, String text, String model) {
        SQLiteDatabase db = this.getWritableDatabase();
     
        ContentValues values = new ContentValues();
        values.put(KEY_ID, id);
        values.put(KEY_TEXT, text);
        values.put(KEY_MODEL, model);
        
        // insert row, returns: the row ID of the newly inserted row, or -1 if an error occurred 
        try {
            long row_id = db.insert(TABLE_CARS, null, values);
            return row_id > 0;
        } catch (Exception e) {
        	Log.e(TAG, "SQLiteConstraintException, can't insert car");
        }

        return false;

    }
    

    /**
     * Get all stored cars.
     * 
     * @return All stored cars
     */
    public List getInkList() {
        List carList = new ArrayList();
        String selectQuery = "SELECT  * FROM " + TABLE_CARS;
     
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);
     
        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
            	int id = c.getInt((c.getColumnIndex(KEY_ID)));
            	String text = c.getString(c.getColumnIndex(KEY_TEXT));
            	String model = c.getString(c.getColumnIndex(KEY_MODEL));
            	
//            	carList.add(...);
            } while (c.moveToNext());
        }
     
        return carList;
    }
    

    public void clearTableInk() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CARS, KEY_ID + " >= ?", new String[] { String.valueOf(0) });
    }
    
    /**
     * Delete specific car.
     * 
     * @param id Delete an car
     */
    public void deleteInk(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CARS, KEY_ID + " = ?", new String[] { String.valueOf(id) });
    }    
}

View

Show toast

Further information: Android Guide - Toasts

Toast.makeText(getApplicationContext(), "My text here", Toast.LENGTH_SHORT).show();

Create an option menu

Further information: Android Guide - Menus, How to Create Android Menus

In this example we create a option menu with a settings and a about icon. From the official Android page you can download the Action Bar Icon Pack which includes a number of icons.

res/menu/options.xml (you could also use a different name)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item android:id="@+id/menu_settings"
          android:icon="@drawable/ic_action_settings"
          android:title="Settings" />
 
    <item android:id="@+id/menu_about"
          android:icon="@drawable/ic_action_about"
          android:title="About" />
 
</menu>

src/MainActivity.java

public class MainActivity extends FragmentActivity {

    [...]

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_settings:
            	 Toast.makeText(getApplicationContext(), "Settings is selected", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menu_about:
            	 Toast.makeText(getApplicationContext(), "About is selected", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

Create swipe view with tabs

see Creating Swipe Views with Tabs

Further information: public void setOffscreenPageLimit (int limit)

/*
 * Set the number of pages that should be retained to either side of thet
 * 3 = Number of pages which will be kept offscreen in an idle state.
 */
mViewPager.setOffscreenPageLimit(3);

Date and time picker

Further information: DatePicker, TimePicker

src/MY-FRAGMENT.java

import java.util.Calendar;
import java.util.Date;

import android.widget.DatePicker;
import android.widget.TimePicker;

// [...]

// ----------------- get elements -----------------
CheckBox form_time = (TimePicker) rootView.findViewById(R.id.timePicker1);
TimePicker form_date = (DatePicker) rootView.findViewById(R.id.datePicker1);

// ----------------- settings -----------------
form_time .setIs24HourView(true);
form_date .setCalendarViewShown(false);

// ----------------- get datetime -----------------
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, form_expire_date.getYear());
cal.set(Calendar.MONTH, form_expire_date.getMonth());
cal.set(Calendar.DATE, form_expire_date.getDayOfMonth());
cal.set(Calendar.HOUR_OF_DAY, form_expire_time.getCurrentHour());
cal.set(Calendar.MINUTE, form_expire_time.getCurrentMinute());
Date dateFromPickers = cal.getTime();

Sytem.out.println(dateFromPickers);

res/layout/MY-FRAGMENT.xml

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

        <!-- .... -->

        <TimePicker
            android:id="@+id/timePicker1"
            android:layout_width="wrap_content"
            android:layout_height="93dp"
            android:layout_weight="0.13" />

        <DatePicker
            android:id="@+id/datePicker1"
            android:layout_width="262dp"
            android:layout_height="116dp" />

</FrameLayout>

Libraries

Android libraries
Name Description
Android-PullToRefresh Update app when pull down (or up)
Android Asynchronous Http Client Asynchronous HTTP Client
google-http-java-client HTTP Client
Retrofit REST Client
Little Fluffy Location Library Location Updates

See also