Advertisement
shlomibergic

deviceList

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