Java Code in Android


 //--------------------------------------------Code Detail and Working---------------------------------------------------------

Get URI Camera Open

private static final int CAMERA_REQUEST_CODE = 1;
// Open the camera to capture an image
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);

//============================java Code Start =========================================

   @Override
    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);

// Toast.makeText(this, ""+resultCode, Toast.LENGTH_SHORT).show();
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
// Bitmap photo = (Bitmap) resultData.getExtras().get("data");
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
// Uri imageUri = getImageUri(this, photo);
Bundle bundleObj = resultData.getExtras();
Bitmap bmpImage = (Bitmap) bundleObj.get("data");
// ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// bmpImage .compress(Bitmap.CompressFormat.JPEG, 100, bytes);
// if(bmpImage!=null){
//// String path = MediaStore.Images.Media.insertImage(getContentResolver(), bmpImage, "Title", null);
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
// String path = MediaStore.Images.Media.insertImage(getContentResolver(), bmpImage, "IMG_" + Calendar.getInstance().getTime(), null);
// binding.profileImageTeacher.setImageURI(Uri.parse(path));
// }



try {
// Existing code
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, "IMG_");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

Uri imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

if (imageUri != null) {
OutputStream outputStream = getContentResolver().openOutputStream(imageUri);
bmpImage.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
binding.profileImageTeacher.setImageURI(imageUri);
// Use the imageUri as needed
Toast.makeText(this, "Image saved successfully", Toast.LENGTH_SHORT).show();
} else {
// Handle case when imageUri is null
}

// String path = MediaStore.Images.Media.insertImage(getContentResolver(), bmpImage, "Title", null);
// Toast.makeText(this, ""+path, Toast.LENGTH_SHORT).show();
// Rest of the code
} catch (Exception e) {
e.printStackTrace();
binding.textViewTeacherName.setText(e+"");
Toast.makeText(this, ""+e, Toast.LENGTH_SHORT).show();
// Handle the exception appropriately
}

}

}

=========================================End========================================== 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Get URI Camera Open

//============================java Code Start =========================================

  @Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);

// Toast.makeText(this, ""+resultCode, Toast.LENGTH_SHORT).show();
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
// Bitmap photo = (Bitmap) resultData.getExtras().get("data");
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
// Uri imageUri = getImageUri(this, photo);
Bundle bundleObj = resultData.getExtras();
Bitmap bmpImage = (Bitmap) bundleObj.get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmpImage .compress(Bitmap.CompressFormat.JPEG, 100, bytes);
if(bmpImage!=null){
// String path = MediaStore.Images.Media.insertImage(getContentResolver(), bmpImage, "Title", null);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
                        bmpImage, "IMG_" + Calendar.getInstance().getTime(), null);
binding.profileImageTeacher.setImageURI(Uri.parse(path));
}
}
}

=========================================End========================================== 

 //--------------------------------------------Code Detail and Working---------------------------------------------------------

Search Image Drawable by name code

//============================java Code Start =========================================

String imageName = pices[0][0].name; // Assuming imageName holds the name of the image
int imageResourceId = getResources().getIdentifier(imageName, "drawable", getPackageName());

if (imageResourceId != 0) {
    Drawable imageDrawable = getResources().getDrawable(imageResourceId);
    ArrayList<Drawable> drawables = new ArrayList<>();
    drawables.add(imageDrawable);
} else {
    // Image with the given name not found
}

=========================================End========================================== 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

BackPress code Fragment load

//============================java Code Start =========================================

    public void onBackPressed() {
// View mBottomNavigationView = requireActivity().findViewById(R.id.bottom_nav_admin);
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frament_container_Director);
if (fragment instanceof DirectorHomeViewCHRFragment) {
loadFragment(new DirectorDashBoardHomeFragment());
}
else { //
super.onBackPressed();
// onBackPressed();
}

}
private void loadFragment(Fragment f){
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();

//manage back track
// ft.add(R.id.frament_container_admin, f);
ft.replace(R.id.frament_container_Director, f);
// ft.addToBackStack(null);
ft.commit();
}

=========================================End==========================================

 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Create Binding  first step and asyn

//============================java Code Start =========================================

//build.Grade file add code

buildFeatures{
    
viewBinding 
true
}
=========================================End==========================================

//--------------------------------------------Code Detail and Working---------------------------------------------------------

++++++++++++++++++++++++PDF DOWNLODER+++++++++++++++++++++++

package com.example.biitdigitallibrarysystem.models;

import android.app.DownloadManager;

import android.content.Context;

import android.net.Uri;

import android.os.Environment;

import android.webkit.CookieManager;

import android.webkit.URLUtil;

import android.widget.Toast;


public class PdfDownloader {

    private Context context;


    public PdfDownloader(Context context) {

        this.context = context;

    }


    public void downloadPdf(String url) {

        String fileName = URLUtil.guessFileName(url, null, null);

        String downloadPath = Environment.DIRECTORY_DOWNLOADS;


        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        request.setDestinationInExternalPublicDir(downloadPath, fileName);


        // Add cookies if required

        String cookie = CookieManager.getInstance().getCookie(url);

        if (cookie != null) {

            request.addRequestHeader("Cookie", cookie);

        }


        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        if (downloadManager != null) {

            downloadManager.enqueue(request);

            Toast.makeText(context, "Downloading PDF...", Toast.LENGTH_SHORT).show();

        } else {

            Toast.makeText(context, "Download Manager not available", Toast.LENGTH_SHORT).show();

        }

    }

}

=========================================End==========================================

 

//=================================================================================

//--------------------------------------------Code Detail and Working---------------------------------------------------------

A binding class is generated for each layout file. By default, the name of the class is based on the name of the layout file, converting it to Pascal case and adding the Binding suffix to it. The above layout filename is activity_main.xml so the corresponding generated class is ActivityMainBinding. This class holds all the bindings from the layout properties (for example, the user variable) to the layout's views and knows how to assign values for the binding expressions.The recommended method to create the bindings is to do it while inflating the layout, as shown in the following example:

//============================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(),

//get position Drop-Down

int selectedPosition = binding.spinnerTeacherDiscipline.getSelectedItemPosition();

                        Toast.LENGTH_LONG).show();================================or===============================================

 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Populate data database show listview

//============================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);
}

================================or===============================================

 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Specific time or countdown create

//============================java Code Start =========================================

// specific time work  

new CountDownTimer(35000, 1000){

            @Override

            public void onTick(long millisUntilFinished) {

                             // working on time

                Log.d("lpg", "onTick: I am hero");

            }

            @Override

            public void onFinish() {

                             //Finish working

                Log.d("lpg", "Khatam ho gaya");

            }

        }.start();

================================or===============================================

//Task Scheduler using Handler and Runnable
      
final Handler handler = new Handler();

//continous runing
      
Runnable run = new Runnable(){
          
@Override
          
public void run() {
              
// Code to execute
              
number++;
              
Toast.makeText(MainActivity.this, "This is toast " + number , Toast.LENGTH_SHORT).show();

// spicific time accor
              
handler.postDelayed(this, 1000);

          
}
       }
;
      
handler.post(run);


=========================================End==========================================

 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Picture   change  hide and show

//============================java Code Start =========================================

//create id Name
String idX = "pic" + currentImage;
//get id create String name
int x = this.getResources().getIdentifier(idX, "id", getPackageName());
// ref get by id
pic = findViewById(x);
// hide pic
pic.setAlpha(0f);
// change pic number
currentImage = (3 + currentImage - 1) % 3;
//create id Name
String idY = "pic" + currentImage;
//get id create String name
int y = this.getResources().getIdentifier(idY, "id", getPackageName());
// ref get by id
pic = findViewById(y);
// show pic
pic.setAlpha(1f);


=========================================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---------------------------------------------------------

Create Redirect to another intent and share Data

//============================java Code Start =========================================

// Redirect to another intent and share Data
Bundle bund= new Bundle();
           
bund.putString("user_data","My name");
           
i.putExtras(bund);

=========================================End==========================================

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Move new Page Move Code

//============================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---------------------------------------------------------

Create Thread that will sleep for 5 seconds and data pass bundle

//============================java Code Start =========================================

//example

/****** Create Thread that will sleep for 5 seconds****/
Thread background = new Thread() {
   
public void run() {
       
try {
           
// Thread will sleep for 5 seconds
           
sleep(5*1000);

           
// After 5 seconds redirect to another intent
           
Intent i=new Intent(MainActivity.this,MainActivity2.class);
           
Bundle bund= new Bundle();
           
bund.putString("user_data","My name");
           
i.putExtras(bund);
           
startActivity(i);

           
//Remove activity
           
finish();
       
} catch (Exception e) {
        }
    }
}
;
// start thread
background.start();

 

 

=========================================End===========================================

//=================================================================================

 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Interface definition for a callback to be invoked when an item in this view has been selected.

//============================java Code Start =========================================

//Sample Code

spinnername.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override

    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

        // your code here

    }

 

    @Override

    public void onNothingSelected(AdapterView<?> parentView) {

        // your code here

    }

});

=======================================================

//example DrowpDownList Select item view code and include checkbox code

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---------------------------------------------------------

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 ,display spinner view list

Binding.spinnerFloor.setAdapter(arrayAdapter);

//==================================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 initiat

String colors[] = {"Red","Blue","White","Yellow","Black", "Green","Purple","Orange","Grey"}

===================================================================================

//Diffrent String Create

ArrayList<String> floor= new ArrayList<String>();
floor.add("Ground Floor");
floor.add("First Floor");

//==================================End===========================================

//=================================================================================

 

//--------------------------------------------Code Detail and Working---------------------------------------------------------

image get in database and Imagesviews

//============================java Code Start =========================================

===================================================================================

//Database show img in image view

DBManager mgr = new DBManager(SirZahidLabtaskimageview.this);

//create arraylist profile
ArrayList<profile> profiles = mgr.getAllprofilePerson();

//profiles size grader then 0
if
(profiles.size()>0) {

// get only singal profile
    profile p = profiles.get(
0);

// image byte to bitmap convert  0 than lenght
   
Bitmap bmpImage =
            BitmapFactory.decodeByteArray(p.
image,
                   
0,
                   
p.image.length);

//show imageview
   
binding.imgShow.setImageBitmap(bmpImage);

 

//==================================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---------------------------------------------------------

AlterDialog 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---------------------------------------------------------

//============================java Code Start =========================================

protected void onActivityResult(int requestCode,
                                int
resultCode,
                               
@Nullable Intent data) {
   
if(requestCode == CAMERA_REQUEST_CODE){
       
if(resultCode == RESULT_OK){
            Bundle bundleObj = data.getExtras()
;
           
Bitmap bmpImage = (Bitmap) bundleObj.get("data");
           
binding.imgView.setImageBitmap(bmpImage);
           
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

       
}
    }
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---------------------------------------------------------

Don't fotget to Initialize value into ArrayList

//============================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---------------------------------------------------------

Don't fotget to Initialize value into ArrayList<object>

//============================java Code Start =========================================

 

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

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();

//cutom callig bottom sheet



===================================================================================

 

//--------------------------------------------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);===================================================================================

 

//--------------------------------------------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();

===================================================================================

//--------------------------------------------Code Detail and Working---------------------------------------------------------

Custom Toast Show

//============================java Code Start =========================================


===================================================================================

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();
 
Set<Integer> a= new HashSet<>();
 
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();

===================================================================================

===================================================================================

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);

===================================================================================

 Save SharedPreferences ArrayList

//============================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 ArrayList

//============================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(us.get(0).name+"");
binding.editTxtEmail.setText(us.get(0).id+"");

================================================end============================

 

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.