Everyday Code

Sample useful codes

Daniyar Nurgaliyev
4 min readMay 22, 2018

1. Go Back ActionBar button;
2. Sending parameter from Fragment1 to Activity to Fragment2;
3. Setting TITLE in Activity/Fragment
4. Navigation back to parent activity not to remake it again;
5. Add Background tile (repeat image);
6. Getting random numbers between 1 to 50;
7. “Share” Button;
8. “Copy” Button;
9. Show “Logo” in action bar;
10. JDBC in java application Intellij idea;
11. EditText phone dial action send;
12. Adding button to ActionBar;
13. Send object by intent in extra using GSON;
14. Send object from one activity to another;
15. Full Screen Theme;
16. Splash Screen
17. RoomDatabase adding List
18. Date Picker
19. Android 10 CLEARTEXT communication not permitted by network security policy
20. Add Logging with Class and Method names
21. Create BroadcastReceiver
22. …

1. Go Back ActionBar button

1.1. Closes current Activity:

//Override method
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}

2.1. Adds Back arrow button to ActionBar and Navigates Up:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);

ActionBar actionBar = this.getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}

2. Sending parameter from Fragment1 to Activity to Fragment2 :

2.1. In Fragment1:

public interface onSomeEventListener {
public void someEvent(String s);
}

onSomeEventListener someEventListener;


@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
someEventListener = (onSomeEventListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement onSomeEventListener");
}
}
//put this into any onClickListerner
someEventListener.someEvent(String.valueOf("position"));

2.2. In Activity:

implement interface:

implements onSomeEventListener

Override someEvent() method:

@Override
public void someEvent(String position) {
// Fragment frag1 = getFragmentManager().findFragmentById(R.id.frgmCont);
FragmentMakalList frag1 = new FragmentMakalList();
Bundle bundle = new Bundle();
bundle.putInt("text", Integer.parseInt(position));
frag1.setArguments(bundle);

FragmentTransaction fTrans = getSupportFragmentManager().beginTransaction();
//fragment container name in xml
fTrans.replace(R.id.frgmCont, frag1);
fTrans.commit();



}

2.3. In Fragment2

Bundle bundle = this.getArguments();
int position = 1;
if (bundle != null) {
position = bundle.getInt("position", 1);
}

3. Setting TITLE in Activity/Fragment

In Activity:

getSupportActionBar().setTitle("Activity Title Name");

In Fragment:

getActivity().setTitle(getString("Fragment Title Name"));

4. Navigation back to parent activity not to remake it again:

In manifest.xml add to parent activity :

android:launchMode="singleTop"

5. Add Background tile (repeat image):

In res/drawable path create a file named my_background.xml

Add this code:

<?xml version="1.0" encoding="UTF-8" ?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/background"
android:tileMode="repeat"
/>

In layout put a link to this file e.g.

android:background="@drawable/my_background"

6. Getting random numbers between 1 to 50:

import java.util.Random;
Random rand = new Random();
int n = rand.nextInt(50) + 1;

7. “Share” Button:

8. “Copy” Button:

9. Show “Logo” in action bar:

10. JDBC in java application Intellij idea

11. EditText phone dial action send

<EditText
android:id="@+id/et_number"
android:inputType="phone"
android:imeOptions="actionSend"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

12. Adding button to ActionBar

12.1. In *.java file:

// create an action bar button
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
}

// handle button activities
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

switch (id) {
case R.id.btn_share: break;
case R.id.btn_share_whatsapp: break;
case R.id.btn_share_telegram: break;
}
return super.onOptionsItemSelected(item);
}

12.2. Create menu Android resource directory and create mymenu.xml Layout resource file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/mybutton"
android:title=""
app:showAsAction="always"
android:icon="@drawable/mybuttonicon"
/>
</menu>

13. Send object by intent in extra using GSON

13.1. From first Activity:

Product product = new Product();
String s = (new Gson().toJson(product));

Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra("tag", s);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

13.2. From Second Activity:

String s = getIntent().getStringExtra("tag");
Product product = new Gson().fromJson(s, Product.class);

14. Copied from here:

14.1.

//To pass:
intent.putExtra("MyClass", obj);

// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");

14.2.

Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:

class MainClass implements Serializable {

public MainClass() {}

public static class ChildClass implements Serializable {

public ChildClass() {}
}
}

15. Full Screen Theme

15.1. Add this to styles.xml:

<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>

15.2. Add this to AndroidManifest.xml:

<activity android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen" />

16. Splash Screen

16.1. Create activity with xml. In activity_splash.xml add this code:

16.2. In SplashActivity.java add this code:

16.3. In AndroidManifest.xml set SplashActivity.java as a MAIN and apply Fullscreen style (about Fullscreen goto 15 item of this article):

<activity
android:name=".Activites.SplashActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

17. RoomDatabase adding List

Implement GSON library to build.gradle

implementation 'com.google.code.gson:gson:2.8.2'

Just copy this class and start adding list to RoomDatabase as a json String

18. Date Picker

Just copy this method:

19. Android 10 CLEARTEXT communication not permitted by network security policy

20. Add Logging with Class and Method names

Log.i("autolog", javaClass.simpleName + ": " + Throwable().stackTrace[0].methodName + " END");

21. Add BroadcastReceiver

22. …

--

--