Android Development Code (Tips)
Tip 1:
Removing auto keyboard popup on creation of new screen
In project's manifest file, for the screen activity add the following property:
android:windowSoftInputMode="stateHidden"
Tip 2:
Android ‘Unable to add window – token null is not for an application’ exception
If you are facing such error in android application then please check:
are you trying to create Dialog with an application context? Something like this:
new Dialog(getApplicationContext());
This is wrong. You need to use an Activity context. that is use ActivityName.this instead of getApplicationContext();
Tip 3:
WebView text field not poping up the soft keyboard on tapping.
What is actually happening in this case that, the webview is
not getting the focus on tap. To solve this add the following property
to the webview:webView.requestFocus(View.FOCUS_DOWN);
This will solve the problem
Tip 4:
Writing a File to SD Card(External Storage).
To write a file to SD card, Follow these steps:
String my_content = "Content for the file"; if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //handle case of no SDCARD present Toast.makeText(MainActivity.this, "Error", "No media found! Please insert SD card.", Toast.LENGTH_LONG).show(); } else { File file = new File(Environment.getExternalStorageDirectory()+File.separator+"Folder_Name", "file_name.extension"); if(file.exists()){ file.delete(); } File fileDir = new File(Environment.getExternalStorageDirectory()+File.separator+"Folder_Name"); if(!fileDir.exists()){ fileDir.mkdirs(); } try { file.createNewFile(); } catch (Exception e) { Log.d("My Activity", e.getMessage()); } try{ BufferedWriter my_buffered_writer = new BufferedWriter(new FileWriter(file, true)); my_buffered_writer.append(my_content); my_buffered_writer.newLine(); my_buffered_writer.close(); }catch (Exception e) { Log.d("My Activity", e.getMessage()); } }Tip 5: ActionBar “setSelectedNavigationItem()” Does Not Work in “Collapsed Tabs” State.
Implement OnPageChangeListener and in the onPageSelected(int position) call this method like this:
@Override public void onPageSelected(int position) { mActionBar.setSelectedNavigationItem(position); selectInSpinnerIfPresent(position, true); } private void selectInSpinnerIfPresent(int position, boolean animate) { try { ActionBar actionBarView = mActionBar; Class actionBarViewClass = actionBarView.getClass(); Field mTabScrollViewField = actionBarViewClass.getDeclaredField("mTabScrollView"); mTabScrollViewField.setAccessible(true); Object mTabScrollView = mTabScrollViewField.get(actionBarView); if (mTabScrollView == null) { return; } Field mTabSpinnerField = mTabScrollView.getClass().getDeclaredField("mTabSpinner"); mTabSpinnerField.setAccessible(true); Object mTabSpinner = mTabSpinnerField.get(mTabScrollView); if (mTabSpinner == null) { return; } Method setSelectionMethod = mTabSpinner.getClass().getSuperclass().getDeclaredMethod("setSelection", Integer.TYPE, Boolean.TYPE); setSelectionMethod.invoke(mTabSpinner, position, animate); Method requestLayoutMethod = mTabSpinner.getClass().getSuperclass().getDeclaredMethod("requestLayout"); requestLayoutMethod.invoke(mTabSpinner); } catch (Exception e) { e.printStackTrace(); } }Tip 6: Get Screen resolution of the android device programmatically. Use this code snippet to get screen resolution of android device:
DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE); // the results will be higher than using the activity context object or the getWindowManager() shortcut wm.getDefaultDisplay().getMetrics(displayMetrics); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; Log.d(""+screenHeight, ""+ screenWidth);Tip 7: Resolve android.os.NetworkOnMainThreadException. There are two Solution of this Problem. 1) Don’t write network call in Main UI Thread, Use Async Task for that. 2) Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }Also import android.os.StrictMode class. Tip 8: Check the orientation of the Activity. use this check to find the orientation of activity.
if(myActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { // code to do for Portrait Mode } else { // code to do for Landscape Mode }Tip 9: Check if the device is a phone or Tablet. Use this method to check device type if tablet.
public static boolean isTabletDevice(Context activityContext) { boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE); if (xlarge) { DisplayMetrics metrics = new DisplayMetrics(); Activity activity = (Activity) activityContext; activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM) { // Yes, this is a tablet! return true; } } return xlarge; }This returns true if the device is a tablet else false if phone. Tip 10: Check if the entered email is valid or not. Use this method to check:
public final static boolean isValidEmail(CharSequence target) { if (target == null || target == "") { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } }you can use this class to check and validate other fields too: 1. Email Address. 2. IP Address. 3. Phone Number. 4. Domain Name. 5. Web Url. for more details how to use this in your code, please refer to : Android Patterns Tip 11: Hide the soft keyboard forcefully: Use InputMethodManage to do this as:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditView.getWindowToken(), 0);where mEditView is the view to hide keyboard from. Tip 12: To Stop an editText from getting focus automatically on Activity startup: In Android Manifest file for the activity please add the following property:
android:windowSoftInputMode="stateHidden" //Hide the keyboard on activity startup
Tip 13:
To provide Touch/Press effect on a button:
Create a drawable selector file using following code and give it a name(say my_button.xml):
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/button_background" /> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/button_background_onclick" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/button_background_onclick" /> <item android:drawable="@drawable/button_background" /> </selector>Now add this drawable (i.e. my_button.xml) in the background attribute of that button like this:
android:background="@drawable/my_button"
NOTE: The button_background is the default image for the button and button_background_onclick is the image for button in pressed or touch state.
Tip 14:
Force ActionBar to be at the bottom in the screen:
In Android Manifest file for the application tag, add the following property:
android:uiOptions="splitActionBarWhenNarrow"
Tip 15:
Set MaxLength of a EditText programmatically:
set max_length as:
mEditText = new EditText(this); int max_length = 10; InputFilter[] fArray = new InputFilter[1]; fArray[0] = new InputFilter.LengthFilter(max_length); mEditText.setFilters(fArray);Tip 16: Check if a date is valid or not: Use the following method check the valid date
public boolean isThisDateValid(String dateToValidate, String dateFromat){ if(dateToValidate == null){ return false; } SimpleDateFormat sdf = new SimpleDateFormat(dateFromat); sdf.setLenient(false); try { //if not valid, it will throw ParseException Date date = sdf.parse(dateToValidate); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); return false; } return true; }
This article is nicely written. A very well written guide to take care of your furnace.
ReplyDeletetop mobile app development services 2020