Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Android Notes

Uploaded by

Star Bawa
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Android Notes

Uploaded by

Star Bawa
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 22

A WebView Works on the basic idea of a webpage on an android

webview.setWebViewClient();

Provides a space to the webclient page

webview.loadurl("Addresss");

Goto the manifests folder and then set the uses permission to the tag above the application tag.

FULL FORM OF XML


Extensible Markup Language
XML is case sensitive unlike HTML,CSS
XML tags need not be defined like html
XML tags are descriptive
Each layout contains one and only one root tag that is the
starting tag

View
It represents a rectangular area of the screen ,and tis
responsible for displaying information or content and event
handling.
Text ,image and Buttons are all view in android.
ViewGroup
It is essentially an 'invisible container' that holds multiple Views
or ViewGroups togeather and defines their layour properties.

Common View Groups


· A List View displays a list of scrollable items.
· A Grid View displays items in a 2 dimensional scrollable
grid
· A Table layout groups views into rows and columns .

Types Of Layout in android .


Layout in android
Layout are used android are as follows

-1

Linear Layout = This layout works on the general concept of linear designing and
this designing all the app windows buttons are arranged linearly .

They can be both vertical and horizontal


2- Relative Layout - It is a type of layout that displays all child views in relative
positions The position Of Each View is defined in a realtive layout

They can be both vertical and horizontal

3) Grid Layout = This type of layout will lay all the child views in a grid and thus all
the child views can vary in sizes and thus used

4) Table Layout
5)Frame layout

In the scroll View WE need to update the sdk version to 33 or higher then scroll
view will work one example is done in android studion to illustrate the same

ListView In Android
ListView listView= findViewById(R.id.LView);
ArrayList<String> foodItems=new ArrayList<>();
foodItems.add("Paneer");
foodItems.add("Roti");
foodItems.add("Laccha Parantha");
foodItems.add("Kabab");
foodItems.add("Aloo tikki");

ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1,foodItems);
//the context ,the layout , the input array

listView.setAdapter(arrayAdapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String text="Item"+i+""+((TextView)view).getText().toString();
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
}
});

ListView VS RecyclerView
Why RecyclerView ?

Recycler View is much more effiencient compared to listView since as the diagram
explains above.

· Recycler view is used to store thousands of rows of data

· Recycler view only manages the columns that are visible on the screen rest
of the columns do not occupy memory

· You supply data and decide how each item looks and thus RecyclerView ID
Dynamically creates elements when they are needed

· it recycles individual element

· When an itme scrolls off the screen ,RecyclerView doesn't destroy it's
view .Instead RecyclerView reuses the view for new items have scrolled
onscreen.

· this reuse vastly improves preformance ,improving your app's


responsiveness and reducing powe consumption.

NOTE : LISTVIEW HAS A predefined adapter class

whereas the recyclerView has no such predefined class you have to create
view ,layout etc by your own.

Recycler Adapter course


package com.example.recyclerview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class RecyclerContactAdapter extends


RecyclerView.Adapter<RecyclerContactAdapter.ViewHolder>{
//
ArrayList<ContactModal>arrayList;
Context context;
public RecyclerContactAdapter(Context context, ArrayList<ContactModal> contactlist)
{
this.context=context;//context generally helps in formation of links within the classes
arrayList=contactlist;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//here parent means on who we have to apply the inflater
View view= LayoutInflater.from(context).inflate(R.layout.contact_row,parent,false);
//LayoutInflater.from() means that calling the layoutinflator in terms of the
RecyclerContactApdater class
//then we use the inflate(our intent ,parent ,attachroot:false;
//if we set the attach root to true then the purpose of recycler view is defeated that is it will keep
each view
//in it's active memory instead of reusing views
ViewHolder vh=new ViewHolder(view);
return vh;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView t1;
TextView t2;
ImageView img;
public ViewHolder(@NonNull View itemView) {
super(itemView);

//t1=findViewById();
//findViewByID won't work since this is not a
//activity class
//it's a support class
//to acess the contentns of the R.layout.contact view holder here
//we use the following
t1=itemView.findViewById(R.id.textView_contact);
t2=itemView.findViewById(R.id.textView_name);
img=itemView.findViewById(R.id.imageView);

}
}

@Override
public void onBindViewHolder(@NonNull RecyclerContactAdapter.ViewHolder holder, int position) {
//binds the new text to the textView or image etc
//holder contains all the ids of the elements
holder.img.setImageResource(arrayList.get(position).img);
holder.t1.setText(arrayList.get(position).name);
holder.t2.setText(arrayList.get(position).number);

}
@Override
public int getItemCount() {
return arrayList.size();
//if returned 0 then it will not scroll no element will be inesrted
}
}
ADD THE FOLLOWING DEPENDENCIES FOR IMPLEMENTING BOTTOM NAVIGATION ACTIVITY

implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'

Application context is associated with the application and will always be the same throughout the life
of application; it does not change. So if you are using Toast, you can use application context or even
activity context (both) because Toast can be displayed from anywhere within your application and is
not attached to a specific window. But there are many exceptions. One such exception is when you
need to use or pass the activity context.

Activity context is associated with the activity and can be destroyed if the activity is destroyed; there
may be multiple activities (more than likely) with a single application. Sometimes you absolutely need
the activity context handle. For example, should you launch a new Activity, you need to use activity
context in its Intent so that the newly-launched activity is connected to the current activity in terms of
activity stack. However, you may also use application's context to launch a new activity, but then you
need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.

HOW TO DESIGN A BUTTON IN ANDROID

The method of button designing starts at the drawable folder in


that folder we create an xml file

and put the below syntax


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">

<gradient
android:startColor="#47951E"
android:endColor="#D11616"
android:angle="90" />
<corners android:radius="20dp"/>

</shape>

Aur just make the shape tag at start and end

may make the design work but to implement color changes we must to do
This

one more thing

in the values folder there exist a theme folder and open it

open themes.xml
and replace the start tag with one below

<style name="Theme.FireBaseDatabase"
parent="Theme.AppCompat.DayNight.DarkActionBar">

DataSnapshot in Firebase

Database snapshot in firebase is the following

We can easily get the snapshot of the data

Log Cat in Android Studio


Data Passing Between Fragments

So i have a FragmentPagerAdapater called SectionsPagerAdapter


and a fragment called TeamFragment where I display data from a
specific team. So basically I don't want to create different
fragments for each team. That is an overkill. I just want 1
fragment which basically connects to the backend then collects
the data based on the team then displays that data. But I dont
know how to pass the Team name(a string type) from
SectionsPagerAdapter to the TeamFragment so that in
TeamFragment, I can easily know what to retrieve from the
backend. My backend in parse.com. Please help me figure this out
and learn. Thanks

Bundle args = new Bundle();

args.putString("TeamName", team);

TeamFragment teamFragment = new TeamFragment();

teamFragment.setArguments(args);
Bundle bundle = this.getArguments();
mTeam = bundle.getString("TeamName");

//ViewHolder does not contain StartActivity

holder.layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it =new Intent(v.getContext(),PageDetailsVendor.class);
it.putExtra("Desc",model.getBookDescription());
v.getContext().startActivity(it);
//ViewHolder does not contain StartActivity
Toast.makeText(mcontext, "hello", Toast.LENGTH_SHORT).show();
}

});

Use the above instead

Custom toast
dependencies {
...
implementation 'com.github.GrenderG:Toasty:1.5.2'
}
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}

Toasty.success(yourContext, "Success!", Toast.LENGTH_SHORT, true).show();

public class WrapContentLinearLayoutManager extends LinearLayoutManager {

public WrapContentLinearLayoutManager(Context context) {

super(context);

public WrapContentLinearLayoutManager(Context context, int orientation, boolean


reverseLayout) {

super(context, orientation, reverseLayout);

public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr,


int defStyleRes) {

super(context, attrs, defStyleAttr, defStyleRes);

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {

try {

super.onLayoutChildren(recycler, state);

} catch (IndexOutOfBoundsException e) {

Log.e("TAG", "meet a IOOBE in RecyclerView");

} explain this to me

This is a custom implementation of the LinearLayoutManager class for RecyclerView, called


WrapContentLinearLayoutManager. It is designed to handle situations where the RecyclerView
throws an IndexOutOfBoundsException while trying to render its views.

The main modification made in this implementation is in the onLayoutChildren() method, which
is an overridden method from the parent LinearLayoutManager. This method is called when the
RecyclerView needs to layout its children views, which happens when the adapter data changes
or when the RecyclerView is first displayed on the screen.

In this implementation, the super.onLayoutChildren(recycler, state) method is called first, which


is the default implementation of the onLayoutChildren() method from the parent class.
However, if an IndexOutOfBoundsException is thrown during the layout process, the catch block
is executed and logs an error message with the tag "TAG". This catch block is included to
prevent the app from crashing when the IndexOutOfBoundsException is thrown.

Overall, this implementation ensures that the RecyclerView does not crash when an
IndexOutOfBoundsException occurs during the layout process. Instead, it logs an error message
and continues to function normally.
SWIPING OF THE RECYCLER VIEW ITEMS

package com.example.swipe_recycler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;
import java.util.List;

import it.xabaras.android.recyclerview.swipedecorator.RecyclerViewSwipeDecorator;

public class MainActivity extends AppCompatActivity {

List<ViewModel> list;
RecyclerView recyclerView;
Adapter adapter;

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

list = new ArrayList<ViewModel>();


ViewModel vh = new ViewModel("Star", "23", "8318407131",
R.drawable.ic_launcher_foreground);
ViewModel vh2 = new ViewModel("Isham", "16", "8318407131",
R.drawable.ic_launcher_foreground);
ViewModel vh3 = new ViewModel("Ravi", "20", "8318407131",
R.drawable.ic_launcher_foreground);
ViewModel vh4 = new ViewModel("Sonia", "43", "8318407131",
R.drawable.ic_launcher_foreground);

list.add(vh);
list.add(vh2);
list.add(vh3);
list.add(vh4);

recyclerView = findViewById(R.id.RecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

adapter = new Adapter(this, list);


recyclerView.setAdapter(adapter);

ItemTouchHelper //used for swipe gestures

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);


itemTouchHelper.attachToRecyclerView(recyclerView);
}

String deleted_Movie=null;
String del_age=null;
String del_contact=null;
int image_code= 0;
ItemTouchHelper.SimpleCallback simpleCallback = new
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull
RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
//used only for dragging the items of a recycler view not in swiping
}

@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {

int position= viewHolder.getAdapterPosition();


switch (direction){
case ItemTouchHelper.LEFT:
deleted_Movie=list.get(position).name;
del_contact=list.get(position).contact;
del_age=list.get(position).Age;
image_code=list.get(position).img_code;
list.remove(position);
adapter.notifyItemRemoved(position);
Snackbar.make(recyclerView,"DELETED",
BaseTransientBottomBar.LENGTH_LONG).setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View v) {
list.add(position,new
ViewModel(deleted_Movie,del_age,del_contact,image_code));
adapter.notifyItemInserted(position);
}
}).show();
// Toast.makeText(MainActivity.this, "Left Swiped",
Toast.LENGTH_SHORT).show();
break;

case ItemTouchHelper.RIGHT:
deleted_Movie=list.get(position).name;
del_contact=list.get(position).contact;
del_age=list.get(position).Age;
image_code=list.get(position).img_code;
list.remove(position);
adapter.notifyItemRemoved(position);
Snackbar.make(recyclerView,"ARCHIVED",
BaseTransientBottomBar.LENGTH_LONG).setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View v) {
list.add(position,new
ViewModel(deleted_Movie,del_age,del_contact,image_code));
adapter.notifyItemInserted(position);
}
}).show();
break;

}
}

public void onChildDraw (Canvas c, RecyclerView recyclerView,


RecyclerView.ViewHolder viewHolder,float dX, float dY,int actionState, boolean
isCurrentlyActive){

new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY,


actionState, isCurrentlyActive)
.addSwipeLeftBackgroundColor(ContextCompat.getColor(getApplicationContext(),R.c
olor.teal_200))
.addSwipeRightBackgroundColor(ContextCompat.getColor(getApplicationContext(),R.
color.purple_700))
.addSwipeLeftActionIcon(R.drawable.ic_baseline_delete_24)
.addSwipeRightActionIcon(R.drawable.ic_baseline_archive_24)
.create()
.decorate();

super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);


}
};
KOTLIN
Kotlin is preffered for null safety ie no null
pointer exception and a swift boost in the
performance it aslo convers to byte code
constructor in kotlin are working same as java but the syntax is entirely different

class Person(val name: String, val age: Int) {

init {

// Initialization logic or additional code here

println("Initializing Person object: $name, $age")

fun show() {

println("$name $age")

fun main() {

val p = Person("Star", 21)

p.show()

GETTER AND SETTER ARE DIFFERENT FOR KOTLIN

class Person {

var name: String = ""

get() {

println("Getter called for name")


return field

set(value) {

println("Setter called for name")

field = value

var age: Int = 0

get() {

println("Getter called for age")

return field

set(value) {

println("Setter called for age")

field = value

var job: String? = null

get() {

println("Getter called for job")

return field

set(value) {

println("Setter called for job")

field = value

}
fun main() {

val person = Person()

person.name = "John" // Setter called for name

person.age = 30 // Setter called for age

person.job = "Developer" // Setter called for job

println(person.name) // Getter called for name, prints "John"

println(person.age) // Getter called for age, prints 30

println(person.job) /

/ Getter called for job, prints "Developer"

MVVM -- VVV IMP


Sure, here are some notes on MVVM:

Model: The model is the data layer of an application. It contains the application's data
objects and their relationships. The model is responsible for storing, retrieving, and updating
data.

View: The view is the user interface layer of an application. It displays the data to the user
and allows the user to interact with the data. The view is not responsible for storing or
manipulating data.

ViewModel: The view model is the bridge between the model and the view. It exposes the
model's data to the view in a way that is easy to use. The view model also handles user
input and updates the model accordingly.

The MVVM pattern has several benefits, including:

Separation of concerns: The MVVM pattern separates the application's data, presentation,
and behavior into three distinct layers. This makes the application easier to understand,
develop, test, and maintain.

Testability: The MVVM pattern makes it easy to test the application's data, presentation, and
behavior independently. This is because each layer is isolated from the others.

Reusability: The MVVM pattern makes it easy to reuse the application's data, presentation,
and behavior in other applications. This is because each layer is independent of the others.
Here are some tips for using MVVM:

Use a data binding library: A data binding library can help you to bind the model's data to
the view's controls. This can save you a lot of time and effort.

Create a separate view model for each view: This will help to keep your code organized and
maintainable.

Use the view model to handle user input: This will help to keep your view code clean and
concise.

Update the model whenever the view model changes: This will ensure that the application's
data is always up-to-date.

I hope these notes are helpful.

reaad the rest on gfg for diagram

COMPANION OBJECTS IN KOTLIN


fun main(){

val Calculator=calculator();

val result=calculator.add(29,49);
println(result);

println("Difference is "+Calculator.sub(32,54));
}

class calculator{

companion object {
fun add(a: Int, b: Int): Int {
return a + b;
}
}
fun sub(a:Int,b:Int) = a-b;

//In Kotlin, a companion object is a special construct that


allows you to define properties and methods on a class that
are accessible without the need for an instance of that class.
It is similar to static members in other programming
languages like Java.
//Here's an example of how to define and use a companion
object in Kotlin:

Couroutine in kotlin

Aspect Threading Coroutines

Concurrency Model Multiple threads running concurrently


Lightweight units of execution, cooperatively scheduled

Concurrency Control Managed by OS scheduler,


preemptive switching Cooperatively scheduled, explicit
suspension points

Concurrency Complexity Complex (race conditions,


deadlocks, synchronization) Simplified (sequential-like code,
structured suspension)

Resource Utilization Higher memory overhead, more


system resources Smaller memory footprint, efficient
resource utilization
Error Handling Exceptions propagate through threads
Structured error handling within coroutine context

You might also like