Java + Android Library : First Program
Create a Demo Project
Step - 1 : First create a 'JavaLibraryDemo ' project
Step - 2 : Creating a new Android Library
After creating the project, go to File -> New -> New Module:
Step - 3 : Select Java Library.
Step - 4 : Next, you will be prompted to provide a name and the module name.
A. Enter Library Name - In my case 'mathlib-v1.0'
B. Package Name
Step - 5 : After finish, Project look like this in android studio
--------------------Configure----------------------
Step - 1 : Now, Configure the android project
File -> Project Structure -> app -> dependencies -> Click on (+) -> Module Dependency
Step - 2 : A 'Choose Module' popup will show, choose module and press 'OK' -> 'OK'
--------------------Start Code </> -------------------------------
Here, We perform simple Add Operation
Step - 1 : Inside Library, goto Java 'Main' folder. RightClicl -> New -> Java Class ->
Name the class like - 'AdditionClass' -> finish
Write below code too -
Code -
----------
public class AdditionClass {
public static Integer addValue(int n1, int n2){
int sum = n1 + n2;
return sum;
}
}
Step - 2 : Write this code in MainActivity
Code -
-------------------
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
performAddition(25, 35);
}
public void performAddition(int i, int j){
int result = AdditionClass.addValue(i, j);
System.out.println(result);
// Optional, For more interactive
new AlertDialog.Builder(MainActivity.this)
.setMessage(String.valueOf(result))
.show();
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
performAddition(25, 35);
}
public void performAddition(int i, int j){
int result = AdditionClass.addValue(i, j);
System.out.println(result);
// Optional, For more interactive
new AlertDialog.Builder(MainActivity.this)
.setMessage(String.valueOf(result))
.show();
}
}
Note : You can also use this tutorial for android library, Only single change
- Choose 'Android Library' instead of 'Java library', when creating module.
22








Comments
Post a Comment