Converting pixels to dp and dp to px in Android

If you play around with height and width for a android device you often need to convert between real pixel (px) and device indipenden pixel (dp, dip).

The following methods are a easy solution to convert between px to dp

	private float px2Dp(float px, Context ctx)
	{
		return px / ctx.getResources().getDisplayMetrics().density;
	}

	private float dp2Px(float dp, Context ctx)
	{
		return dp * ctx.getResources().getDisplayMetrics().density;
	}

The density equals the following values depending on your device type.

.75 on ldpi (120 dpi)
1.0 on mdpi (160 dpi; baseline)
1.5 on hdpi (240 dpi)
2.0 on xhdpi (320 dpi)
3.0 on xxhdpi (480 dpi)
4.0 on xxxhdpi (640 dpi)

Alternativ you can use a util from the android SDK to get pixel from dip.
http://developer.android.com/reference/android/util/TypedValue.html

		Posted on Tags , , , , , 			

Can Shared Preferences be private?

Short answer

Yes

Long answer

Shared Preference are saved in the file system of your device, and the Shared Preferences Mode defines whether other applications have the right to read or write the Shared Preferences or not. Android SharedPreferences with mode “MODE_PRIVATE”, “MODE_WORLD_READABLE” and “MODE_WORLD_WRITABLE” are possible in android.

  • MODE_PRIVATE
    This is the default mode, where the created file can only be accessed by the calling the application (or other applications sharing the same user ID).
  • MODE_WORLD_READABLE
    This mode allows all other applications to have read access to the Shared Preferences.
  • MODE_WORLD_WRITEABLE
    If you choose this mode, all other applications to have write access to the Shared Preferences.

The getSharedPreferences mothod in the Context class can take two arguments. The first argument is the name of the Shared Preference and the second on is the mode. With the mode you can determines if the shared preferences are private or not.

About Shared Preferences

Full name
android.content.SharedPreferences

Description
Interface for accessing and modifying preference data. For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through the SharedPreferences.Editor.

Note
Currently SharedPreferences do not support multiple processes.

Nested Classes

  • SharedPreferences.Editor
    Interface used for modifying values in a SharedPreferences object.
  • SharedPreferences.OnSharedPreferenceChangeListener
    Interface definition for a callback to be invoked when a shared preference is changed.

Public Methods

  • abstract Boolean contains(String key)
    Checks whether the preferences contains a preference.
  • SharedPreferences.Editor edit()
    Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
  • Map getAll()
    Retrieve all values from the preferences.
  • boolean getBoolean(String key, boolean defValue)
    Retrieve a boolean value from the preferences.
  • float getFloat(String key, float defValue)
    Retrieve a float value from the preferences.
  • int getInt(String key, int defValue)
    Retrieve an int value from the preferences.
  • long getLong(String key, long defValue)
    Retrieve a long value from the preferences.
  • String getString(String key, String defValue)
    Retrieve a String value from the preferences.
  • Set getStringSet(String key, Set defValues)
    Retrieve a set of String values from the preferences.
  • void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)
    Registers a callback to be invoked when a change happens to a preference.
  • void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)
    Unregisters a previous callback.

Summary
Android SharedPreferences with private mode are default in android. Other modes like WORLD_READABLE and WORLD_WRITABLE are possible if you need SharedPreferences with this mode.

How to disable Screenshot in Android

Sometimes it can happen, that the app has to prevent android from taking a screenshot of the app. This can make sense if the app is being pushed into the background and/or for security reasons. So use FLAG_SECURE:

 getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);

This line secures against manual screenshots and automatic screenshots from the ICS recent-tasks history. You still see the application name and icon, but the screenshot is black.

Note: On some android devices FLAG_SECURE can be problematic: Sometimes FLAG_SECURE causes animation problems in screen rotation animation. See code.google.com/p/android/issues/detail?id=58632 – this has been fixed on Android 4.4.

How to check if wifi is connected in android

If you want to try downloading something unless you have wifi. You can use the following code snippet to be able to check if wifi is enabled.

You will be able to use the ConnectivityManager to get the state of the Wifi adapter. From there you can check if it is connected or even available.

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // Do whatever
}

Note: Add


to your AndroidManifest.xml for this to work.

Simple android showDialog example

A dialog can have a custom layout with buttons, text views, list, images, checkboxes, etc. You can create a layout for your dialog and show the dialog with the following simple method.

The showDialog method can be a part of your activity class. In that case you don’t need to explicitly declare the context as parameter. Just use this in case of context in the method body.

public void showDialog(Context context, String title, String message)
{
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.custom_dialog_layout);
    dialog.setTitle(text);
    TextView messageBox = (TextView ) dialog.findViewById(R.id.dialog_message);
    messageBox.setText (message);
    Button dialogButton = (Button) dialog.findViewById(R.id.dialog_button_ok);
    dialogButton.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // do something here when ok is pressed
            dialog.dismiss();
        }
    });
    dialog.show();
}

Tha lyout filename is dialog_message.xml in this example.


       
    
    

You need to use HTML in your message. Simply referencing a String with HTML in your messageBox will not work. If you want to show html formated text in your dialog, you can use the following method to set the text of your text view.

    messageBox.setText (Html.fromHtml(message));

The following HTML tags are supported By TextView:


, , , 
,
, , ,
, , ,

,

,

,

,

,
, , ,

, , , , , , ,

Alternatively, you can use the great HTMLDialog library for you html dialog. (https://github.com/msoftware/HtmlDialog). The HtmlDialog lib simplifies the display of HTML in a DialogFragment. It is useful for displaying Open Source Licenses, EULAs, Terms of Service pages, etc.

The HTMLDialog is licensed under the Apache License, Version 2.0

Export sharedPreferences to file

With the getAll function of sharedPreferences it is possible to save the shared preferences to a file. The following code example is probably the easyest way to do it. With the saveSharedPreferences method you can save all shared preferences a file to the root of your sdcard.

Make sure your App has the following permission. It allows the application to write to external storage.

 
/*
 Possible modes: 
 MODE_PRIVATE
 MODE_WORLD_READABLE
 MODE_WORLD_WRITEABLE
 MODE_MULTI_PROCESS
*/

/* Execute save SharedPreferences example code */
...
String name = "MyName";
int mode = MODE_PRIVATE;
File path = new File(Environment.getExternalStorageDirectory().toString());
File file = new File(path, "MySharedPreferences");
saveSharedPreferences (name, mode, file);
...


private void saveSharedPreferences(String name, int mode, File file)  
{
    SharedPreferences prefs = getSharedPreferences(name, mode);
    try
    {
        FileWriter fw = new FileWriter(file);
        PrintWriter pw = new PrintWriter(fw);
        Map prefsMap = prefs.getAll();
        for(Map.Entry entry : prefsMap.entrySet())
        {
            pw.println(entry.getKey() + ": " + entry.getValue().toString());            
        }
        pw.close();
        fw.close();
    }
    catch (Exception e)
    {
        Log.wtf(getClass().getName(), e.toString());
    }
}

Ripple effect on touched item

Google has started to use ripple animations in Material Design UIs. The setHotspot() method is added in API Level 21. This teaches the drawable a “hot spot”, and the RippleDrawable apparently uses this as the emanation point for the ripple effect. The setHotspot() method of a view take the x,y values from the MotionEvent to set the hot spot coordinates.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  view.setOnTouchListener(new View.OnTouchListener() {
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      v
        .findViewById(R.id.row_content)
        .getBackground()
        .setHotspot(event.getX(), event.getY());

      return(false);
    }
  });
}

Source: http://commonsware.com/

Android Reflection-API Constructor without parameters

If you have to create an object with default constructor, you can invoke the newInstance() method on a Class.
This simple class creates the instance of a named class using the empty default constructor by calling the newInstance method:

public class ReflectionTester throws InstantiationException, IllegalAccessException, ClassNotFoundException 
{
   public static Object createObject(String className) {
      return Class.forName(className).newInstance();
   }
}

Hide Keyboard

Request to hide the soft input window from the context of the window that is currently accepting input. This should be called as a result of the user doing some actually than fairly explicitly requests to have the input window hidden.

/**
* This method hides the soft input window, if it's open.
*
* @param activity Activity to hide soft input window
*/
public static void hideKeyboard(Activity activity) {
    if (activity != null && activity.getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }
}

Source: https://www.reddit.com/r/androiddev/wiki/utilities