1f8c84b8b5f7565f11127bcaa95ca95e.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. Подключение retrofit
  2. implementation 'com.squareup.retrofit2:retrofit:2.9.0'
  3. implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
  4. table model
  5. прописать поля
  6. сделать 2 конструктора
  7. сделать конструктор для parcel (source.readInt())
  8. сделать геттеры и сеттеры
  9. сделать describeContents, writeToParcel(dest.writeInt(ID))
  10. прописать creator: public static final Parceable.Creator<tableGamesModel> CREATOR = Parceable.Creator<tableGamesModel>(){}
  11. там переопределить 2 метода createFromParcel (возвращает return new tableGamesModel(source)) и newArray(вместо 0 поставить size)
  12. adapter
  13. private context mContext;
  14. List<tableModel> tableList;
  15. Проставить поля генерейт
  16. public View getView(int position, View convertView, ViewGroup parent) {
  17. View v = View.inflate(mContext, R.layout.item_layout, null);
  18. TextView title = v.findViewById(R.id.titleTV);
  19. TextView cost = v.findViewById(R.id.costTV);
  20. TextView stock = v.findViewById(R.id.stockTV);
  21. TextView store = v.findViewById(R.id.storeTV);
  22. tableGamesModel games = gamesList.get(position);
  23. title.setText(games.getTitle());
  24. cost.setText(String.valueOf(games.getCost()));
  25. stock.setText(String.valueOf(games.getStockAvailability()));
  26. store.setText(String.valueOf(games.getAvailabilityInStore()));
  27. return v;
  28. }
  29. retrofit
  30. создаем интерфейс, делаем импорты
  31. import retrofit2.Call;
  32. import retrofit2.http.Body;
  33. import retrofit2.http.DELETE;
  34. import retrofit2.http.GET;
  35. import retrofit2.http.POST;
  36. import retrofit2.http.PUT;
  37. import retrofit2.http.Path;
  38. import retrofit2.http.Query;
  39. Пример написания методов:
  40. @GET("apps/{id}")
  41. Call<DataModal> getData(@Query("id") int id);
  42. @POST("items")
  43. Call<DataModal> createPost(@Body DataModal dataModal);
  44. @PUT("apps/{id}")
  45. Call<DataModal> updateData(@Path("id") int id, @Body DataModal dataModal);
  46. @DELETE("apps/{id}")
  47. Call<Void> deleteData(@Path("id") int id);
  48. для вывода в листвью
  49. private adapterView adapter;
  50. private List<tableGamesModel> gamesList = new ArrayList<>();
  51. ListView lvApps = findViewById(R.id.gamesLV);
  52. adapter = new adapterView(main_Activity.this, gamesList);
  53. lvApps.setAdapter(adapter);
  54. private class fillList extends AsyncTask<Void, Void, String>
  55. {
  56. @Override
  57. protected String doInBackground(Void... voids)
  58. {
  59. try {
  60. URL url =new URL("https://ngknn.ru:5001/NGKNN/МамшеваЮС/Экзамен/api/TableGames/sortByTableGames?typeOfSort={typeOfSort}&nameProduct={nameProduct}");
  61. HttpURLConnection connection =(HttpURLConnection)url.openConnection();
  62. BufferedReader reader =new BufferedReader(new InputStreamReader(connection.getInputStream()));
  63. StringBuffer result = new StringBuffer();
  64. String line = "";
  65. while((line = reader.readLine()) != null)
  66. {
  67. result.append(line);
  68. }
  69. return result.toString();
  70. }
  71. catch (Exception e) {
  72. return null;
  73. }
  74. }
  75. @Override
  76. protected void onPostExecute(String s)
  77. {
  78. super.onPostExecute(s);
  79. try {
  80. gamesList.clear();
  81. JSONArray temp =new JSONArray();
  82. for (int i=0;i <temp.length();i++)
  83. {
  84. JSONObject gameJS = temp.getJSONObject(i);
  85. tableGamesModel tempArr = new tableGamesModel(
  86. gameJS.getInt("ID"),
  87. gameJS.getString("Title"),
  88. gameJS.getInt("Cost"),
  89. gameJS.getInt("StockAvailability"),
  90. gameJS.getInt("AvailabilityInStore"),
  91. gameJS.getString("Description"),
  92. gameJS.getString("Reviews"),
  93. gameJS.getString("Image")
  94. );
  95. gamesList.add(tempArr);
  96. adapter.notifyDataSetInvalidated();
  97. }
  98. }
  99. catch (Exception e){
  100. }
  101. }
  102. }
  103. private Bitmap getUserImage(String encodedImg)
  104. {
  105. if(encodedImg!=null&& !encodedImg.equals("null")) {
  106. byte[] bytes = Base64.decode(encodedImg, Base64.DEFAULT);
  107. return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  108. }
  109. else
  110. {
  111. return null;
  112. }
  113. }
  114. Retrofit retrofit = new Retrofit.Builder()
  115. .baseUrl("https://ngknn.ru:5001/NGKNN/МорозовАВ/api/")
  116. .addConverterFactory(GsonConverterFactory.create())
  117. .build();
  118. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
  119. Call<DataModal> call = retrofitAPI.getData(MainActivity.index);
  120. call.enqueue(new Callback<DataModal>() {
  121. @Override
  122. public void onResponse(Call<DataModal> call, Response<DataModal> response) {
  123. id = response.body().getApp_id();
  124. appName.setText(response.body().getAppName());
  125. appAgeLimit.setText(Integer.valueOf(response.body().getAppAgeLimit()).toString());
  126. appPrice.setText(Double.valueOf(response.body().getAppPrice()).toString());
  127. encodedImage = response.body().getAppImage();
  128. if(response.body().getAppImage() == null)
  129. {
  130. image.setImageResource(R.drawable.empty);
  131. }
  132. else
  133. {
  134. image.setImageBitmap(getImgBitmap(response.body().getAppImage()));
  135. }
  136. }
  137. @Override
  138. public void onFailure(Call<DataModal> call, Throwable t) {
  139. }
  140. });
  141. image = findViewById(R.id.appImageIV);
  142. image.setOnClickListener(v -> {
  143. Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  144. intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  145. pickImg.launch(intent); });
  146. private final ActivityResultLauncher<Intent> pickImg = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
  147. if (result.getResultCode() == RESULT_OK) {
  148. if (result.getData() != null) {
  149. Uri uri = result.getData().getData();
  150. try {
  151. InputStream is = getContentResolver().openInputStream(uri);
  152. Bitmap bitmap = BitmapFactory.decodeStream(is);
  153. image.setImageBitmap(bitmap);
  154. encodedImage = encodeImage(bitmap);
  155. } catch (Exception e) {
  156. }
  157. }
  158. }
  159. });
  160. private String encodeImage(Bitmap bitmap) {
  161. int prevW = 150;
  162. int prevH = bitmap.getHeight() * prevW / bitmap.getWidth();
  163. Bitmap b = Bitmap.createScaledBitmap(bitmap, prevW, prevH, false);
  164. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  165. b.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
  166. byte[] bytes = byteArrayOutputStream.toByteArray();
  167. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  168. return Base64.getEncoder().encodeToString(bytes);
  169. }
  170. return "";
  171. }
  172. private Bitmap getImgBitmap(String encodedImg) {
  173. if (encodedImg != null) {
  174. byte[] bytes = new byte[0];
  175. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  176. bytes = Base64.getDecoder().decode(encodedImg);
  177. }
  178. return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  179. }
  180. return BitmapFactory.decodeResource(editApp.this.getResources(),
  181. R.drawable.empty);
  182. }
  183. private void deleteRecord(int index)
  184. {
  185. saveChangesBtn.setEnabled(false);
  186. deleteBtn.setEnabled(false);
  187. deletePhoto.setEnabled(false);
  188. Retrofit retrofit = new Retrofit.Builder()
  189. .baseUrl("https://ngknn.ru:5001/NGKNN/МорозовАВ/api/")
  190. .addConverterFactory(GsonConverterFactory.create())
  191. .build();
  192. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
  193. Call call = retrofitAPI.deleteData(index);
  194. call.enqueue(new Callback<DataModal>() {
  195. @Override
  196. public void onResponse(Call<DataModal> call, Response<DataModal> response) {
  197. if(!response.isSuccessful())
  198. {
  199. Toast.makeText(editApp.this, "При удание записи возникла ошибка", Toast.LENGTH_SHORT).show();
  200. return;
  201. }
  202. saveChangesBtn.setEnabled(false);
  203. deleteBtn.setEnabled(false);
  204. deletePhoto.setEnabled(false);
  205. Toast.makeText(editApp.this, "Удаление прошло успешно", Toast.LENGTH_SHORT).show();
  206. startActivity(new Intent(editApp.this, MainActivity.class));
  207. finish();
  208. }
  209. @Override
  210. public void onFailure(Call<DataModal> call, Throwable t) {
  211. }
  212. });
  213. }
  214. private void putChanges(int id, String appName, double appPrice, int appAgeLimit, String picture) {
  215. saveChangesBtn.setEnabled(false);
  216. deleteBtn.setEnabled(false);
  217. deletePhoto.setEnabled(false);
  218. Retrofit retrofit = new Retrofit.Builder()
  219. .baseUrl("https://ngknn.ru:5001/ngknn/морозовав/api/")
  220. .addConverterFactory(GsonConverterFactory.create())
  221. .build();
  222. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
  223. DataModal modal = new DataModal(id, appName, appPrice, appAgeLimit, picture);
  224. Call<DataModal> call = retrofitAPI.updateData(MainActivity.index, modal);
  225. call.enqueue(new Callback<DataModal>() {
  226. @Override
  227. public void onResponse(Call<DataModal> call, Response<DataModal> response) {
  228. if(response.isSuccessful())
  229. {
  230. saveChangesBtn.setEnabled(true);
  231. deleteBtn.setEnabled(true);
  232. deletePhoto.setEnabled(true);
  233. Toast.makeText(editApp.this, "Изменение прошло успешно", Toast.LENGTH_SHORT).show();
  234. startActivity(new Intent(editApp.this, MainActivity.class));
  235. finish();
  236. return;
  237. }
  238. Toast.makeText(editApp.this, "Произошла ошибка", Toast.LENGTH_SHORT).show();
  239. }
  240. @Override
  241. public void onFailure(Call<DataModal> call, Throwable t) {
  242. }
  243. });
  244. }