Category Archives: Android (Java)

Settings

Settings can be stored using

SharedPreferences settings;
settings = PreferenceManager.getDefaultSharedPreferences(context);

This will access settings stored for the context which is typically an Activity! To share settings cross Activities use context.getApplicationContext() instead of context. This will share the data,

settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

Lastest update in August 2013, inital post in August 2013

Show a kind of messagebox

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?");

builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
MainActivity.this.finish();
}
});

builder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});

builder.setNeutralButton("Test", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{


}
});

AlertDialog alert = builder.create();
alert.show();
Lastest update in October 2012, inital post in October 2012

Attach items to a listview

A listview shows data provided by an adapter. To create a simple list use the following:

//Find the listview with id 'list' in the resources 
ListView listView = (ListView) findViewById(R.id.list);

//Make a connection through an adapter 
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, new String[] {"AAA", "BBB", "CCC"}));


Lastest update in October 2012, inital post in October 2012