API Retrofit in Android

Security Reason solve 

Add Code

android:usesCleartextTraffic="true"

How to add internet permission in AndroidManifest.xml in android studio.

Step 1 :

Go to app -> src -> main -> AndroidManifest.xml.

Step 2:

Copy following code:

To add a dependency to your project, specify a dependency configuration such as implementation in the dependencies block of your module's build.gradle file.

For example, the following build.gradle file for an app module includes three different types of dependencies:

Java
plugins {
  id
'com.android.application'
}

android
{ ... }

dependencies
{
   
// Dependency on a local library module for retrofit2
    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'
}

Create Api Step 1

 Api Class Create in Android use Retrofit

Step 2:

Create FileUtil fuction in android

Step 3:

Create API InterFace and Api fuction in android

app/src/main/java/com/example/app/Api.java

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

@POST("exec")
public Call<String> ImageSend(@Query("action") String action, @Body RequestBody requestBody);
   @Multipart
@POST("api/mark-attendance")
public Call<ArrayList<Attendance>> mark_attendance(
        @Part MultipartBody.Part file);

    
@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 partNameUri fileUriContext 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.
FORMdescriptionString);
        return  
description;
    
}
}


Step 4: 

This function Calling

@GET("math/getusers")
public Call<List<User>> getUsers(); //array get function call

app/src/main/java/com/example/app/main.class

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

------------------------------------------------------------------------------------------------------

This function Calling

@POST("exec")

public Call<String> ImageSend(@Query("action") String action, @Body RequestBody requestBody);// function callimage send binary

app/src/main/java/com/example/app/main.class

 Bundle bundleObj = data.getExtras();
Bitmap bmpImage = (Bitmap) bundleObj.get("data");
binding.imageViewUser.setImageBitmap(bmpImage);
//save database convert byte
BitmapDrawable bmpDrawble = (BitmapDrawable)
binding.imageViewUser.getDrawable();
// Bitmap bmpImage = bmpDrawble.getBitmap();
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG,
100,outputStream);
byte[] imgeArr = outputStream.toByteArray();
//byte to bitmap
RetrofitClientResponseString client = RetrofitClientResponseString.getInstance();
Api api = client.getMyApi();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), imgeArr);

api.ImageSend("saveImagebinary",requestBody).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Toast.makeText(getContext(), ""+response.code(), Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(getContext(), ""+t, Toast.LENGTH_SHORT).show();
}
});
        
}

Image and other data send sql

app/src/main/java/com/example/app/min.class

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"imgeUriUserProfileActivity.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> callResponse<String> response) {
                
if(response.isSuccessful()){
                    Toast.makeText(getApplicationContext()
,
                            
response.body(),
                            
Toast.LENGTH_SHORT).show();
                
}
            }
            
@Override
            
public void onFailure(Call<String> callThrowable t) {

            }
        })
;

Request Camera Permission

app/src/main/java/com/example/app/main.class

private void requestCameraPermission() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);//CAMERA_PERMISSION_REQUEST_CODE=100
}
private boolean hasCameraPermission() {
return ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}

Calling on Activity Result Camera and Gallery

app/src/main/java/com/example/app/main.class

private static final int REQUEST_IMAGE_CAPTURE = 1;

private static final int REQUEST_IMAGE_SELECT = 2;
byte[] imgeArr;
Uri imgeUri;
@Override
    public void onActivityResult(int requestCode,
int resultCode,
@Nullable Intent data) {
//camera user
if(requestCode == REQUEST_IMAGE_CAPTURE){
if(resultCode == Activity.RESULT_OK){
Bundle bundleObj = data.getExtras();
Bitmap bmpImage = (Bitmap) bundleObj.get("data");
binding.imageViewUser.setImageBitmap(bmpImage);
//save database convert byte
BitmapDrawable bmpDrawble = (BitmapDrawable)
binding.imageViewUser.getDrawable();
// Bitmap bmpImage = bmpDrawble.getBitmap();
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG,
100,outputStream);
imgeArr = outputStream.toByteArray();
//byte to bitmap

}
}//gallery use code
else if(requestCode == REQUEST_IMAGE_SELECT){
if(resultCode == Activity.RESULT_OK){
imgeUri = data.getData();
binding.imageViewUser.setImageURI(imgeUri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}

AlterDialog Create  and show pic from camera and Gallery 

app/src/main/java/com/example/app/main.class

// 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(intentGALLERY_REQUEST_CODE);
        
}
        
else {

//open camera code
            Intent intent = 
new Intent(
                    MediaStore.
ACTION_IMAGE_CAPTURE);
            
startActivityForResult(intentCAMERA_REQUEST_CODE);
        
}

  }
})
;

//builde show
builde.show();

Capture image send api 

Camera Cpture image send api

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;
import com.example.meyepro.api.Api;
import com.example.meyepro.api.RetrofitClient;
import com.example.meyepro.databinding.ActivityTeacherAttendanceMarkBinding;
import com.example.meyepro.models.Attendance;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TeacherAttendanceMarkActivity extends AppCompatActivity {
ActivityTeacherAttendanceMarkBinding binding;
ArrayList<Attendance> attendances= new ArrayList<>();
Uri sourceUri;
MultipartBody.Part file = null;
private static final int CAMERA_REQUEST_CODE = 1;

private int openRequestCode = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// binding.progressBar.setVisibility(View.VISIBLE);
binding= ActivityTeacherAttendanceMarkBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// captureImage();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);


}

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


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
sourceUri = getImageUri(getApplicationContext(), photo);
if ( sourceUri != null) {
ApiCallingAttendanceMark();
// try {
// InputStream inputStream = getContentResolver().openInputStream( sourceUri);
// // rest of your code
// } catch (IOException e) {
// e.printStackTrace();
// }
} else {
Toast.makeText(this, "Unable to capture image.", Toast.LENGTH_SHORT).show();
}

}

}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage,
"Title", null);
return Uri.parse(path);
}

public void ApiCallingAttendanceMark(){
RetrofitClient client= RetrofitClient.getInstance();
Api api= client.getMyApi();

try {
file = api.prepareFilePart("file", sourceUri, getApplicationContext());
} catch (IOException e) {
e.printStackTrace();
}
api.mark_attendance(file).enqueue(new Callback<ArrayList<Attendance>>() {
@Override
public void onResponse(Call<ArrayList<Attendance>> call, Response<ArrayList<Attendance>> response) {
Toast.makeText(TeacherAttendanceMarkActivity.this, ""+response.code(), Toast.LENGTH_SHORT).show();

if(response.isSuccessful()){
attendances.clear();
attendances.addAll(response.body());
// ArrayAdapter<String> adapter = new ArrayAdapter(this,
// android.R.layout.simple_list_item_1, attendances);
// binding.listViewShow.setAdapter(adapter);

}
binding.progressBar.setVisibility(View.GONE);
}

@Override
public void onFailure(Call<ArrayList<Attendance>> call, Throwable t) {

binding.progressBar.setVisibility(View.GONE);
}
});
}



}


Upload XLX file Code 

@Multipart
@POST("api/add-timetable")
public Call<Map<String,String>> UploadTimetable(
@Part MultipartBody.Part file);

package com.example.meyepro.fragments.Admin.Setting.TimeTableUpload;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.meyepro.R;
import com.example.meyepro.api.Api;
import com.example.meyepro.api.RetrofitClient;
import com.example.meyepro.databinding.ActivityTeacherDashBoardBinding;
import com.example.meyepro.databinding.ActivityTimetableUploadBinding;

import java.io.IOException;
import java.util.Map;

import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TimetableUploadActivity extends AppCompatActivity {
ActivityTimetableUploadBinding Binding;
private int createRequestCode = 1;
private int openRequestCode = 2;
private Uri sourceUri;
private Uri targetUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Binding= ActivityTimetableUploadBinding.inflate(getLayoutInflater());
setContentView(Binding.getRoot());
Binding.btnUploadTimetable.setVisibility(View.INVISIBLE);
Binding.btnImageXlsx.setVisibility(View.INVISIBLE);

Binding.btnSelectTimetable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openFile();
}
});
Binding.btnUploadTimetable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RetrofitClient client= RetrofitClient.getInstance();
Api api= client.getMyApi();
MultipartBody.Part file = null;
try {
file = api.prepareFilePart("file", sourceUri, getApplicationContext());
} catch (IOException e) {
e.printStackTrace();
}
api.UploadTimetable(file).enqueue(new Callback<Map<String, String>>() {
@Override
public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
Toast.makeText(TimetableUploadActivity.this, ""+response.body().get("data"), Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Call<Map<String, String>> call, Throwable t) {
Toast.makeText(TimetableUploadActivity.this, ""+t.toString(), Toast.LENGTH_SHORT).show();
}
});

}
});

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == openRequestCode && resultCode == RESULT_OK) {
sourceUri = resultData.getData();
Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
Binding.btnUploadTimetable.setVisibility(View.VISIBLE);
Binding.btnImageXlsx.setVisibility(View.VISIBLE);
}

}
private void openFile() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
String[] mimeTypes = {"application/xml", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
startActivityForResult(Intent.createChooser(intent, "Select a file"), openRequestCode);


}

}

Get Data change unique data by name display unique object


@GET("api/add-timetable")
public Call<List<Assign_Graders_PF_Model>> graders.clone();

 call_graders.clone().enqueue(new Callback<List<Assign_Graders_PF_Model>>() {
                    @Override
                    public void onResponse(Call<List<Assign_Graders_PF_Model>> call, Response<List<Assign_Graders_PF_Model>> response) {
                        Toast.makeText(AssignGrader.this, "dcjsjscjk"+response.code(), Toast.LENGTH_SHORT).show();
                        if (!response.isSuccessful()){
                            return;
                        }

                        list_assigned_graders=response.body();
                        List<Assign_Graders_PF_Model> DataTeacher = new ArrayList<>();
                        Map<String, List<Assign_Graders_PF_Model>> groupedData = new HashMap<>();
                        for (Assign_Graders_PF_Model data : list_assigned_graders) {
                            if (!groupedData.containsKey(data.getTeacher_Name())) {
                                groupedData.put(data.getTeacher_Name(), new ArrayList<>());
                            }
                            groupedData.get(data.getTeacher_Name()).add(data);
                        }


                        // Create a set to store unique teacher names
                        Set<String> uniqueTeacherNames = new HashSet<>();

                        // Extract unique teacher names
                        for (Assign_Graders_PF_Model data : list_assigned_graders) {
                            uniqueTeacherNames.add(data.getTeacher_Name());
                        }

                        // Create a new list of objects with distinct teacher names
                        List<Assign_Graders_PF_Model> uniqueObjects = new ArrayList<>();
                        for (Assign_Graders_PF_Model data : list_assigned_graders) {
                            if (uniqueTeacherNames.contains(data.getTeacher_Name())) {
                                uniqueObjects.add(data);
                                uniqueTeacherNames.remove(data.getTeacher_Name());
                            }
                        }

                        Toast.makeText(AssignGrader.this, ""+uniqueObjects.size(), Toast.LENGTH_SHORT).show();
                        grader_view_adapter adapter=new grader_view_adapter(uniqueObjects,AssignGrader.this);
                        assignGraderBinding.recyclerviewAssignedGraderList.setAdapter(adapter);
                        LinearLayoutManager layoutManager=new LinearLayoutManager(AssignGrader.this,LinearLayoutManager.VERTICAL,false);
                        assignGraderBinding.recyclerviewAssignedGraderList.setLayoutManager(layoutManager);
                    }

                    @Override
                    public void onFailure(Call<List<Assign_Graders_PF_Model>> call, Throwable t) {
                        Toast.makeText(AssignGrader.this, "jjhkjkj"+t.toString(), Toast.LENGTH_SHORT).show();
                    }
                });

open the camera and capture an image in most programming languages or frameworks, you'll typically need to use platform-specific libraries or APIs. Since you haven't specified a particular programming language or platform, I'll provide a general example using the Android platform and Java.

Here's an example of how you can open the camera, capture an image, and obtain the URI (Uniform Resource Identifier) of the captured image:

@GET("api/dvr-details")
public Call<ArrayList<HashMap<String,Object>>> api_dvr_details();

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

Post a Comment

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