0% found this document useful (0 votes)
2 views31 pages

Android Note

The document provides code snippets for various Android functionalities including calculating BMI, handling user ratings, creating dialogs, and managing SQLite database connections. It covers event handling for UI components like TextViews, RatingBars, SeekBars, WebViews, AutoCompleteTextViews, and DatePickers. Additionally, it includes XML layouts for buttons and lists, and demonstrates how to create alert dialogs and manage user login attempts.

Uploaded by

Wamisho
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views31 pages

Android Note

The document provides code snippets for various Android functionalities including calculating BMI, handling user ratings, creating dialogs, and managing SQLite database connections. It covers event handling for UI components like TextViews, RatingBars, SeekBars, WebViews, AutoCompleteTextViews, and DatePickers. Additionally, it includes XML layouts for buttons and lists, and demonstrates how to create alert dialogs and manage user login attempts.

Uploaded by

Wamisho
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Event handler method in main activity android studio to calculate

body mass index;


public void handleText(View v){
v=findViewById([Link]);
TextView tx= (TextView)v;
String text = [Link]().toString();
double weight=[Link](text);
v=findViewById([Link]);
tx=(TextView)v;
float height=[Link]([Link]().toString());
String Result="You BMI:
"+[Link](weight/([Link](height,2)));
TextView txt=(TextView)(findViewById([Link]));
[Link](Result
);
//We use toast to push a popup message like alert
[Link](this,"hi "+text + " thank
you",Toast.LENGTH_LONG).show();
}

this method handle an event and create a new page or activity by


using intent
public void LaunchNew(View v){
Intent i = new Intent(this,[Link]);
startActivity(i);

}
Method if rating bar’s is taken submit text is clicked where check is registered to submit button

public void check(View v){


RatingBar rb=((RatingBar)(findViewById([Link])));

TextView tx =((TextView)(findViewById([Link])));
[Link]("You have rated us with :
"+[Link]([Link]())+" star");
}
And this method register a listener to the rating bar which listen to when people click the stars
public void rating(){
RatingBar rb=((RatingBar)(findViewById([Link])));
TextView tx =((TextView)(findViewById([Link])));
[Link](
new [Link]() {
@Override
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) {
[Link]([Link](rating));
}
});

To create an alert box we use the [Link] class and also the AlertDialog class to give it title
and to make it visible in the screen by calling show method

The code is this:


[Link] alb= new [Link](this);
[Link]("You have given a rating\nDo you want to close the
app?").
setCancelable(false).setPositiveButton("Awo", new
[Link]() {
@Override
public void onClick(DialogInterface dialog, int which)
{
finish();

}
}).setNegativeButton("Aye", new
[Link]() {
@Override
public void onClick(DialogInterface dialog, int which)
{
[Link]();
}
});
AlertDialog alert=[Link]();
[Link]("Sinibit");
[Link]();
Login checker method for this
Code:
public void attempt(View v){
EditText ta1 =((EditText)findViewById([Link].e1));
EditText ta2 =((EditText)findViewById([Link].e2));
TextView txv = ((TextView)findViewById([Link]));
String uname=[Link]().toString();
String pass=[Link]().toString();
boolean login_success=false;
//[Link]([Link]().toString());
if(([Link]()||[Link]())&& i!=0){
[Link]("Please fill all the information\nYou have left
"+i+" trials");
}
else if(i!=0){
i--;
if([Link]("wama")&& [Link]("wama")){
[Link]("Success Welcom Boss!!!");
}
else if([Link]("wama")&& ![Link]("wama")){
[Link]("Password invalid\nYou have left "+i+"
trials");
login_success=true;
}
else if(![Link]("wama")&& [Link]("wama")){
[Link]("User Name not found \nYou have left
"+i+" trials");
}
else {
[Link]("Wrong information \nYou have left
"+i+" trials");
}

}
if(i==0 && login_success) {
[Link](false);
[Link](false);
((Button)findViewById([Link].button6)).setEnabled(false);
[Link]("Out of trials you have been blocked");
}

Code for list view with actionListener when we click the list the code
public void page(){
String
name[]={"Mark","Daniel","Fassil","Wamisho","Nati","Lidet","Silas","
Tom","Hana","Zagol","Mamo"};
lv=((ListView)findViewById([Link]));
ArrayAdapter<String> adapter= new
ArrayAdapter<String>(this,[Link].name_list,name);
[Link](adapter);

[Link](new
[Link]() {
@Override
public void onItemClick(AdapterView<?> parent, View
view, int position, long id) {
String
value=(String)[Link](position);
TextView tt=((TextView)findViewById([Link]));
[Link]("Hey "+value);
}
});}
}

This need a new xml file to be created for this list inside layout folder the code is:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

</TextView>
Code to create seek bar which works like progress bar

Code:

public void seekBar(){


SeekBar sb = ((SeekBar)findViewById([Link]));
TextView tt= ((TextView) findViewById([Link]));
[Link]("Covered "+[Link]()+"/"+[Link]());

[Link](new
[Link]() {
int progressv;
@Override
public void onProgressChanged(SeekBar seekBar, int
progress, boolean fromUser) {
progressv=progress;
[Link]("Covered: "+progress+"/"+[Link]());

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
[Link]("Covered: "+progressv+"/"+[Link]());
}
});
}

This is seek bar:


Creating web view to load webpage on activity but if we try to use it it will jump to their browser to do
so

The code in the web view is this


: @SuppressLint("SetJavaScriptEnabled")
public void page(View v){
WebView wb = ((WebView)findViewById([Link]));

TextView tx =((TextView)findViewById([Link]));
String url =[Link]().toString();
[Link]().setLoadsImagesAutomatically(true);
[Link]().setAllowFileAccess(true);
[Link]().setAllowContentAccess(true);
[Link]().setJavaScriptEnabled(true);
[Link](View.SCROLLBARS_INSIDE_OVERLAY);
[Link](url);
}
We need certain permission in the android manifest code block this are
<uses-permission android:name="[Link]"
android:usesCleartextTraffic="true"
/>
<uses-permission
android:name="[Link].ACCESS_NETWORK_STATE" />

AutoComplete Text view with suggestion

Code inside the oncreate method


auto=((AutoCompleteTextView)findViewById([Link]));
ArrayAdapter adapter = new ArrayAdapter(this,
[Link].select_dialog_item,countryNames);
[Link](1);
[Link](adapter)
and declaration above the method
AutoCompleteTextView auto;
String[] countryNames={
"Sidama",
"Oromia",
"Amhara",
"Central Ethiopia",
"Somale",
"Afar",
"South East Ethiopia",
"Benishangul Gumuz",
"Gambela",
"Tigray",
"Harrari"
};

Autocompletetextview which suggest from an array

How to create Day Picker from a calander by using DatapickerDialoge

No view element nedded in [Link]

Just button to triger the dialog of the calander

Code in the mainactivity


int yearx,monthx,dayx;

static final int dualog=0;


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
final Calendar calendar=[Link]();
yearx=[Link]([Link]);
monthx=[Link]([Link]);
dayx=[Link](Calendar.DAY_OF_MONTH);
[Link](this);
setContentView([Link].activity_main);

[Link](findViewById([Link]),
(v, insets) -> {
Insets systemBars =
[Link]([Link]());
[Link]([Link], [Link],
[Link], [Link]);
return insets;
});
auto=((AutoCompleteTextView)findViewById([Link]));
ArrayAdapter adapter = new ArrayAdapter(this,
[Link].select_dialog_item,regionNames);
[Link](1);
[Link](adapter);

}
@Override
protected Dialog onCreateDialog(int id){
if (id==dualog){
return new
DatePickerDialog(this,dpicker,yearx,monthx,dayx);
}
return null;
}
private [Link] dpicker=new
[Link]() {
@Override
public void onDateSet(DatePicker view, int year, int month,
int dayOfMonth) {
yearx=year;
monthx=month+1;
dayx=dayOfMonth;
[Link]("calander:
"+[Link](dayx)+"/"+[Link](monthx)
+"/"+[Link](yearx));
}
};
public void cal(View v){
showDialog(dualog);
}
}

For soild buttons

for soild
buttons code in xml of drawable resource
<solid android:color="#FFA07A"></solid>

For stock and rounded buttons

<shape xmlns:android="[Link]
android:shape="rectangle">
<stroke android:color="#FFA07A" android:width="1dp"></stroke>
<corners android:radius="10dp"></corners>
</shape>

But we must first change the color setting in the themes foloder under values

To this

<resources xmlns:tools="[Link]
<!-- Base application theme. -->
<style name="[Link]"
parent="[Link]">
<!-- Customize your light theme here. -->
<!-- <item
name="colorPrimary">@color/my_light_primary</item> -->
</style>

<style name="[Link]"
parent="[Link]" />
</resources>

How to add database (sqllite) connectivity to our android app

First we need to create a java class in mainActivity folder

The this class inherit SQLiteOpenHelper class then we override this methods:

 DataBaseHelper (@Nullable Context context ) -> this is not normal method but
a constructor
 onCreate ( SQLiteDatabase db)
 onUpgrade ( )

DataBaseHelper ( ) : this method have the following code inside it’s body

public DataBaseHelper(@Nullable Context context) {


super(context, db_name, null, 1);

}
the context is provided when we create an object of this class DataBaseHelper in the mainActivity the
context is (this) and the db_name it the name of the database we want to create,the null is the factory
and 1 is the version.

This constructor is used to create our database.

onCreate ( ) : this method take SQLLITE database as parameter and then create a table the code is this:

public void onCreate(SQLiteDatabase db) {


[Link]("create table "+table_name+" (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARK INTEGER)");
}
db is the database that is passed to it as it is called this method take this db database and use the
exexSQL()- method which is used to write sqllite codes like create table ,drop table….
The ID is the primary key and it’s data type is integer ,text means String and we use autoincrement to
give a number from 1 to ∞ automatically as a new info is recorded without typing.

onUpgrade ( ) : this method is used to check where the database created existed or not it’s the one
who call the onCreate method the code is:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int


newVersion) {
[Link]("drop table if exists "+table_name);
onCreate(db);
}

As you can see this method accepts 3 parameters for now we are concerned more on the database db

In the body we wrote sql query in order to check if the database already existed if it does we drop it,

Then this method call onCreate method to create the table of the database by passing the db variable.

Method we create in order to insert,update and delete data from the database

insertData()to insert data to db

public boolean insertData(String name,String surname,String mark){


SQLiteDatabase db = [Link]();
ContentValues contentValues= new ContentValues();
[Link](col_2,name);
[Link](col_3,surname);
[Link](col_4,mark);
long result =[Link](table_name,null,contentValues);
if(result==-1){
return false;
}else {
return true;
}

First we create a sqllitedatabse object and set it to the current database we created :
SQLiteDatabase db = [Link]();

Then to add values to the database we create an object of


ContentValues , next by calling the put method we give the columns
name and the values of the columns which in this case we get as
parameter .

Then this values are in the content not in the database to insert
the data in the content to the database we use the insert method.
In the insert method first we pass table name, then null and then
the contentvalues reference variable . This method returns a
integer which we can use to verify if we insert the data correctly

If it returns -1 it means that it failed to insert the data. Else


it was successful.

getAllData(): to get all the record in the table

public Cursor getAllData(){


SQLiteDatabase db = [Link]();
Cursor res=[Link]("select * from "+table_name,null);
return res;
}
we use this expression to get the database we created

SQLiteDatabase db = [Link]();

Then we create a Cursor object to hold the data that is given by


the select statement query last we return this cursor we created.

This method fetch data from the database and store it in the
content reference and return it.

We also need method inside the MainActivity class to work with this method

When the button which says view all data is clicked this method is called. Then this method call the
method which is found in DataBaseHelper class getAllData()- this method returns the cursor we created
in the above. This cursor which is returned have a method called getCount() which gives a value or zero
if zero it means there is no data that is fetched and stored in the cursor else there is data.

Then we create a StringBuffer to holde the datas from the cursor .


We extract the data from the cursor by using the method getString() it the parenthesis we pass the the
indices of the column ( col-1:0 , col-2:1 …)

[Link]("ID: "+[Link](0)+"\n")-> this means the data


will be stored in this format “ID:1”;in the buffer

The reading should be in while loop by using moveToNext()which will


loop until to end of the table.

At last we call showMessage()- method and pass “Data” and and cast
the StringBuffer to string.

public void viewAll(View v){


Cursor res=[Link]();
if ([Link]()==0){
showMessage("Error","Noting found");
return;
}
StringBuffer buffer= new StringBuffer();
while ([Link]()){
[Link]("ID: "+[Link](0)+"\n");
[Link]("Name: "+[Link](1)+"\n");
[Link]("Surname: "+[Link](2)+"\n");
[Link]("Mark: "+[Link](3)+"\n");
}
showMessage("Data",[Link]());
}

showMessage(): this method is used create an alerdialog panel to


show the buffer which was casted to string an passed to this as
[Link] use [Link] to create the alert.

public void showMessage(String title,String Message){


[Link] builder= new [Link](this);
[Link](true);
[Link](title);
[Link](Message);
[Link]();

}
update() : this method is defined by us in the DataBaseHelper class it take the new data to replace the
data to be updated . This is done by getting our database db by creating SQLiteDatabase object and then
we Create ContentValues object to put the parameters with proper column names ”col_1 is the hold the
name if the 1 column” then we use the update method of our db and pass the table name,
ContentValues, ”ID=?” and String array with id given(new String []{id})

public boolean update(String id,String name,String surname,String


mark ){
SQLiteDatabase db=[Link]();
ContentValues contentValues = new ContentValues();
[Link](col_1,id);
[Link](col_2,name);
[Link](col_3,surname);
[Link](col_4,mark);
[Link](table_name,contentValues,"ID = ?",new String[]{id});
return true;
}

updateData(View v): this method inside the mainactivity is used to


update the database based on the ID given. This method is called
when the button linked is cliked. We achive this by using the
object of our database class (DataBaseHelper) and we call the
method update () which we defined in the above. As this we return
Boolean if true updated if false failed.

public void updateData(View v){


String id=[Link]().toString();
String data1= [Link]().toString();
String data2= [Link]().toString();
String data3= [Link]().toString();
boolean isupdated=[Link](id,data1,data2,data3);
if (isupdated){
[Link](this, "Data is updated successfully",
Toast.LENGTH_SHORT).show();

}else {
[Link](this, "Data update failed",
Toast.LENGTH_SHORT).show();

}
}
How to Delete a data from a database

public int deleteData(String id){


SQLiteDatabase db=[Link]();
int a =[Link](table_name,"ID=?",new String[]{id});
return a;
}
This is just like the insert() function we pass table name ,”ID=?” this mean that delete in the given id
where ? will be replaced by new String[] {id} . The delete function returns 0 if nothing is deleted and
other number which is the number of row deleted.

In the mainactivity we link a button with method and this method call this function code is:

public void delete(View v){


String id=[Link]().toString();
int a=[Link](id);
if (a==0){
[Link](this, "Data delete failed",
Toast.LENGTH_SHORT).show();

}
else {
[Link](this, [Link](a)+" rows are deleted
successfully", Toast.LENGTH_SHORT).show();
}
}

How to create SplashScreen

Step-1:

[Link] (module) file implement this:

implementation '[Link]:lottie:4.2.0'

Step-2:

Download Jason file from [Link] and create androiddirectory(raw) inside the resource file and
paste the Jason file there
The create an activity in which this h screen will be shown

In the Activity file add the following code above the on create method

Code:

private Handler handler=new Handler();


private Runnable runnable;

in the onCreate method write this code:

runnable=new Runnable() {
@Override
public void run() {
Intent intent=new
Intent([Link],[Link]);
startActivity(intent);
finish();
}
};
[Link](runnable,2000);

then create this method to handle memory leak

@Override
protected void onDestroy() {
[Link]();
[Link](runnable);
}

In the xml create lottieview with this attributes

Code in xml:

<[Link]
android:id="@+id/lottie_view"
android:layout_width="264dp"
android:layout_height="264dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_autoPlay="true"
app:lottie_loop="false"
app:lottie_rawRes="@raw/shop"
tools:ignore="MissingConstraints" />

To remove the default splash screen

Update the theme file to this :

<activity
android:name=".[Link]"
android:exported="true"
android:theme="@style/SplashScreenTheme"
android:launchMode="singleTask"
android:screenOrientation="fullSensor"
android:noHistory="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]"
/>
</intent-filter>
</activity>

Create if not exit [Link] file in value directory

<item name="android:windowIsTranslucent">true</item>
Put this inside the first style tags

Scrollview to make the scress scrollable

.xml file

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:id="@+id/main"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_width="match_parent"
>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>
</ScrollView>

</LinearLayout>

How to create spinners in android studio

Spinner spinner = ((Spinner)findViewById([Link]));


[Link](new
[Link]() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String item=[Link](position).toString();
[Link]([Link], "Selected: "+item,
Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
});
ArrayList<String> arrayList = new ArrayList<>();
[Link]("Leather Tote");
[Link]("Cotton Tote");
[Link]("Leather Beget");
[Link]("Children Bag");
[Link]("Workplace Bag");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
[Link].simple_spinner_item,arrayList);
[Link]([Link].select_dialog_item
);
[Link](adapter);
How to change the textcolor of spinners in android studio put these code inside the
onItemselected method

((TextView) [Link](0)).setTextColor([Link]);

How to add a tool bar inside the activity

Step -1:

Change the themes parent setting to enable action bar

<style name="[Link]" parent=


"[Link]">
Step 2:

Add toolbar in xml

<[Link]
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="?attr/colorPrimary"
android:title="Your Label Text" />

How to Fix the EditText being keyen by the system keyboard

The if-part is when the keyboard pop’s up and the else one when the keyboard hides.

final View rootView = findViewById([Link]);


[Link]().addOnGlobalLayoutListener(new
[Link]() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
[Link](r);
int screenHeight = [Link]().getHeight();
int keypadHeight = screenHeight - [Link];
if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is
a threshold for keyboard height
[Link](-730f);
} else {
[Link](-0f);
}
}
});

How to create RadioButtons

<RadioGroup
android:layout_width="match_parent"
android:id="@+id/radio_group"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:layout_height="wrap_content"
android:background="@drawable/input_shape"
android:layout_toRightOf="@+id/spinner"
android:orientation="horizontal"
android:padding="7dp"

android:elevation="2dp"
android:layout_below="@+id/name_inputs">

<RadioButton
android:id="@+id/gender_male"
android:textColor="#000"
android:layout_width="wrap_content"
android:layout_height="38dp"
android:layout_marginRight="20dp"
android:gravity="center"

android:fontFamily="@font/roboto_regular"
android:text="Male"
android:theme="@style/RadioButtonSelectedTheme"
android:textSize="17sp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:theme="@style/RadioButtonSelectedTheme"
android:textSize="17sp"
android:fontFamily="@font/roboto_regular"
android:textColor="#000"
android:id="@+id/gender_female"/>
</RadioGroup>

How to to make sure any radiobutton is selected

int isGenderSelected =[Link]();

if -1 nothing is selected ;

Integrating video jason in android studio

In gradel file

implementation '[Link]:rive-android:latest-version'

in java file

import [Link];

import [Link];

import [Link];

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);

setContentView([Link].activity_main);

RiveAnimationView riveAnimationView =
findViewById([Link]);

[Link]([Link].your_animation);

}}

How to set Animaton to view

for (int i=0;i<[Link]();i++){


View child= [Link](i);
if(child instanceof TextView){
Animation a = [Link](getContext(),
[Link].fade_in);
[Link]();
[Link]();
[Link](a);
}
}
Typing effect in textview

final Handler handler = new Handler();


[Link](new Runnable() {
@Override
public void run() {
[Link]([Link](0, index));
index++;
if (index <= [Link]()) {
[Link](this, delay);
}
}
}, delay);
Gemini

public String answerWithGemini(TextView mytext){

String api=BuildConfig.API_KEY;
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
new GenerativeModel(
/* modelName */ "gemini-1.5-flash",
api);
GenerativeModelFutures model = [Link](gm);

Content content =
new [Link]().addText("Write a story about a
magic backpack.").build();

ListenableFuture<GenerateContentResponse> response =
[Link](content);

[Link](
response,
new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse
result) {
String resultText = [Link]();
final Handler handler = new Handler();
[Link](new Runnable() {
@Override
public void run() {
[Link]([Link](0,
index));
index++;
if (index <= [Link]()) {
[Link](this, delay);
}
}
}, delay);

@Override
public void onFailure(Throwable t) {
[Link]();
[Link]( "I can't continue this chat");
}
},
[Link]());
}

Gemini cont…

[Link](new [Link]() {
@Override
public void onResult(String result) {
[Link]([Link]);
ai_holder.setVisibility([Link]);

runOnUiThread(() -> {
final Handler handler = new Handler();
[Link](new Runnable() {
@Override
public void run() {
ai_answer.setText([Link](0,
index));
index++;
if (index <= [Link]()) {
[Link](this, delay);
}
}
}, delay);

});
}
});

}
});
Keyboard up and down controller not to hide the view
Inside android manifest file

android:windowSoftInputMode="adjustPan"

Inside java file

InputMethodManager imm = (InputMethodManager)


getSystemService(Activity.INPUT_METHOD_SERVICE);

Inside onClick method or onclicklistner

View view = getCurrentFocus();

if (view != null) {

[Link]([Link](), 0);}

XML TO PDF

public class MainActivity extends AppCompatActivity {

private static final int REQUEST_CODE = 1232;


Button btn;
RelativeLayout root;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
[Link](this);
setContentView([Link].activity_main);

[Link](findViewById([Link]),
(v, insets) -> {
Insets systemBars =
[Link]([Link]());
[Link]([Link], [Link],
[Link], [Link]);
return insets;
});
root=findViewById([Link]);
btn=findViewById([Link]);
[Link](v -> {
gotoButton();
});
}

private void gotoButton() {


[Link]([Link]);
permissonAsker();
convertoPDF();
}

private void convertoPDF() {


View viewr =
[Link](this).inflate([Link].activity_main,null);
RelativeLayout view = [Link]([Link]);
DisplayMetrics displayMetrics =new DisplayMetrics();
if([Link].SDK_INT>=Build.VERSION_CODES.R){
[Link]().getRealMetrics(displayMetrics);
}else{

[Link]().getDefaultDisplay().getMetrics(displayMetri
cs);
}

[Link]([Link]([Link]
ixels,[Link])
,[Link]([Link]
ls,[Link]));

[Link](0,0,[Link],[Link]
els);
PdfDocument document= new PdfDocument();
int viewWidth=[Link]();
int viewHieht=[Link]();
[Link] pageInfo= new
[Link](viewWidth,viewHieht,1).create();
[Link] page=[Link](pageInfo);
Canvas canvas =[Link]();
[Link](canvas);
[Link](page);
File downloadsDir=
[Link]([Link]
_DOWNLOADS);
String fileName="[Link]";
File file = new File(downloadsDir,fileName);
try{
FileOutputStream fos = new FileOutputStream(file);
[Link](fos);
[Link]();
[Link]();
String sourceFilePath = [Link]();
String destFilePath = new File(downloadsDir,
"[Link]").getAbsolutePath();

[Link](this, "Written Successful",


Toast.LENGTH_SHORT).show();

} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}

public void permissonAsker(){


[Link](this,new String[]
{[Link].WRITE_EXTERNAL_STORAGE},REQUEST_CODE);
}
}

How to save xml to pdf in a4

private void convertToPDF() {


// Capture the view as a Bitmap
Bitmap bitmap = getBitmapFromView(root); // Replace this with
your method to capture the view

// Create the output file


File downloadsDir =
[Link]([Link]
_DOWNLOADS);
String fileName = "output_proportional.pdf";
File file = new File(downloadsDir, fileName);

try {
// Initialize iText7 writer and PDF document
PdfWriter writer = new PdfWriter([Link]());
PdfDocument pdfDocument = new PdfDocument(writer);

// Set the PDF page size to A4


[Link](PageSize.A4);

// Create the iText Document


[Link] document = new
[Link](pdfDocument);

// Convert the Bitmap to ImageData


ByteArrayOutputStream stream = new ByteArrayOutputStream();
[Link]([Link], 100, stream);
ImageData imageData =
[Link]([Link]());

// Create an Image object


Image image = new Image(imageData);

// Calculate scaling to preserve the aspect ratio


float originalWidth = [Link]();
float originalHeight = [Link]();
float a4Width = [Link]();
float a4Height = [Link]();

float scaleX = a4Width / originalWidth;


float scaleY = a4Height / originalHeight;
float scale = [Link](scaleX, scaleY); // Use the smaller
scaling factor to fit content

// Scale the image proportionally


[Link](scale, scale);

// Center the image on the page


float offsetX = (a4Width - (originalWidth * scale)) / 2;
float offsetY = (a4Height - (originalHeight * scale)) / 2;
[Link](offsetX, offsetY);
// Add the image to the document
[Link](image);

// Close the document


[Link]();
[Link]();

[Link](this, "PDF saved at: " +


[Link](), Toast.LENGTH_LONG).show();

} catch (Exception e) {
[Link]();
[Link](this, "Error: " + [Link](),
Toast.LENGTH_LONG).show();
}
}

// Helper method to capture the view as a Bitmap


private Bitmap getBitmapFromView(View view) {
[Link](true);
[Link]();
Bitmap bitmap = [Link]([Link]());
[Link](false);
return bitmap;
}

You might also like