1) Set app to Full Screen
In AndroidManifest.xml, set under application attributes
android:theme="@style/Theme.AppCompat.NoActionBar"
2) Catching errors
When your code breaks while running, look for the blue underlined links in the console. They point to the line number in your code that caused the excception
3) Date time string
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateTime = sdf.format(new Date());
4) Listening back button pressed
In Activity file
@Override public void onBackPressed() { super.onBackPressed(); //Do something }In cases where we want to display something before going back, this approach may be needed (Eg,WebView project)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction()==KeyEvent.ACTION_DOWN){
if(keyCode==KeyEvent.KEYCODE_BACK){
if(Some condition) // this is important because at some point we want back to close
//Do something
else
finish();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
5) Listening to edit text change
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
});
6) JSON Array is useful when an array is represented as a string. Ie, to get the individual elements of "[1,2,3]",
JSONArray arr = new JSONArray(string);
for(int i=0; i< arr.length();i++)
arr.getInt(i); //use the get method corresponding to datatype needed
7) Check if device is connected to internet
boolean isConnected(){
ConnectivityManager cm =
(ConnectivityManager)getApplicationContext().getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean connection = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return connection;
}
Needs permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
8) Delete files from phone directory
void clearArchieves(){
for(File child : getFilesDir().listFiles()){
if(child.getAbsolutePath().endsWith(".mht"))
child.delete();
}
}