Create Binding first step and asyn
//============================Gradle Side Code
=========================================
//build.Grade file add code
buildFeatures{
viewBinding true
}
//============================java
Code Start =========================================
//class add Binding
ActivityLasklabcheckboxBinding Binding;
===================================================================================
//Binding Create Actitivity Page Name ,initail
xlm and set view
//Method Code
Binding
=
ActivityLasklabcheckboxBinding.
inflate(getLayoutInflater());
View view = Binding.getRoot();
setContentView(view);
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Toast show data in Spinner select item
//============================java Code Start
=========================================
Toast.makeText(SpinnerActivity.this,
"Selected Province
:"+
spinnerBinding.spinnerProvinces.
getSelectedItem().toString(),
Toast.LENGTH_LONG).show();
================================End===============================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Populate data database show
listview with Method
//============================java
Code Start =========================================
private void populateListView(){
ArrayList<String>
data = objMgr.getAllPerson();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, data);
Binding.listViewShow.setAdapter(adapter);
}
================================end===============================================
Spinner setOnItemSelectedListener
//=================================================================================
Binding.spinnerFloor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View
view, int position, long id) {
String msgShow = "";
String item = Binding.spinnerFloor.getItemAtPosition(position).toString();
Toast.makeText(LASKLABCHECKBOX.this, "hello" + item, Toast.LENGTH_SHORT).show();
if (item == "Ground
Floor") {
Binding.txtViewSelect.setText("");
if (Binding.chkBoxFacultyOff.isChecked()) {
msgShow += "B1";
Binding.txtViewSelect.setText(msgShow + "");
Toast.makeText(LASKLABCHECKBOX.this, "hello" + item, Toast.LENGTH_SHORT).show();
}
if(Binding.chkBoxLaboratories.isChecked()){
msgShow +="B3";
Binding.txtViewSelect.setText(msgShow+"");
}
if(Binding.chkBoxLectureThreater.isChecked()){
msgShow +="B2";
Binding.txtViewSelect.setText(msgShow+"");
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
// can leave this empty
}
});
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Custom Adapter
//============================java
Code Start =========================================
//create class level
ArrayList<Customer> data;
//create adapter custom
data =
new ArrayList<Customer>();
customerAdapter adapter = new customerAdapter(data, this);
//only use frament not xml
layoutmanager
binding.recyclerViewCustomer.setLayoutManager(new LinearLayoutManager(this));
//show xml
binding.recyclerViewCustomer.setAdapter(adapter);
// diffrent way of call Adapter
data.clear();
//get data api
data.addAll(response.body());
binding.recyclerViewCustomer.getAdapter().notifyDataSetChanged();
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
ArrayAdapter
The Adapter acts as a bridge between the UI Component
and the Data Source. It converts data from the data sources into view items
that can be displayed into the UI Component. Data Source can be Arrays,
HashMap, Database, etc.
//============================java
Code Start =========================================
//example
public ArrayAdapter(Context
context, int resource, int textViewResourceId, T[] objects)// DataPut
//create drowpdownlist
ArrayAdapter
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, floor);
//calling ArrayAdapter
Binding.spinnerFloor.setAdapter(arrayAdapter);
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Create References
and Get Reference by id
//============================java
Code Start =========================================
// EditText References
EditText
txtmath;
EditText
txtenglish;
EditText
txturdu;
EditText
txtcomputer;
EditText
txtscience;
EditText
txtresult;
Button
btnCalPercentage;
Button
btnCalGrade;
Button
btnClear;
=================================================================
//
Object initialed
txtmath=
findViewById(R.id.txt_Math);
txtenglish=
findViewById(R.id.txt_English);
txturdu=
findViewById(R.id.txt_Urdu);
txtcomputer=
findViewById(R.id.txt_computer);
txtscience=
findViewById(R.id.txt_Science);
txtresult=
findViewById(R.id.txt_ResultGrade);
btnCalPercentage=findViewById(R.id.btn_calPercentage);
btnCalGrade=findViewById(R.id.btn_calGrade);
btnClear=findViewById(R.id.btn_clear);
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Move new Page
//============================java
Code Start =========================================
// Redirect
to another intent , new page move
Intent i=new
Intent(MainActivity.this,MainActivity2.class);
// start Activity
startActivity(i);
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Save data in Bundle
//============================java
Code Start =========================================
// Redirect
to another intent and share Data
Intent
i=new Intent(MainActivity.this,MainActivity2.class);
Bundle
bund= new Bundle();
bund.putString("user_data","My
name");
i.putExtras(bund);
startActivity(i);
//get show data
Intent intent = getIntent();
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
String array is an array of objects. This is because
each element is a String and you know that in Java, String is an object.
//============================java
Code Start =========================================
//String Create and initiate
String colors[] = {"Red","Blue","White","Yellow","Black", "Green","Purple","Orange","Grey"}
===================================================================================
//Different String Create Array
ArrayList<String> floor= new ArrayList<String>();
floor.add("Ground Floor");
floor.add("First Floor");
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
image conververt to byte
//============================java
Code Start =========================================
//get imageview then convert into
bitmapdrawable
BitmapDrawable bmpDrawble = (BitmapDrawable)
binding.imgView.getDrawable();
//convert into bitmap from
bitmapdrable
Bitmap bmpImage =
bmpDrawble.getBitmap();
ByteArrayOutputStream
outputStream =
new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG,
100,outputStream);
byte[] imgeArr = outputStream.toByteArray();
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Alter Dialog Create and show
//============================java
Code Start =========================================
// AlertDialog builder (correntpage Names)
AlertDialog.Builder
builde =new AlertDialog.Builder(SirZahidLabtaskimageview.this);
builde.setTitle("Select option");
String [] choice= new String[]{"capture by
Cemera","Gallery "};
//builder (array, click listener
create)
builde.setItems(choice, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface
dialogInterface,
int i) {
//list first item select in i
if(i==0){
//open gallery code
Intent intent = new Intent(Intent.ACTION_GET_CONTENT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_REQUEST_CODE);
}
else {
//open camera code
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
//builde show
builde.show();
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
onActivityResult after calling Camera or GALLERY
//============================java
Code Start =========================================
private static final int CAMERA_REQUEST_CODE = 1001;
protected void onActivityResult(int requestCode,
int resultCode,
@Nullable Intent data) {
//camera user
if(requestCode
== CAMERA_REQUEST_CODE){
if(resultCode
== RESULT_OK){
Bundle bundleObj =
data.getExtras();
Bitmap bmpImage = (Bitmap)
bundleObj.get("data");
binding.imgView.setImageBitmap(bmpImage);
//save
database convert byte
BitmapDrawable bmpDrawble = (BitmapDrawable)
binding.imgView.getDrawable();
// Bitmap bmpImage = bmpDrawble.getBitmap();
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG,
100,outputStream);
byte[] imgeArr = outputStream.toByteArray();
//byte to bitmap
}
}//gallery use code
else if(requestCode
== GALLERY_REQUEST_CODE){
if(resultCode
== RESULT_OK){
Uri imgeUri = data.getData();
binding.imgView.setImageURI(imgeUri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Initialize value into ArrayList Intent
//============================java
Code Start =========================================
ArrayList<String> imageList = new ArrayList<>();
Intent intent = new Intent(this, NextActivity.class);
intent.putStringArrayListExtra("IMAGE_LIST", imageList);
startActivity(intent);
//Receive data using
intent.getStringArrayListExtra()...
ArrayList<String> imageList = new ArrayList<>();
Intent intent = getIntent();
imageList = intent.getStringArrayListExtra("IMAGE_LIST");
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Bundle send data array of object
and get data ArrayList<object>
//============================java
Code Start =========================================
//save in bundle
ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",object);
intent.putExtra("BUNDLE",args);
startActivity(intent);
In the Transfer.class
//get
data
Intent intent =
getIntent();
Bundle args =
intent.getBundleExtra("BUNDLE");
ArrayList<Object>
object = (ArrayList<Object>)
args.getSerializable("ARRAYLIST");
//==================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
alterdialog Custom
//============================java
Code Start =========================================
//start alterDialog
// final View c=
getLayoutInflater().inflate(R.layout.admin_home_venue_cell,null);
venueBinding = AdminHomeVenueCellBinding.inflate(getLayoutInflater());
AlertDialog.Builder builde =new AlertDialog.Builder(getActivity());
builde.setView(venueBinding.getRoot());
builde.show();
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Dialog Box Custom
//============================java
Code Start =========================================
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(venueBinding.getRoot());
dialog.show();
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Connecting
imageView and Picasso will happen in onBindViewHolder of CityAdapter so put
this line of code at the end of the method.
//============================java
Code Start =========================================
Picasso.get().load(city.getImageURL()).into(holder.image);
===============================End=================================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Bottom sheet show
//============================java
Code Start =========================================
View dialogView = getLayoutInflater().inflate(R.layout.bottomsheet_dialog_teacher, null);
BottomSheetDialog dialog =
new BottomSheetDialog(getContext(),R.style.BottomSheetStyle);
dialog.setContentView(dialogView);
dialog.show();
====================================End===========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Custom Toast Show
//============================java
Code Start =========================================
====================================End=================================================
Random number call
//============================java
Code Start =========================================
//
int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, //80]
Random r = new Random();
int
randomNumber = r.nextInt(5)+10;
binding.txtClassShow.setText(String.valueOf(randomNumber));
===================================================================================
Random number call save unique
number
//============================java
Code Start =========================================
Random r = new
Random();
ArrayList<Integer>
arrayList =new
ArrayList<Integer>();
while (true){
for
(int
i = 0; arrayList.size()!=10; i++) {
int randomNumber = r.nextInt(11) + 10;
if (!arrayList.contains(randomNumber)) {
arrayList.add(randomNumber);
}
}
break;
}
binding.txtClassShow.setText(arrayList.indexOf(12)+"");
// arrayList.remove(arrayList.indexOf(12));
ArrayAdapter<Integer>
adapter = new ArrayAdapter<Integer>(getApplicationContext(),
android.R.layout.simple_list_item_1, arrayList);
binding.listViewShow.setAdapter(adapter);
===================================================================================
Save SharedPreferences
//============================java
Code Start =========================================
SharedPreferences ref = getApplicationContext().
getSharedPreferences("store", Context.MODE_PRIVATE);
SharedPreferences.Editor
edit= ref.edit();
edit.putString("name",binding.editTxtName.getText().toString());
edit.putString("email",binding.editTxtEmail.getText().toString());
edit.commit();
//array of list save
ArrayList<Customer> clist= new ArrayList<>();
Customer c= new Customer();
c.id=2;
c.name="ali";
c.address="ISB";
clist.add(c);
Gson g= new Gson();
String s =g.toJson(clist);
edit.putString("customer",s);
edit.commit();
===================================================================================
Show SharedPreferences
//============================java
Code Start =========================================
SharedPreferences ref =
getApplicationContext().
getSharedPreferences("store", Context.MODE_PRIVATE);
String name= ref.getString("name","name not fount");
String email= ref.getString("email","email
not fount");
binding.editTxtName.setText(name);
binding.editTxtEmail.setText(email);
//
array of list get data json
String s= ref.getString("customer",null);
//single object
Customer u = null;
ArrayList<Customer> list = null;
if(s!=null){
Gson g= new Gson();
//single object get
// u=
g.fromJson(s, Customer.class);
list=
g.fromJson(s,new TypeToken <ArrayList<Customer>>(){}.getType() );
binding.editTxtName.setText(list.get(0).name+"");
binding.editTxtEmail.setText(list.get(0).id+"");
================================================end============================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Dependencies add in bulid.gradle
file
//============================java
Code Start =========================================
implementation
'com.squareup.retrofit2:retrofit:2.7.2'
implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
implementation 'com.squareup.okhttp3:okhttp:3.6.0'
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Api Class Create in Android use
Retrofit
//============================java
Code Start =========================================
import
retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private
static RetrofitClient instance = null;
private Api myApi;
private RetrofitClient() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
myApi = retrofit.create(Api.class);
}
public
static synchronized RetrofitClient getInstance() {
if(instance== null){
instance = new RetrofitClient();
}
return instance;
}
public
Api getMyApi(){
return myApi;
}
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Create API InterFace and Api
fuction in android
//============================java Code
Start =========================================
public interface Api {
public static String
BASE_URL="http://192.168.136.33/FYPApi/api/";
public static String
IMAGE_BASE_URL="http://192.168.136.33/FYPApi/";
@POST("Customer/SaveCustomer")
public Call<String>
saveCustomer(@Body Customer
c);
@GET("math/getuser")
public Call<User>
getUser();
@GET("math/getusers")
public Call<List<User>>
getUsers();
@GET("math/divide")
public Call<Integer>
divide(@Query("n1") int n1, @Query("n2") int n2);
@GET("Customer/getallcustomers")
public Call<ArrayList<Customer>>
getAllCustomers();
@GET("Customer/getAllProfiles")
public Call<ArrayList<UserProfileInfo>>
getAllProfile();
@Multipart
@POST("Customer/uploadImage")
public Call<String>
saveUserProfile
(
@Part ArrayList<MultipartBody.Part> images,
@Part("id") RequestBody id,
@Part("lname") RequestBody lname,
@Part("fname") RequestBody fname,
@Part("address") RequestBody address,
@Part("gender") RequestBody g
);
@NonNull
public default MultipartBody.Part prepareFilePart(String partName, Uri
fileUri, Context context) throws IOException {
File file = FileUtil.from(context, fileUri);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(context.getContentResolver().getType(fileUri)),
file
);
return MultipartBody.Part.createFormData(partName,
file.getName(),
requestFile);
}
public default RequestBody createPartFromString(String
descriptionString){
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM,
descriptionString);
return description;
}
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Image and other data send sql
//============================java
Code Start =========================================
int id
= Integer.parseInt
(binding.editTextId.
getText().toString());
String fname = binding.editTextFname.getText().toString();
String lname = binding.editTextLname.getText().toString();
String address = binding.editTextAddress.getText().toString();
String gender = "Male";
if(binding.radioButtonFemaleProfile.isChecked())
gender = "Female";
//retrofit object create
RetrofitClient client =
RetrofitClient.getInstance();
//create api object
Api api = client.getMyApi();
//multi image send
ArrayList<MultipartBody.Part> imageList = new ArrayList<>();
try {
//image send body object create
MultipartBody.Part image = api.prepareFilePart("imge", imgeUri, UserProfileActivity.this);
//add image
imageList.add(image);
} catch (IOException e) {
e.printStackTrace();
}
//api function call
api.saveUserProfile(imageList,
api.createPartFromString(id+""),
api.createPartFromString(fname),
api.createPartFromString(lname),
api.createPartFromString(address),
api.createPartFromString(gender))
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String>
response) {
if(response.isSuccessful()){
Toast.makeText(getApplicationContext(),
response.body(),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
@GET("math/getusers")
public Call<List<User>>
getUsers(); //array
get function call
//============================java
Code Start =========================================
RetrofitClient client = RetrofitClient.getInstance();
Api api = client.getMyApi();
api.getUsers().enqueue(new Callback<List<User>>()
{
@Override
public void onResponse(Call<List<User>>
call,
Response<List<User>>
response) {
if(response.code()==200){
List<User> users = response.body();
String data = "";
for(User u : users){
data+="Name : "+u.Name +
"\nEmail : "+u.Email+"\n";
}
binding.editTextData.setText(data);
}
=========================================End==========================================
//--------------------------------Code
Detail and Working---------------------------------------------------------
Drawer create
//======================java
Code Start =========================================
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group
android:checkableBehavior="single">
<item
android:id="@+id/action_fav"
android:title="Favourites" />
<item
android:id="@+id/action_history"
android:title="History" />
</group>
</menu>
2 step String add
//============================java
Code Start =========================================
<string name="navigation_drawer_open">open
drawer</string>
<string name="navigation_drawer_close">close
drawer</string>
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Drawer
Navigation calling navigation bar show in theme changing
//============================java
Code Start =========================================
//show navigation bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//create Toggle
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
binding.drawerLayout,//use
spicific navigation bar
binding.drawerToolbar,//use
spicific navigation bar
R.string.drawer_opened,
R.string.drawer_closed);
//show toogle
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
//header changing
View
headerView = binding.drawerNavigation.getHeaderView(0);
DrawerHeaderBinding
dbinding = DrawerHeaderBinding.bind(headerView);
dbinding.textViewEmail.setText("Hello");
//Drawer clich function
binding.drawerNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
@Override
public
boolean onNavigationItemSelected(@NonNull
MenuItem item) {
if(item.getItemId()
== R.id.action_fav){
loadFragment(new FavouriteFragment());
}else
if(item.getItemId() == R.id.action_history){
loadFragment(new HistoryFragment());
}
binding.drawerLayout.
closeDrawer(GravityCompat.START);
return true;
}
});
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
to open and close the navigation drawer when the icon is clicked
//============================java
Code Start =========================================
@Override
public
boolean onOptionsItemSelected(
@NonNull
MenuItem
item) {
toggle.onOptionsItemSelected(item);
return super.onOptionsItemSelected(item);
}
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
calling Fragment function
//============================java
Code Start =========================================
private void loadFragment(Fragment f){
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
ft.replace(R.id.drawer_container,
f);
ft.commit();
}
//===============================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Three Dot Navigation create theme not icon
navigation change Theme
//============================java
Code Start =========================================
setSupportActionBar(binding.drawerToolbar);
binding.drawerToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener()
{
@Override
public
boolean onMenuItemClick(MenuItem item) {
if(item.getItemId() == R.id.action_add){
Toast.makeText(getApplicationContext(), "clicked
add", Toast.LENGTH_SHORT).show();
}
return
false;
}
});
===================Three Dot Show
XML==============================
@Override
public
boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(
R.menu.menu_draawer_activity,
menu);
return super.onCreateOptionsMenu(menu);
}
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Fragment Java Binding
//============================java
Code Start =========================================
FragmentHome2Binding Binding;
@Override
public View
onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
Binding =
FragmentHome2Binding.inflate(inflater, container, false);
Binding.ActionTxt.setText("Pakistan");
return Binding.getRoot();
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Recycler View Adapter create
//============================java
Code Start =========================================
public class AdminViewDVRAdapter extends RecyclerView.Adapter<AdminViewDVRAdapter.AdminViewDVRViewHolder>{
private Fragment fragment;
private ArrayList<DVR> DVRList;
private Context context;
public AdminViewDVRAdapter(ArrayList<DVR> DVRList, Context
context) {
this.DVRList = DVRList;
this.context = context;
}
public AdminViewDVRAdapter(ArrayList<DVR>
DVRList, Context context, Fragment fragment ) {
this.DVRList = DVRList;
this.context = context;
this.fragment=fragment;
}
@NonNull
@Override
public AdminViewDVRViewHolder
onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
AdminViewDvrCellBinding b =AdminViewDvrCellBinding.
inflate(LayoutInflater
.from(parent.getContext()),
parent, false);
AdminViewDVRViewHolder vh = new AdminViewDVRViewHolder(b);
return vh;
}
@Override
public void onBindViewHolder(@NonNull
AdminViewDVRViewHolder
holder, int position) {
DVR obj = DVRList.get(position);
holder.binding.textViewViewDvrName.setText(obj.getNAME()+"");
holder.binding.textViewViewDvrHost.setText(obj.getHOST()+"");
holder.binding.textViewViewDvrIp.setText(obj.getIP()+"");
//show image
String imageUri = Api.IMAGE_BASE_URL
+ "Files/"+obj.pic;
Picasso.with(context).load(imageUri).
into(holder.binding.imageViewUserProfile);
//click call function
holder.binding.adminViewDVRSelected.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AdminViewTabDVRFragment AdminViewTabDVR =
(AdminViewTabDVRFragment) fragment;
AdminViewTabDVR.recyclerviewAdminViewTabDVRCellClick(obj,context);
}
});
}
@Override
public int getItemCount() {
return DVRList.size();
}
class AdminViewDVRViewHolder extends RecyclerView.ViewHolder {
AdminViewDvrCellBinding binding;//<----
public AdminViewDVRViewHolder(
@NonNull AdminViewDvrCellBinding
itemView) {
super(itemView.getRoot());
binding = itemView;//<----
}
}
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Calling Custom Adapter
//============================java
Code Start =========================================
ArrayList<DVR> data = new ArrayList<DVR>();
AdminViewDVRAdapter adapter = new
AdminViewDVRAdapter (data, getActivity()
, AdminViewTabDVRFragment.this);
LinearLayoutManager
manager = new LinearLayoutManager(getActivity());
Binding.RecycerviewAdminViewDVR.setLayoutManager(manager);
Binding.RecycerviewAdminViewDVR.
setAdapter(adapter);
=========================================End==========================================
//----------------------------------Code Detail and
Working---------------------------------------------------------
Tab Craete PagerAdapter
//============java
Code Start =========================================
public class CustomPagerAdapter extends FragmentStateAdapter {
public CustomPagerAdapter(@NonNull FragmentManager
fragmentManager,
@NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
@NonNull
@Override
public Fragment
createFragment(int position) {
if(position
== 0){
return new HomeFragment();
}else
if (position == 1){
return new ProfileFragment();
}else{
return new SettingFragment();
}
}
@Override
public int getItemCount() {
return 3;
}
}
//----------------------------------Code Detail and
Working---------------------------------------------------------
Tab Craete and calling Page Adapter
//============java
Code Start =========================================
binding.tabLayout.addTab(binding.tabLayout.newTab().setText("Home"));
binding.tabLayout.addTab(binding.tabLayout.newTab().setText("Profile"));
binding.tabLayout.addTab(binding.tabLayout.newTab().setText("Setting"));
//Page
Calling create
CustomPagerAdapter
adapter = new CustomPagerAdapter(getSupportFragmentManager(),
getLifecycle()
);
binding.viewpagerContainer.setAdapter(adapter);
//Tab
Button click
binding.tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
@Override
public
void onTabSelected(TabLayout.Tab tab) {
binding.viewpagerContainer.
setCurrentItem(tab.getPosition());
}
@Override
public
void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public
void onTabReselected(TabLayout.Tab tab) {
}
});
//Tab
Change Page Call
binding.viewpagerContainer.
registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback()
{
@Override
public
void onPageSelected(int position) {
super.onPageSelected(position);
binding.tabLayout.selectTab(
binding.tabLayout.getTabAt(position)
);
}
});
//============java
End =========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Bottom Navigation
//============================java
Code Start =========================================
binding.bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch
(item.getItemId()){
case R.id.Home:
loadFragment(new
HomeFragment());
break;
default:
loadFragment(new SettingFragment());
break;
}
return true;
}
});
private void loadFragment(Fragment
f){
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frament_container, f);
ft.commit();
}
//======================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Create Database in Android SQLite
//============================java
Code Start =========================================
public
class DBManager extends SQLiteOpenHelper {
public
DBManager(@Nullable Context context) {
super(context, "demo.db", null, 1);
}
@Override
public
void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not " +
"exists user(userid integer primary key, username
text," +
"password text,role text)");
}
@Override
public
void onUpgrade(SQLiteDatabase db,
int i, int i1) {
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Database Change SQLite
//============================java
Code Start =========================================
public void onUpgrade(SQLiteDatabase
db, int i, int i1) {
db.execSQL("create table if not
exists " +
"profile(id integer, name text, gender text," +
"address text, image blob)");
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Save Database Data in Android
//============================java
Code Start =========================================
public
void saveUser(int id,String uname,String password, String role){
ContentValues
values = new ContentValues();
values.put("userid",id);
values.put("username",uname);
values.put("password",password);
values.put("role",role);
SQLiteDatabase
db = getWritableDatabase();
db.insertOrThrow("user",null,values);
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Update Database Data in Android
//============================java
Code Start =========================================
public
void userUpdate(int id,String uname,String password, String role){
ContentValues values = new ContentValues();
values.put("userid",id);
values.put("username",uname);
values.put("password",password);
values.put("role",role);
SQLiteDatabase
db = getWritableDatabase();
db.update("user",values,"userid=?",new
String[]{id+""});
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Delete Database Data in Android
//============================java
Code Start =========================================
public
void deletePerson(int pid){
SQLiteDatabase db =
getWritableDatabase();
db.delete("user","userid=?",new
String[]{pid+""});
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Show data Database in Android
//============================java
Code Start =========================================
public
ArrayList<String> getAllPerson(){
ArrayList<String> personList = new ArrayList<>();
SQLiteDatabase
db = getReadableDatabase();
Cursor
cursorRef = db.rawQuery("Select * from
user",
null);
cursorRef.moveToFirst();
while(cursorRef.isAfterLast() == false){
int id = cursorRef.getInt(0);
String user = cursorRef.getString(1);
String pass = cursorRef.getString(2);
String role = cursorRef.getString(3);
String row = "Id
: "+id+ ", NameUser : "+user+", Pass : "+pass+", Role "+role;
personList.add(row);
cursorRef.moveToNext();
}
cursorRef.close();
return personList;
}
=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Store Image and data calling DB
function
//============================java
Code Start =========================================
binding.buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View
view) {
int id
= Integer.parseInt
(binding.editTextId.
getText().toString());
String name = binding.editTextName.getText().toString();
String address = binding.editTextAddress.getText().toString();
String gender = "Male";
if(binding.radioButtonFemaleProfile.isChecked())
gender = "Female";
//drawble create
BitmapDrawable bmpDrawble = (BitmapDrawable)
binding.imageViewProfile.getDrawable();
//drawble to bitmap change
Bitmap bmpImage = bmpDrawble.getBitmap();
//create byte object
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
//compress file Stream
bmpImage.compress(Bitmap.CompressFormat.PNG,
100,outputStream);
//save byte
byte[]
imgeArr = outputStream.toByteArray();
Profile p = new Profile(id,
name,
gender,
address, imgeArr);
//DB object create
DBManager objMgr =new DBManager(ProfileActivity.this);
objMgr.saveProfile(p);
Toast.makeText(ProfileActivity.this,
"Data Saved", Toast.LENGTH_LONG)
.show();
}
});=========================================End==========================================
//--------------------------------------------Code
Detail and Working---------------------------------------------------------
Show data Database with image in
Android
//============================java
Code Start =========================================
DBManager mgr = new DBManager(this);
ArrayList<Profile>
profiles = mgr.getAllProfiles();
if(profiles.size()>0){
//one object get
Profile
p = profiles.get(0);
Bitmap bmpImage =BitmapFactory.decodeByteArray(p.image, 0,
p.image.length);
binding.imageViewProfile.setImageBitmap(bmpImage);
=========================================End==========================================