viernes, 29 de marzo de 2013

Android: Time ago...

Today I was using this very useful function from Android API for calculating time ago (added in Api Level 3) I decided to write it down here because it's a very common functionality (since I guess Facebook came up with the idea, years ago)

Code:

long minResolution = 1000;

long transitionResolution = 1000;


long ago = 1364503132624L;
String strAgo = DateUtils.getRelativeDateTimeString(
    this, ago, minResolution, transitionResolution, 0).toString();
System.out.println("How ago: " + strAgo );

This will output: 16 hours ago.

(16 will vary since the value 1364503132624L is not from 16 hours ago)

If you change the values for minResolution, you will tell Android how much or less you want to inform as minimun value. For example, if you need to report only how many hours ago has passed, then you should change this value to:

long minResolution = 60 * 60 * 1000; // 1 hour in millisecs

After doing that, you will start getting reports only when at least 1 hour has passed (before that you will get "0 hours ago")

Full documentation:
http://developer.android.com/reference/android/text/format/DateUtils.html


jueves, 28 de marzo de 2013

Android programming: FileDialog and Base64

A very common task for all developers is to look for files on disk and then process them (maybe even send them to a server in the Internet)

For this tutorial I'm using the following project (it's included here for download)
https://code.google.com/p/android-file-dialog/

Steps to get all your files into Eclipse:

1) Download both ZIP files. Import into Eclipse as an existing project.
2) Set this project as Android Library.

3) Uncompress AttachFilesDemo.zip and import it like the one before.
4) Define that you will use FileDialog as a library.

Notice that if you use Android 2.1, Base64 is not supported (it was included in 2.2) so here in this tutorial you will find a Base64.java taken from: http://iharder.sourceforge.net/current/index.html

The code is pretty well commented and I hope you can do great applications with it :-)

Download links:
http://www.WalterRodriguez.info/uploads/FileExplorer.zip
http://www.WalterRodriguez.info/uploads/AttachFilesDemo.zip

miércoles, 27 de marzo de 2013

Beginning Android programming: Dealing with Checkboxes


Today I developed a sample code to explain how to create, use and control checkboxes created in Android via programming (and not using XML layouts)

I decided to write this down because it has nothing to do with Android programming, it has to do with programming in general.

The final result will be like the image below:


In your layout you need to have a LinearLayout where to put all the new elements:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layoutBase"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
</LinearLayout>

Next, write the following code in your Activity (change as you need for your specific project):

package com.example.test;

import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity 
{
    Context context;
    
    /**
     * Vector for storing checkboxes and use later
     */
    Vector<CheckBoxCreatedModel> vectorWithCheckboxes = new Vector<CheckBoxCreatedModel>();
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = getApplicationContext();
        
        // Vector with all the info about the checkbox to be created
        Vector<CheckboxModel> vectorWithInfo = new Vector<CheckboxModel>();
        
        CheckboxModel model = new CheckboxModel();
        model.id = "1";
        model.name = "Uno";
        model.enabled = true;
        model.checked = true;
        vectorWithInfo.add( model );
        
        model = new CheckboxModel();
        model.id = "2";
        model.name = "Dos";
        model.enabled = true;
        model.checked = true;
        vectorWithInfo.add( model );
        
        model = new CheckboxModel();
        model.id = "3";
        model.name = "Tres";
        model.enabled = false;
        model.checked = true;
        vectorWithInfo.add( model );
        
        LinearLayout layoutBase = (LinearLayout)findViewById(R.id.layoutBase);
        addCheckbox(vectorWithInfo, layoutBase);
    }

    private void addCheckbox(Vector<CheckboxModel> vectorWithInfo, LinearLayout addToView)
    {
    for ( int i=0; i < vectorWithInfo.size(); i++ )
    {
    // Model with data 
    CheckboxModel model = vectorWithInfo.elementAt(i);
   
    // Create a new LinearLayout for adding the elements
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.HORIZONTAL);
    addToView.addView(ll);
   
    // Create a checkbox
    CheckBox check = new CheckBox(this);
    ll.addView(check);
    check.setEnabled( model.enabled );
    check.setChecked( model.checked);
   
    // Create a TextView as a label for the checkbox
    TextView tv = new TextView(this);
    tv.setText(model.name);
    ll.addView(tv);
   
    // Create a model for adding it to our Vector
    CheckBoxCreatedModel cbcm = new CheckBoxCreatedModel();
    cbcm.model = model;
    cbcm.ll = ll;
    cbcm.check = check;
    cbcm.tv = tv;
   
    // Add this model to Vector so I can access it anytime from anywhere
    vectorWithCheckboxes.addElement(cbcm);
    }
    }
    
    class CheckBoxCreatedModel
    {
    public CheckboxModel model;
    public LinearLayout ll;
    public CheckBox check;
    public TextView tv;
    }
    
    /**
     * Model class for creating a checkbox.
     * (you should use all the variables as you please)
     */
    class CheckboxModel 
    {
    public String name;
    public String id;
    public boolean enabled = false;
    public boolean checked = false;
    }
}

Hope you understand and lern something about it.


viernes, 22 de marzo de 2013

PHP: XML to Array

I just found this excellent peace of code. It transforms XML to PHP ARray. And from that you can build a JSON too (which is what I need)

There are other methods, sure. But this is the one I was looking for :-)

Thanks to http://stackoverflow.com/users/445500/nexusrex

<?php
/**
 * Convert XML to an Array
 *
 * @param string  $XML
 * @return array
 */
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close') {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete') {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while ($start_level < $x_level) {
            $php_stmt .= '[$level['.$start_level.']]';
            if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
            $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
            $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes', $xml_elem)) {
            if (isset($xml_elem['value'])) {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value) {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
    return $xml_array;
}
?>