Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.repoai.myhome.Devices;
- import androidx.annotation.NonNull;
- import androidx.annotation.Nullable;
- import androidx.appcompat.app.AlertDialog;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.core.app.ActivityCompat;
- import androidx.core.content.ContextCompat;
- import android.Manifest;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Matrix;
- import android.media.ExifInterface;
- import android.net.Uri;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.os.Environment;
- import android.os.StrictMode;
- import android.provider.MediaStore;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ImageButton;
- import android.widget.ImageView;
- import android.widget.ListView;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.backendless.Backendless;
- import com.backendless.async.callback.AsyncCallback;
- import com.backendless.exceptions.BackendlessFault;
- import com.backendless.files.BackendlessFile;
- import com.backendless.persistence.DataQueryBuilder;
- import com.repoai.myhome.R;
- import com.repoai.myhome.Rooms.Rooms;
- import com.sdsmdg.tastytoast.TastyToast;
- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.UUID;
- public class DeviceList extends AppCompatActivity {
- Context context;
- List<Devices> deviceList;
- List<DeviceTypes> deviceTypesList;
- ListView myDeviceList;
- String roomName;
- ImageButton imageButton;
- boolean hasCamera = false;
- String fileName;
- String roomUUID;
- Rooms myRoom;
- TextView numODevices;
- Bitmap b;
- ImageView myImage;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_device_list);
- this.roomName = getIntent().getStringExtra("roomName");
- this.roomUUID = getIntent().getStringExtra("roomUUID");
- setPointer();
- numODevices=findViewById(R.id.roomItemDevices);
- getPermissions();
- }
- private void getPermissions() {
- List<String> listPermissionNeeded = new ArrayList<>();
- //check if we have permission
- int camPerm = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
- int writePerm = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
- int readPerm = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
- if (camPerm != PackageManager.PERMISSION_GRANTED) {
- listPermissionNeeded.add(Manifest.permission.CAMERA);
- }
- if (writePerm != PackageManager.PERMISSION_GRANTED) {
- listPermissionNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
- }
- if (readPerm != PackageManager.PERMISSION_GRANTED) {
- listPermissionNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
- }
- if (listPermissionNeeded.isEmpty()) {
- hasCamera = true;
- } else {
- ActivityCompat.requestPermissions(this, listPermissionNeeded.toArray(new String[listPermissionNeeded.size()]), 100);
- }
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- //fire the camera dispatch
- hasCamera = true;
- } else {
- Toast.makeText(context, "you need to grant all permissions", Toast.LENGTH_SHORT).show();
- }
- }
- private void getData() {
- String whereClause = "objectId = '" + this.roomUUID + "'";
- DataQueryBuilder queryBuilder = DataQueryBuilder.create();
- queryBuilder.setWhereClause(whereClause);
- queryBuilder.setPageSize(100);
- Backendless.Data.of(Rooms.class).find(queryBuilder, new AsyncCallback<List<Rooms>>() {
- @Override
- public void handleResponse(List<Rooms> response) {
- myRoom = response.get(0);
- deviceList = myRoom.getDevices();
- DeviceAdapter adapter = new DeviceAdapter(context, deviceList);
- myDeviceList.setAdapter(adapter);
- }
- @Override
- public void handleFault(BackendlessFault fault) {
- TastyToast.makeText(context, fault.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
- }
- });
- }
- private void setPointer() {
- this.context = this;
- setMyDevices();
- myDeviceList = findViewById(R.id.lstDevices);
- ((TextView) findViewById(R.id.devicesRoomName)).setText(this.roomName);
- findViewById(R.id.addDevice).setOnClickListener(view -> addNewDeviceDialog());
- findViewById(R.id.imageButton).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (hasCamera) {
- takePhoto();
- } else {
- TastyToast.makeText(context, "We dont have camera permissions", TastyToast.LENGTH_LONG, TastyToast.CONFUSING).show();
- getPermissions();
- }
- }
- });
- getData();
- }
- public class information extends AsyncTask<String, String, String> {
- @Override
- protected String doInBackground(String... arg0) {
- try{
- URL url = new URL("https://backendlessappcontent.com/344AF76F-1202-003F-FF47-57AD623DE600/25FDFC2D-BDFA-80C0-FFDD-DEA6915E2200/files/rooms/"+roomName+".jpg");
- InputStream is = new BufferedInputStream(url.openStream());
- Bitmap b = BitmapFactory.decodeStream(is);
- } catch(Exception e){}
- return null;
- }
- @Override
- protected void onPostExecute(String result) {
- if(b==null){
- myImage.setImageResource(R.drawable.living_room);
- }else {
- myImage.setImageBitmap(b);
- }
- }
- }
- public void takePhoto() {
- //to avoid api26 policy restrictions.
- StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
- StrictMode.setVmPolicy(builder.build());
- //we call the android image capture
- Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
- //we creating a filename so we can use it later on and put the picture inside the imageView
- fileName = Environment.getExternalStorageDirectory() + File.separator + UUID.randomUUID().toString() + ".jpg";
- File file = new File(fileName);
- //we setting a global pointer to the file location
- intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
- //since it can create exception, we surroud it with try/catch block to avoid exception and application crash
- try {
- startActivityForResult(intent, 200);
- } catch (Exception e) {
- Log.e("camera", "dispatchTakeImageIntent: error in dispatch camera");
- }
- }
- private void setMyDevices() {
- deviceTypesList = new ArrayList<>();
- deviceTypesList.add(new DeviceTypes("TV", R.drawable.tv));
- deviceTypesList.add(new DeviceTypes("Curtain", R.drawable.curtain));
- deviceTypesList.add(new DeviceTypes("Light", R.drawable.light));
- deviceTypesList.add(new DeviceTypes("Boiler", R.drawable.boiler));
- deviceTypesList.add(new DeviceTypes("Air Condition", R.drawable.aircondition));
- }
- private void addNewDeviceDialog() {
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle("Add Device to the Room");
- //create the view for the alert dialog
- View myView = LayoutInflater.from(context).inflate(R.layout.new_device_list, null);
- //create the view
- ListView myDevicesTypeList = myView.findViewById(R.id.deviceTypeList);
- DeviceTypesAdapter myAdapter = new DeviceTypesAdapter(context, deviceTypesList);
- myDevicesTypeList.setAdapter(myAdapter);
- //create the builder
- builder.setView(myView);
- builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i) {
- dialogInterface.dismiss();
- }
- });
- final AlertDialog deviceDialog = builder.create();
- deviceDialog.show();
- //handle on item click
- myDevicesTypeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
- //deviceDialog.dismiss();
- //Log.e("item", "onItemClick: " + deviceList.get(index).getDeviceName());
- //add device by type:
- Devices newDevice = new Devices();
- switch (index) {
- case 0:
- newDevice.setDeviceName("Tv");
- //newDevice.setDeviceIcon(R.drawable.tv);
- break;
- case 1:
- newDevice.setDeviceName("Curtain");
- //newDevice.setDeviceIcon(R.drawable.curtain);
- break;
- case 2:
- newDevice.setDeviceName("Light");
- //newDevice.setDeviceIcon(R.drawable.light);
- break;
- case 3:
- newDevice.setDeviceName("Boiler");
- //newDevice.setDeviceIcon(R.drawable.boiler);
- break;
- case 4:
- newDevice.setDeviceName("Air Condition");
- //newDevice.setDeviceIcon(R.drawable.aircondition);
- break;
- }
- newDevice.saveAsync(new AsyncCallback<Devices>() {
- @Override
- public void handleResponse(Devices response) {
- TastyToast.makeText(context, "Device list was updated", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
- //parent
- HashMap<String, Object> parentObject = new HashMap<String, Object>();
- parentObject.put("objectId", getIntent().getStringExtra("roomUUID"));
- //child
- HashMap<String, Object> childObject = new HashMap<String, Object>();
- childObject.put("objectId", response.getObjectId());
- //set children list (in our case only one child)
- ArrayList<Map> childrens = new ArrayList<>();
- childrens.add(childObject);
- //create a relation between father and child
- Backendless.Data.of("Rooms").setRelation(parentObject, "devices", childrens,
- new AsyncCallback<Integer>() {
- @Override
- public void handleResponse(Integer response) {
- Log.e("relation", "handleResponse: created");
- }
- @Override
- public void handleFault(BackendlessFault fault) {
- Log.e("MYAPP", "server reported an error - " + fault.getMessage());
- }
- });
- }
- @Override
- public void handleFault(BackendlessFault fault) {
- TastyToast.makeText(context, fault.getMessage() , TastyToast.LENGTH_LONG, TastyToast.CONFUSING).show();
- }
- });
- deviceDialog.dismiss();
- deviceList.add(newDevice);
- DeviceAdapter adapter = new DeviceAdapter(context, deviceList);
- myDeviceList.setAdapter(adapter);
- }
- });
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == 200) {
- try {
- //get our saved file into a bitmap object
- Log.e("file", "onActivityResult: " + fileName);
- final File file = new File(fileName);
- //read the image from the file and convert it to bitmap
- Bitmap myBitmap = BitmapFactory.decodeFile(fileName);
- //get exif data (extra information) from the image so we will know the oriention of the image
- ExifInterface exif = null;
- try {
- exif = new ExifInterface(fileName);
- } catch (IOException e) {
- e.printStackTrace();
- }
- assert exif != null;
- //get the image orienation
- int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
- //we will rotate the image with method
- Bitmap bm = rotateImage(myBitmap, orientation);
- //myImage.setImageBitmap(bm);
- ((ImageView) findViewById(R.id.roomImage)).setImageBitmap(bm);
- //save new image to backendless
- Backendless.Files.Android.upload(bm, Bitmap.CompressFormat.JPEG, 50, roomName + ".jpg", "rooms",true, new AsyncCallback<BackendlessFile>() {
- @Override
- public void handleResponse(BackendlessFile response) {
- ((ImageView) findViewById(R.id.roomImage)).setImageBitmap(bm);
- Log.e("image", "handleResponse: " + response.getFileURL());
- }
- @Override
- public void handleFault(BackendlessFault fault) {
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- private Bitmap rotateImage(Bitmap myBitmap, int orientation) {
- //we create a matrix, so we can put the image on it and just rotate
- //it will be faster then copy pixel by pixel
- Matrix matrix = new Matrix();
- //depending on the orientation that we got from the exif we will rotate
- //in this sample we will deall with all kind of rotating from api 15 to api 29
- switch (orientation) {
- case ExifInterface.ORIENTATION_NORMAL:
- //all is o.k. no need to rotate just return the image
- break;
- case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
- //flip the matrix horzintal
- matrix.setScale(-1, 1);
- break;
- case ExifInterface.ORIENTATION_ROTATE_180:
- //rotate the matrix 180 degress
- matrix.setRotate(180);
- break;
- case ExifInterface.ORIENTATION_FLIP_VERTICAL:
- //flip the matrix vertical
- matrix.setRotate(180);
- matrix.postScale(-1, 1);
- break;
- case ExifInterface.ORIENTATION_TRANSPOSE:
- //rotate 90 degress and flip
- matrix.setRotate(90);
- matrix.postScale(-1, 1);
- break;
- case ExifInterface.ORIENTATION_ROTATE_90:
- //rotate 90 degress and flip
- matrix.setRotate(90);
- break;
- case ExifInterface.ORIENTATION_TRANSVERSE:
- //rotate 90 degress to other side and flip
- matrix.setRotate(-90);
- matrix.postScale(-1, 1);
- break;
- case ExifInterface.ORIENTATION_ROTATE_270:
- //rotate 90 degres to other side
- matrix.setRotate(-90);
- break;
- default:
- return myBitmap;
- }
- try {
- //create an image from our rotated matrix
- Bitmap bmRotated = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true);
- //recycke the data by calling a garbage collector
- //in this case, we free memory for big pictures
- myBitmap.recycle();
- //return the rotated image
- return bmRotated;
- } catch (OutOfMemoryError e) {
- //if we have a memory leak , we need to know about it
- e.printStackTrace();
- return myBitmap;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement