RSS
 

onChange event on EditText in Android

09 ott

Sooner or later you’ll have to deal with it. If you’re an html developer and you write also in javascript you’ll surely know the onchange event.

Unfortunately it’s a little bit tricky to find the same event on android.

The onChange event is helpful when you’ve to deal with the following things:

  • Let the user know (in realtime) how many characters he typed.
  • Let the user know (in realtime) how many remaining characters he is allowed to type.
  • Make realtime processing of the content ( like sending it online and fetch some partial results of the partial typed edittext )

You’ve to implement your own instance of TextWatcher and let the edittext know that you want to be notified at each change by calling the method EditText.addTextChangedListener.

Below i will give you a simple example ( it’s written on the fly but you’ll understand the idea )

			((EditText)findViewById(R.id.et_testo)).addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
				((TextView)findViewById(R.id.numcaratteri)).setText(String.format(getString(R.string.caratteri), s.length()));

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

		});
 

Android Root Certification Authorities List

23 set

Since it was a little hard for me finding it, here you can find the trusted CAs in Android 2.2 Froyo.

In order to get my result on each android device you’ve to download this file and place it on $JAVA_HOME/lib/ext . Plus, you should have $JAVA_HOME/bin in your $PATH

adb pull /system/etc/security/cacerts.bks cacerts.bks
keystore cacerts.bks -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider -storepass changeit -list -v >> certificates.txt

After the break my certificates.txt.
Read the rest of this entry »

 
4 Comments

Posted in Android

 

Reading $_GET variable on CODEIGNITER

14 ago

There are multiple solutions out there but i did create my own.

It’s simple as 1,2,3. Hope it helps.

		// CODEIGNITER HACK
		$tmp = explode('?',$_SERVER['REQUEST_URI']);
		$tmp = explode('&', $tmp[1]);

		foreach($tmp as $keyval) {
			$tmpAppoggio = explode('=', $keyval);
			$_GET[urldecode($tmpAppoggio[0])]=urldecode($tmpAppoggio[1]);
		}
		// end of codeigniter hack
 
 

Write an SMS without sending it on Android 2.2 Froyo

12 ago

I just figured out how to write an sms without sending it really on android froyo 2.2 using the content provider.

I’ll write only the snippet here. Hope it helps

	/**
	 * writes an sms on the contentprovider
	 * @param ctx Context
	 * @param mobNo mobile number
	 * @param msg text of the message
	 */
	private final static void storeMessage(Context ctx,String mobNo, String msg) {
		ContentValues values = new ContentValues();
		values.put("address", mobNo);
		values.put("body", msg);
		ctx.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
	}

Obviously you should set the right permissions on the manifest ( Yes the following are all needed for this task ) :

<manifest>
	....
	....
	<uses-permission android:name="android.permission.WRITE_SMS"></uses-permission>
	<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
</manifest>
 
1 Comment

Posted in Android

 

Add Events on Google Calendar on Android Froyo

09 ago

Since i started developing applications for android i noticed there were some undocumented apis. Google does reccomend to not use these apis but since there are no “other nice ways” to achieve some tasks sometimes they are useful ( but still unreccomended)

It’s the case of the Google Calendar Apis. Out there you can find a lot of docs about these undocumented & unsupported apis but you’ll get some troubles if google decides to change them.

For example if you want to add an “event” to the calendar programmatically you can follow the snippet below which is SDK proof. In fact i did ( It’s not refactored for better reading ) write some code that would work on Sdk from 1.5 to 2.2 ( aka Froyo ) solving the provider issue on froyo.

/**
 * Adds the event to a calendar. It lets the user choose the calendar
 * @param ctx Context ( Please use the application context )
 * @param title title of the event
 * @param dtstart Start time: The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
 * @param dtend End time: The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
 */
private static void addToCalendar(Context ctx, final String title, final long dtstart, final long dtend) {
	final ContentResolver cr = ctx.getContentResolver();
	Cursor cursor ;
	if (Integer.parseInt(Build.VERSION.SDK) == 8 )
		cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
	else
		cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
	if ( cursor.moveToFirst() ) {
		final String[] calNames = new String[cursor.getCount()];
		final int[] calIds = new int[cursor.getCount()];
		for (int i = 0; i < calNames.length; i++) {
			calIds[i] = cursor.getInt(0);
			calNames[i] = cursor.getString(1);
			cursor.moveToNext();
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		builder.setSingleChoiceItems(calNames, -1, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog,	int which) {
				ContentValues cv = new ContentValues();
				cv.put("calendar_id", calIds[which]);
				cv.put("title", title);
				cv.put("dtstart", dtstart );
				cv.put("hasAlarm", 1);
				cv.put("dtend", dtend);

				Uri newEvent ;
				if (Integer.parseInt(Build.VERSION.SDK) == 8 )
					newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
				else
					newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);

				if (newEvent != null) {
					long id = Long.parseLong( newEvent.getLastPathSegment() );
					ContentValues values = new ContentValues();
					values.put( "event_id", id );
					values.put( "method", 1 );
					values.put( "minutes", 15 ); // 15 minuti
					if (Integer.parseInt(Build.VERSION.SDK) == 8 )
						cr.insert( Uri.parse( "content://com.android.calendar/reminders" ), values );
					else
						cr.insert( Uri.parse( "content://calendar/reminders" ), values );

				}
				dialog.cancel();
			}

		});

		builder.create().show();
	}
	cursor.close();
}

Hope it helps to solve the problem about google calendar in froyo :)

Reference to the CP: Xda

 

Android Usefull Docs

27 lug

Today i surfed the web searching about guidelines and best practices on writing android apps. In this in-depth search i found some useful slides and tips:

1. Android Ui Design Guidelines

A slideshare with some usefull tips about android ui design:



2. Android Ui Stencil and PSDs

I also found a great resource where there are some other stencils and psds to download.

Link

3. Android icon templatepack

I also noticed the Google Android team released the icon template pack so you can easily design you’r own menus and icons using their psd with a lot of presets.

Link

 

How to use codeigniter with eclipse helios

24 giu

Codeigniter is a great framework. Eclipse is a very nice IDE. Why not using them both when writing our own apps ?

After some googling i found a way to get auto-completion with codeigniter on eclipse.

Requirements:

  1. Xampp : I suggest using xampp lite.
  2. Codeigniter: Obviously
  3. Eclipse Helios for PHP Development : :)

Read the rest of this entry »

 

How to manage custom post type category template on wordpress 3.0

18 giu

Today wordpress 3.0 has been released. Since i started to play with it almost immediately i found some troubles when i was trying to display all the post in the new wordpress custom type into one single page.

The goals:

  1. I wanted to create a custom template for these custom posts.
  2. I wanted to create a custom archive template for these custom posts

I found immediately the solution for the first “issue” . WordPress 3.0 templating system would search for a file named single-[custom post type name].php inside the theme directory so i simply copied and pasted the single.php into the new file and made some tiny modifications.

The second goal was a little bit difficult to achieve. I googled it and i found some articles talking about this issue but none of them gave  ma an easy and working solution.

So i decided to take some parts from them and make my own solution.

Note: The custom post type name is “androidapps”

I did create a new useless plugin that fixed my issues. the source coude is the following:

/*
Plugin Name: Androidapss
Plugin URI: http://i love you.com
Version: 1.0.78
Description: A very useless plugin
Author: Baccega Andrea
Author URI: http://www.andreabaccega.com
Tags: seo,google,link,optimization
*/
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');
add_action("template_redirect",'buch_template_redirect');
// Remember to flush_rules() when adding rules
function flushRules(){
	global $wp_rewrite;
   	$wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
	$newrules = array();
	$newrules['androidapps/feed/(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?&feed=$matches[1]&post_type=androidapps';
	$newrules['androidapps/(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?&feed=$matches[1]&post_type=androidapps';
	$newrules['androidapps/page/?([0-9]{1,})/?$'] = 'index.php?&paged=$matches[1]&post_type=androidapps';
	$newrules['androidapps/?$'] = 'index.php?paged=1&post_type=androidapps';
	return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'id');
    return $vars;
}

function buch_template_redirect()
{
	global $wp;

	$muley_custom_types = array("androidapps");

	if (in_array($wp->query_vars["post_type"], $muley_custom_types))
	{
		if ( is_robots() ) :
			do_action('do_robots');
			return;
		elseif ( is_feed() ) :
			do_feed();
			return;
		elseif ( is_trackback() ) :
			include( ABSPATH . 'wp-trackback.php' );
			return;
		elseif($wp->query_vars["name"]):
			include(TEMPLATEPATH . "/single-".$wp->query_vars["post_type"].".php");
			die();
		else:
			include(TEMPLATEPATH . "/".$wp->query_vars["post_type"].".php");
			die();
		endif;

	}
}

Well all the trick is done by two functions

  • buch_template_redirect
  • wp_insertMyRewriteRules

The first one buch_template_redirect would hack the template functions and would tell wordpress to search for

  • single-androidapps.php for single posts
  • androidapps.php for archive

The second wp_insertMyRewriteRules which is copied from the wordpress codex website would add some rewrite rules to wordpress so he will knows how to route the requests :) .

Now if you navigate through http://www.andreabaccega.com/androidapps you’ll see the archive template dedicated to the posts inside the “androidapps” type.

How would you use my code for your meanings?

Simply create a new plugin with the code above, then replace all those androidapps instances with your custom post type name.

Enjoy :)

 

5 Comments

Posted in Seo

 

Cpu al 100% e non trovate il motivo? Eccone uno

29 apr

Premetto che parlo da profano e quello che scriverò in quest’articolo potrebbe essere errato però io ho risolto il mio problema nel modo che andrò scrivendo perciò voglio raccontarvelo.

Cominciamo con il dire che ho avuto non pochi problemi con la riproduzione di video in alta qualità. Infatti, video in 720p erano diventati off-limits per me. Iniziai a pensare che il problema fosse relativo alla scheda video, che per inciso ha subito un operazione di esportazione della sua ventola di raffreddamento, perciò come prima soluzione logica andai subito in uno store e comprai una ati qualsiasi ( Tanto per quello che ne devo fare io ).

Una volta tornato a casa e dopo aver montato la scheda rimasi sorpreso come nulla cambiò. Perciò dopo essermi masturbato la mente con qualche pippa mentale arrivai alla conclusione che forse il mio pc era infetto da qualche virus che oltre ad infettare rompesse le palle alla cpu.

La soluzione fù quella di scaricare avg free e far partire una scansione che ovviamente diede risultati ( in tempi epici ) deludenti: Nel senso che non trovai nulla  di particolarmente significativo.

Perciò, rassegnato e con la convinzione di aver bisogno di un bel upgrade hardware spesi circa 450euro di nuovo hardware ( Per la cronaca: intel i5 750 , Asus P7H55-M Pro , Corsair 3x2GB 1600Mhz ).

Ma nel frattempo il mio pc diventava sempre più lento e inutilizzabile perciò decisi di comprare una bombola di aria compressa per pulirlo un po’ da quella polvere che nel tempo si accumula inesorabilmente sulle ventole e i dissipatori dei nostri pc.

Torno a casa , lo pulisco, lo riaccendo ed ecco che si presenta la sorpresa…. Quasi subito mi accorgo della differenza di velocità. Ora non solo posso guardare i video in 720p . Ma posso guardarne 3 contemporaneamente senza rallentamento alcuno … perciò ecco la spiegazione che mi sono dato:

Considerato il fatto che la polvere aveva fatto delle mie ventole e dissipatori la sua nuova casa,  le vie resipiratorie della cpu erano praticamente inesistenti e portavano i due core a temperature veramente impraticabili; quest’innalzamento della temperatura della cpu probabilmente causava uno scaling forzato della frequenza di clock ( Effettuato automaticamente dall’hardware nel tentativo di ridurre la temperatura della cpu ) . Perciò il mio pc, operando su ben altre frequenze da quelle alle quali ero abituato , era divenuto lentissimo.

Conclusione:

Prima di comprare del nuovo hardware, date una pulita a quello che avete già . Potrebbe, incredibilmente, aumentare le prestazioni del vostro pc.

 
4 Comments

Posted in Varie

 

Come configurare Nginx davanti ad apache per ottimizzare e velocizzare il caricamento dei vostri siti web

07 apr

Per prima cosa dovete aver già installato nginx e spostato apache su un altra porta/ip. Una volta fatta questa procedura bisognerà semplicemente configurare nginx in modo da istruirlo sul da-farsi.

Premetto che su quest'esempio che porterò ho spostato apache vero in localhost 127.0.0.1. Il mio obiettivo era quello di utilizzare nginx per servire tutte le immagini e apache per servire le richieste dinamiche in php o altro.

Perciò , facendo risiedere nginx e apache sulla stessa macchina, ho potuto evitare di utilizzare il modulo di caching di nginx ( dato che accederà direttamente ai files tramite il filesystem ).

CODE:
  1. http {
  2.     include       mime.types;
  3.     default_type  application/octet-stream;
  4.     sendfile        on;
  5.     large_client_header_buffers 4 8k;
  6.     client_header_buffer_size 4k;
  7.     keepalive_timeout  65;
  8.     #proxy_cache_path /tmp/nginx levels=1:2:2 keys_zone=cache:100m max_size=1024m;
  9.  
  10.     server {
  11.         listen       123.123.123.123:80;
  12.         server_name  www.example.com;
  13.         error_log  /usr/local/nginx/logs/error_example.log;
  14.        
  15.         location ~* ^.+.(jpg|jpeg|gif|png|ico|css|txt|js)$ {
  16.             root /var/www/example.com/web;
  17.         }
  18.         location / {
  19.             #proxy_cache cache;
  20.             #proxy_cache_valid any 1m;
  21.  
  22.             if ($http_user_agent ~* .*(Android|2.0\ MMP|240x320|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|Elaine/3.0|EudoraWeb|hiptop|IEMobile|iPhone|iPod|KYOCERA/W$
  23.                 rewrite ^(.*)$ http://m.example.com$1 permanent;
  24.             }
  25.             proxy_buffer_size 8k;
  26.             proxy_pass http://127.0.0.1:80;
  27.             proxy_set_header X-Real-IP $remote_addr;
  28.             proxy_set_header Host $host;
  29.             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  30.  
  31.  
  32.  
  33.         }
  34.     }
  35. }

Come potete vedere la configurazione è abbastanza semplice. Una piccola nota: Le righe con il # sono dei commenti. Li ho volutamente lasciati perchè quelle direttive, qualora decommentate, abiliterebbero il caching dell'intero sito tramite il modulo di nginx.

Ho lasciato anche uno statement condizionale che verifica se la richiesta proviene da un browser mobile . In quel caso nginx effettua un redirect a m.example.com. Ho pensato di lasciarlo perchè a qualcuno potrebbe effettivamente servire una configurazione simile.

Tuttavia c'è un altro problema che ho dovuto risolvere. Infatti apache deve essere in grado di riconoscere l'ip del visitatore e non l'ip del proxy nginx. Il motivo ? Alcuni programmi come vbulletin fanno alcuni controlli di sicurezza sugli ip.

Questo problema l'ho risolto installando su apache un modulo chiamato rpaf che fa proprio al caso nostro. Ovviamente in questo howto non spiegherò come installarlo ma vi darò la mia configurazione corretta per nginx :)

CODE:
  1. LoadModule rpaf_module /usr/lib/apache2/modules/mod_rpaf-2.0.so
  2. RPAFenable On
  3. RPAFsethostname On
  4. RPAFproxy_ips 127.0.0.1 123.123.123.123
  5. RPAFheader X-Forwarded-For

L'unica direttiva alla quale stare attenti è sicuramente RPAFproxy_ips dove dovete specificare tutti gli ip del vostro proxy nginx :)

I risultati

I risultati sono sbalorditivi, utilizzando Apache Benchmarking ( ab in console ) con 2000 richieste ( 100 concorrenti ) il numero di richieste al secondo completate raddoppia passando da 5000ca a 11000ca. Senza contare che il footprint di memoria utilizzato da nginx è veramente più basso.

Vale la pena provarlo ;)

 
1 Comment

Posted in Varie

 
 

Wordpress Seo Plugin