Advertisement
shlomibergic

deviceList

Sep 18th, 2019
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.26 KB | None | 0 0
  1. package com.repoai.myhome.Devices;
  2.  
  3. import androidx.annotation.NonNull;
  4. import androidx.annotation.Nullable;
  5. import androidx.appcompat.app.AlertDialog;
  6. import androidx.appcompat.app.AppCompatActivity;
  7. import androidx.core.app.ActivityCompat;
  8. import androidx.core.content.ContextCompat;
  9.  
  10. import android.Manifest;
  11. import android.content.Context;
  12. import android.content.DialogInterface;
  13. import android.content.Intent;
  14. import android.content.pm.PackageManager;
  15. import android.graphics.Bitmap;
  16. import android.graphics.BitmapFactory;
  17. import android.graphics.Matrix;
  18. import android.media.ExifInterface;
  19. import android.net.Uri;
  20. import android.os.AsyncTask;
  21. import android.os.Bundle;
  22. import android.os.Environment;
  23. import android.os.StrictMode;
  24. import android.provider.MediaStore;
  25. import android.util.Log;
  26. import android.view.LayoutInflater;
  27. import android.view.View;
  28. import android.widget.AdapterView;
  29. import android.widget.ImageButton;
  30. import android.widget.ImageView;
  31. import android.widget.ListView;
  32. import android.widget.TextView;
  33. import android.widget.Toast;
  34.  
  35. import com.backendless.Backendless;
  36. import com.backendless.async.callback.AsyncCallback;
  37. import com.backendless.exceptions.BackendlessFault;
  38. import com.backendless.files.BackendlessFile;
  39. import com.backendless.persistence.DataQueryBuilder;
  40. import com.repoai.myhome.R;
  41. import com.repoai.myhome.Rooms.Rooms;
  42. import com.sdsmdg.tastytoast.TastyToast;
  43.  
  44. import java.io.BufferedInputStream;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.net.URL;
  49. import java.util.ArrayList;
  50. import java.util.HashMap;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.UUID;
  54.  
  55. public class DeviceList extends AppCompatActivity {
  56. Context context;
  57. List<Devices> deviceList;
  58. List<DeviceTypes> deviceTypesList;
  59. ListView myDeviceList;
  60. String roomName;
  61. ImageButton imageButton;
  62. boolean hasCamera = false;
  63. String fileName;
  64. String roomUUID;
  65. Rooms myRoom;
  66. TextView numODevices;
  67. Bitmap b;
  68. ImageView myImage;
  69.  
  70. @Override
  71. protected void onCreate(Bundle savedInstanceState) {
  72. super.onCreate(savedInstanceState);
  73. setContentView(R.layout.activity_device_list);
  74. this.roomName = getIntent().getStringExtra("roomName");
  75. this.roomUUID = getIntent().getStringExtra("roomUUID");
  76. setPointer();
  77. numODevices=findViewById(R.id.roomItemDevices);
  78. getPermissions();
  79. }
  80.  
  81. private void getPermissions() {
  82. List<String> listPermissionNeeded = new ArrayList<>();
  83. //check if we have permission
  84. int camPerm = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
  85. int writePerm = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
  86. int readPerm = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
  87. if (camPerm != PackageManager.PERMISSION_GRANTED) {
  88. listPermissionNeeded.add(Manifest.permission.CAMERA);
  89. }
  90. if (writePerm != PackageManager.PERMISSION_GRANTED) {
  91. listPermissionNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
  92. }
  93. if (readPerm != PackageManager.PERMISSION_GRANTED) {
  94. listPermissionNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
  95. }
  96. if (listPermissionNeeded.isEmpty()) {
  97. hasCamera = true;
  98. } else {
  99. ActivityCompat.requestPermissions(this, listPermissionNeeded.toArray(new String[listPermissionNeeded.size()]), 100);
  100. }
  101. }
  102.  
  103. @Override
  104. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  105. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  106. //fire the camera dispatch
  107. hasCamera = true;
  108. } else {
  109. Toast.makeText(context, "you need to grant all permissions", Toast.LENGTH_SHORT).show();
  110. }
  111. }
  112.  
  113. private void getData() {
  114. String whereClause = "objectId = '" + this.roomUUID + "'";
  115. DataQueryBuilder queryBuilder = DataQueryBuilder.create();
  116. queryBuilder.setWhereClause(whereClause);
  117. queryBuilder.setPageSize(100);
  118.  
  119. Backendless.Data.of(Rooms.class).find(queryBuilder, new AsyncCallback<List<Rooms>>() {
  120. @Override
  121. public void handleResponse(List<Rooms> response) {
  122. myRoom = response.get(0);
  123. deviceList = myRoom.getDevices();
  124. DeviceAdapter adapter = new DeviceAdapter(context, deviceList);
  125. myDeviceList.setAdapter(adapter);
  126. }
  127.  
  128. @Override
  129. public void handleFault(BackendlessFault fault) {
  130. TastyToast.makeText(context, fault.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
  131. }
  132. });
  133. }
  134.  
  135. private void setPointer() {
  136.  
  137. this.context = this;
  138. setMyDevices();
  139. myDeviceList = findViewById(R.id.lstDevices);
  140. ((TextView) findViewById(R.id.devicesRoomName)).setText(this.roomName);
  141. findViewById(R.id.addDevice).setOnClickListener(view -> addNewDeviceDialog());
  142. findViewById(R.id.imageButton).setOnClickListener(new View.OnClickListener() {
  143. @Override
  144. public void onClick(View view) {
  145. if (hasCamera) {
  146. takePhoto();
  147. } else {
  148. TastyToast.makeText(context, "We dont have camera permissions", TastyToast.LENGTH_LONG, TastyToast.CONFUSING).show();
  149. getPermissions();
  150. }
  151. }
  152. });
  153. getData();
  154. }
  155.  
  156. public class information extends AsyncTask<String, String, String> {
  157. @Override
  158. protected String doInBackground(String... arg0) {
  159.  
  160. try{
  161. URL url = new URL("https://backendlessappcontent.com/344AF76F-1202-003F-FF47-57AD623DE600/25FDFC2D-BDFA-80C0-FFDD-DEA6915E2200/files/rooms/"+roomName+".jpg");
  162. InputStream is = new BufferedInputStream(url.openStream());
  163. Bitmap b = BitmapFactory.decodeStream(is);
  164.  
  165. } catch(Exception e){}
  166. return null;
  167. }
  168.  
  169. @Override
  170. protected void onPostExecute(String result) {
  171. if(b==null){
  172. myImage.setImageResource(R.drawable.living_room);
  173. }else {
  174. myImage.setImageBitmap(b);
  175. }
  176.  
  177. }
  178. }
  179.  
  180. public void takePhoto() {
  181. //to avoid api26 policy restrictions.
  182. StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
  183. StrictMode.setVmPolicy(builder.build());
  184. //we call the android image capture
  185. Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
  186. //we creating a filename so we can use it later on and put the picture inside the imageView
  187. fileName = Environment.getExternalStorageDirectory() + File.separator + UUID.randomUUID().toString() + ".jpg";
  188. File file = new File(fileName);
  189. //we setting a global pointer to the file location
  190. intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
  191. //since it can create exception, we surroud it with try/catch block to avoid exception and application crash
  192. try {
  193. startActivityForResult(intent, 200);
  194. } catch (Exception e) {
  195. Log.e("camera", "dispatchTakeImageIntent: error in dispatch camera");
  196. }
  197.  
  198. }
  199.  
  200. private void setMyDevices() {
  201. deviceTypesList = new ArrayList<>();
  202. deviceTypesList.add(new DeviceTypes("TV", R.drawable.tv));
  203. deviceTypesList.add(new DeviceTypes("Curtain", R.drawable.curtain));
  204. deviceTypesList.add(new DeviceTypes("Light", R.drawable.light));
  205. deviceTypesList.add(new DeviceTypes("Boiler", R.drawable.boiler));
  206. deviceTypesList.add(new DeviceTypes("Air Condition", R.drawable.aircondition));
  207.  
  208. }
  209.  
  210. private void addNewDeviceDialog() {
  211. AlertDialog.Builder builder = new AlertDialog.Builder(context);
  212. builder.setTitle("Add Device to the Room");
  213. //create the view for the alert dialog
  214. View myView = LayoutInflater.from(context).inflate(R.layout.new_device_list, null);
  215. //create the view
  216. ListView myDevicesTypeList = myView.findViewById(R.id.deviceTypeList);
  217. DeviceTypesAdapter myAdapter = new DeviceTypesAdapter(context, deviceTypesList);
  218. myDevicesTypeList.setAdapter(myAdapter);
  219.  
  220. //create the builder
  221. builder.setView(myView);
  222. builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  223. @Override
  224. public void onClick(DialogInterface dialogInterface, int i) {
  225. dialogInterface.dismiss();
  226. }
  227. });
  228. final AlertDialog deviceDialog = builder.create();
  229. deviceDialog.show();
  230.  
  231. //handle on item click
  232. myDevicesTypeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  233. @Override
  234. public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
  235. //deviceDialog.dismiss();
  236. //Log.e("item", "onItemClick: " + deviceList.get(index).getDeviceName());
  237. //add device by type:
  238. Devices newDevice = new Devices();
  239. switch (index) {
  240. case 0:
  241. newDevice.setDeviceName("Tv");
  242. //newDevice.setDeviceIcon(R.drawable.tv);
  243. break;
  244. case 1:
  245. newDevice.setDeviceName("Curtain");
  246. //newDevice.setDeviceIcon(R.drawable.curtain);
  247. break;
  248.  
  249. case 2:
  250. newDevice.setDeviceName("Light");
  251. //newDevice.setDeviceIcon(R.drawable.light);
  252. break;
  253.  
  254. case 3:
  255. newDevice.setDeviceName("Boiler");
  256. //newDevice.setDeviceIcon(R.drawable.boiler);
  257. break;
  258.  
  259. case 4:
  260. newDevice.setDeviceName("Air Condition");
  261. //newDevice.setDeviceIcon(R.drawable.aircondition);
  262. break;
  263.  
  264. }
  265. newDevice.saveAsync(new AsyncCallback<Devices>() {
  266. @Override
  267. public void handleResponse(Devices response) {
  268. TastyToast.makeText(context, "Device list was updated", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
  269. //parent
  270. HashMap<String, Object> parentObject = new HashMap<String, Object>();
  271. parentObject.put("objectId", getIntent().getStringExtra("roomUUID"));
  272. //child
  273. HashMap<String, Object> childObject = new HashMap<String, Object>();
  274. childObject.put("objectId", response.getObjectId());
  275. //set children list (in our case only one child)
  276. ArrayList<Map> childrens = new ArrayList<>();
  277. childrens.add(childObject);
  278. //create a relation between father and child
  279. Backendless.Data.of("Rooms").setRelation(parentObject, "devices", childrens,
  280. new AsyncCallback<Integer>() {
  281. @Override
  282. public void handleResponse(Integer response) {
  283. Log.e("relation", "handleResponse: created");
  284. }
  285.  
  286. @Override
  287. public void handleFault(BackendlessFault fault) {
  288. Log.e("MYAPP", "server reported an error - " + fault.getMessage());
  289. }
  290. });
  291.  
  292. }
  293.  
  294. @Override
  295. public void handleFault(BackendlessFault fault) {
  296. TastyToast.makeText(context, fault.getMessage() , TastyToast.LENGTH_LONG, TastyToast.CONFUSING).show();
  297.  
  298. }
  299. });
  300. deviceDialog.dismiss();
  301. deviceList.add(newDevice);
  302. DeviceAdapter adapter = new DeviceAdapter(context, deviceList);
  303. myDeviceList.setAdapter(adapter);
  304.  
  305. }
  306. });
  307.  
  308. }
  309.  
  310. @Override
  311. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  312. super.onActivityResult(requestCode, resultCode, data);
  313. if (requestCode == 200) {
  314. try {
  315. //get our saved file into a bitmap object
  316. Log.e("file", "onActivityResult: " + fileName);
  317. final File file = new File(fileName);
  318.  
  319. //read the image from the file and convert it to bitmap
  320. Bitmap myBitmap = BitmapFactory.decodeFile(fileName);
  321.  
  322. //get exif data (extra information) from the image so we will know the oriention of the image
  323. ExifInterface exif = null;
  324. try {
  325. exif = new ExifInterface(fileName);
  326. } catch (IOException e) {
  327. e.printStackTrace();
  328. }
  329.  
  330. assert exif != null;
  331. //get the image orienation
  332. int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
  333. //we will rotate the image with method
  334. Bitmap bm = rotateImage(myBitmap, orientation);
  335. //myImage.setImageBitmap(bm);
  336. ((ImageView) findViewById(R.id.roomImage)).setImageBitmap(bm);
  337. //save new image to backendless
  338. Backendless.Files.Android.upload(bm, Bitmap.CompressFormat.JPEG, 50, roomName + ".jpg", "rooms",true, new AsyncCallback<BackendlessFile>() {
  339. @Override
  340. public void handleResponse(BackendlessFile response) {
  341. ((ImageView) findViewById(R.id.roomImage)).setImageBitmap(bm);
  342. Log.e("image", "handleResponse: " + response.getFileURL());
  343. }
  344.  
  345. @Override
  346. public void handleFault(BackendlessFault fault) {
  347.  
  348. }
  349. });
  350.  
  351. } catch (Exception e) {
  352. e.printStackTrace();
  353. }
  354. }
  355. }
  356.  
  357. private Bitmap rotateImage(Bitmap myBitmap, int orientation) {
  358. //we create a matrix, so we can put the image on it and just rotate
  359. //it will be faster then copy pixel by pixel
  360. Matrix matrix = new Matrix();
  361. //depending on the orientation that we got from the exif we will rotate
  362. //in this sample we will deall with all kind of rotating from api 15 to api 29
  363. switch (orientation) {
  364. case ExifInterface.ORIENTATION_NORMAL:
  365. //all is o.k. no need to rotate just return the image
  366. break;
  367. case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
  368. //flip the matrix horzintal
  369. matrix.setScale(-1, 1);
  370. break;
  371. case ExifInterface.ORIENTATION_ROTATE_180:
  372. //rotate the matrix 180 degress
  373. matrix.setRotate(180);
  374. break;
  375. case ExifInterface.ORIENTATION_FLIP_VERTICAL:
  376. //flip the matrix vertical
  377. matrix.setRotate(180);
  378. matrix.postScale(-1, 1);
  379. break;
  380. case ExifInterface.ORIENTATION_TRANSPOSE:
  381. //rotate 90 degress and flip
  382. matrix.setRotate(90);
  383. matrix.postScale(-1, 1);
  384. break;
  385. case ExifInterface.ORIENTATION_ROTATE_90:
  386. //rotate 90 degress and flip
  387. matrix.setRotate(90);
  388. break;
  389. case ExifInterface.ORIENTATION_TRANSVERSE:
  390. //rotate 90 degress to other side and flip
  391. matrix.setRotate(-90);
  392. matrix.postScale(-1, 1);
  393. break;
  394. case ExifInterface.ORIENTATION_ROTATE_270:
  395. //rotate 90 degres to other side
  396. matrix.setRotate(-90);
  397. break;
  398. default:
  399. return myBitmap;
  400. }
  401. try {
  402. //create an image from our rotated matrix
  403. Bitmap bmRotated = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true);
  404. //recycke the data by calling a garbage collector
  405. //in this case, we free memory for big pictures
  406. myBitmap.recycle();
  407. //return the rotated image
  408. return bmRotated;
  409. } catch (OutOfMemoryError e) {
  410. //if we have a memory leak , we need to know about it
  411. e.printStackTrace();
  412. return myBitmap;
  413. }
  414. }
  415. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement