Новый текстовый документ.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. !!!!!ПОДКЛЮЧЕНИЕ RETROFIT В BUILD.GRADLE (MODULE:___.APP)!!!!!
  2. implementation 'com.squareup.retrofit2:retrofit:2.9.0'
  3. implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
  4. -----------------------------------------------------------------------------------
  5. !!!!!RETROFITAPI!!!!!
  6. import retrofit2.Call;
  7. import retrofit2.http.Body;
  8. import retrofit2.http.DELETE;
  9. import retrofit2.http.GET;
  10. import retrofit2.http.POST;
  11. import retrofit2.http.PUT;
  12. import retrofit2.http.Path;
  13. import retrofit2.http.Query;
  14. public interface RetrofitAPI {
  15. @POST("Hotels")
  16. Call<DataStorage> createPost(@Body DataStorage dataStorage);
  17. @GET("Hotels/{id}")
  18. Call<DataStorage> getData(@Query("id") int id);
  19. @PUT("Hotels/{id}")
  20. Call<DataStorage> updateData(@Path("id") int id, @Body DataStorage dataModal);
  21. @DELETE("Hotels/{id}")
  22. Call<Void> deleteData(@Path("id") int id);
  23. }
  24. -----------------------------------------------------------------------------------
  25. !!!ADAPTER!!!
  26. import android.content.Context;
  27. import android.content.Intent;
  28. import android.graphics.Bitmap;
  29. import android.graphics.BitmapFactory;
  30. import android.util.Base64;
  31. import android.view.View;
  32. import android.view.ViewGroup;
  33. import android.widget.BaseAdapter;
  34. import android.widget.ImageView;
  35. import android.widget.TextView;
  36. import java.util.List;
  37. public class AdapterHotel extends BaseAdapter {
  38. private Context mContext;
  39. List<DataStorage> hotelList;
  40. public AdapterHotel(Context mContext, List<DataStorage> listProduct) {
  41. this.mContext = mContext;
  42. this.hotelList = listProduct;
  43. }
  44. @Override
  45. public int getCount() {
  46. return hotelList.size();
  47. }
  48. @Override
  49. public Object getItem(int i) {
  50. return hotelList.get(i);
  51. }
  52. @Override
  53. public long getItemId(int i)
  54. {
  55. return hotelList.get(i).getID();
  56. }
  57. @Override
  58. public View getView(int i, View view, ViewGroup viewGroup)
  59. {
  60. View v = View.inflate(mContext,R.layout.item_layout,null);
  61. TextView tRoom = v.findViewById(R.id.txtRoom);
  62. TextView tCountPeoples = v.findViewById(R.id.txtCountPeoples);
  63. TextView tStatus = v.findViewById(R.id.txtStatus);
  64. ImageView img = v.findViewById(R.id.imgV);
  65. DataStorage dataStorage = hotelList.get(i);
  66. tRoom.setText(String.valueOf(dataStorage.getRoom()));
  67. tCountPeoples.setText(String.valueOf(dataStorage.getCount_Peoples()));
  68. tStatus.setText(dataStorage.getStatus());
  69. if(dataStorage.getImage().equals("null")){
  70. img.setImageResource(R.drawable.picture);
  71. }
  72. else {
  73. img.setImageBitmap(getUserImage(dataStorage.getImage()));
  74. }
  75. return v;
  76. }
  77. private Bitmap getUserImage(String encodedImg)
  78. {
  79. if(encodedImg!=null&& !encodedImg.equals("null")) {
  80. byte[] bytes = Base64.decode(encodedImg, Base64.DEFAULT);
  81. return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  82. }
  83. else
  84. {
  85. return null;
  86. }
  87. }
  88. }
  89. -----------------------------------------------------------------------------------
  90. !!!!!MAIN!!!!!
  91. import android.content.Intent;
  92. import android.os.AsyncTask;
  93. import android.os.Bundle;
  94. import android.text.Editable;
  95. import android.text.TextWatcher;
  96. import android.view.View;
  97. import android.widget.AdapterView;
  98. import android.widget.EditText;
  99. import android.widget.ListView;
  100. import androidx.appcompat.app.AppCompatActivity;
  101. import org.json.JSONArray;
  102. import org.json.JSONObject;
  103. import java.io.BufferedReader;
  104. import java.io.InputStreamReader;
  105. import java.net.HttpURLConnection;
  106. import java.net.URL;
  107. import java.util.ArrayList;
  108. import java.util.List;
  109. public class MainActivity extends AppCompatActivity {
  110. private AdapterHotel pAdapter;
  111. private List<DataStorage> listProduct = new ArrayList<>();
  112. public static Integer index;
  113. public EditText searchtxt;
  114. @Override
  115. protected void onCreate(Bundle savedInstanceState) {
  116. super.onCreate(savedInstanceState);
  117. setContentView(R.layout.activity_main);
  118. ListView ivHotel = findViewById(R.id.LV_HOTEL);//Находим лист в который будем класть наши объекты
  119. pAdapter = new AdapterHotel(MainActivity.this, listProduct); //Создаем объект нашего адаптера
  120. ivHotel.setAdapter(pAdapter); //Cвязывает подготовленный список с адаптером
  121. new GetProducts().execute(); //Подключение к нашей API в отдельном потоке
  122. searchtxt = findViewById(R.id.Searchtxt);
  123. searchtxt.addTextChangedListener(new TextWatcher() {
  124. @Override
  125. public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  126. }
  127. @Override
  128. public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  129. new GetProducts().execute();
  130. }
  131. @Override
  132. public void afterTextChanged(Editable editable) {
  133. }
  134. });
  135. ivHotel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  136. @Override
  137. public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
  138. index = (int) l;
  139. startActivity(new Intent(MainActivity.this,ChangePage.class));
  140. finish();
  141. }
  142. });
  143. }
  144. public class GetProducts extends AsyncTask<Void, Void, String> {
  145. @Override
  146. protected String doInBackground(Void... voids) {
  147. try {
  148. URL url = new URL("https://ngknn.ru:5001/NGKNN/ЛедровЕИ/api/apps/search?searchstring="+searchtxt.getText().toString());//Строка подключения к нашей API
  149. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //вызываем нашу API
  150. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  151. /*
  152. BufferedReader успрощает чтение текста из потока символов
  153. InputStreamReader преводит поток байтов в поток символов
  154. connection.getInputStream() получает поток байтов
  155. */
  156. StringBuilder result = new StringBuilder();
  157. String line = "";
  158. while ((line = reader.readLine()) != null) {
  159. result.append(line);//кладет строковое значение в потоке
  160. }
  161. return result.toString();
  162. } catch (Exception exception) {
  163. return null;
  164. }
  165. }
  166. @Override
  167. protected void onPostExecute(String s) {
  168. super.onPostExecute(s);
  169. try
  170. {
  171. listProduct.clear();
  172. JSONArray tempArray = new JSONArray(s);//преоброзование строки в json массив
  173. for (int i = 0;i<tempArray.length();i++)
  174. {
  175. JSONObject productJson = tempArray.getJSONObject(i);//Преобразование json объекта в нашу структуру
  176. DataStorage tempProduct = new DataStorage(
  177. productJson.getInt("ID"),
  178. productJson.getInt("Room"),
  179. productJson.getInt("Count_Peoples"),
  180. productJson.getString("Status"),
  181. productJson.getString("Image")
  182. );
  183. listProduct.add(tempProduct);
  184. pAdapter.notifyDataSetInvalidated();
  185. }
  186. } catch (Exception ignored) {
  187. }
  188. }
  189. }
  190. public void gotoaddRooms(View v){startActivity(new Intent(this,CreatePage.class)); finish();}
  191. }
  192. -----------------------------------------------------------------------------------
  193. !!!!!CREATEPAGE!!!!!
  194. import androidx.activity.result.ActivityResultLauncher;
  195. import androidx.activity.result.contract.ActivityResultContracts;
  196. import androidx.appcompat.app.AppCompatActivity;
  197. import retrofit2.Call;
  198. import retrofit2.Callback;
  199. import retrofit2.Response;
  200. import retrofit2.Retrofit;
  201. import retrofit2.converter.gson.GsonConverterFactory;
  202. import android.content.Intent;
  203. import android.graphics.Bitmap;
  204. import android.graphics.BitmapFactory;
  205. import android.net.Uri;
  206. import android.os.Build;
  207. import android.os.Bundle;
  208. import android.provider.MediaStore;
  209. import android.view.View;
  210. import android.widget.Button;
  211. import android.widget.CheckBox;
  212. import android.widget.EditText;
  213. import android.widget.ImageButton;
  214. import android.widget.ImageView;
  215. import android.widget.Toast;
  216. import java.io.ByteArrayOutputStream;
  217. import java.io.InputStream;
  218. import java.util.Base64;
  219. public class CreatePage extends AppCompatActivity {
  220. private EditText inRoom;
  221. private EditText inCountPeoples;
  222. private CheckBox bStatus;
  223. private Button btnCreate;
  224. private String status;
  225. private ImageView image;
  226. private String encodedImage;
  227. @Override
  228. protected void onCreate(Bundle savedInstanceState) {
  229. super.onCreate(savedInstanceState);
  230. setContentView(R.layout.activity_create_page);
  231. inRoom = findViewById(R.id.RoomInput);
  232. inCountPeoples =findViewById(R.id.CountPeopleInput);
  233. bStatus = findViewById(R.id.BoxStatus);
  234. btnCreate = findViewById(R.id.btn_create);
  235. image = findViewById(R.id.img);
  236. image.setOnClickListener(v -> {
  237. Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  238. intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  239. pickImg.launch(intent); });
  240. btnCreate.setOnClickListener(new View.OnClickListener() {
  241. @Override
  242. public void onClick(View v) {
  243. // validating if the text field is empty or not.
  244. if (inRoom.getText().toString().isEmpty() && inCountPeoples.getText().toString().isEmpty()) {
  245. Toast.makeText(CreatePage.this, "Все текстовые поля должны быть заполнены", Toast.LENGTH_SHORT).show();
  246. return;
  247. }
  248. // calling a method to post the data and passing our name and job.
  249. postData(inRoom.getText().toString(), inCountPeoples.getText().toString(),bStatus.isChecked());
  250. }
  251. });
  252. }
  253. private final ActivityResultLauncher<Intent> pickImg = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
  254. if (result.getResultCode() == RESULT_OK) {
  255. if (result.getData() != null) {
  256. Uri uri = result.getData().getData();
  257. try {
  258. InputStream is = getContentResolver().openInputStream(uri);
  259. Bitmap bitmap = BitmapFactory.decodeStream(is);
  260. image.setImageBitmap(bitmap);
  261. encodedImage = encodeImage(bitmap);
  262. } catch (Exception e) {
  263. }
  264. }
  265. }
  266. });
  267. private String encodeImage(Bitmap bitmap) {
  268. int prevW = 150;
  269. int prevH = bitmap.getHeight() * prevW / bitmap.getWidth();
  270. Bitmap b = Bitmap.createScaledBitmap(bitmap, prevW, prevH, false);
  271. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  272. b.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
  273. byte[] bytes = byteArrayOutputStream.toByteArray();
  274. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  275. return Base64.getEncoder().encodeToString(bytes);
  276. }
  277. return "";
  278. }
  279. private void postData(String room, String countPeoples, boolean check) {
  280. if(check){
  281. status = "Занято";
  282. }
  283. else{
  284. status = "Свободно";
  285. }
  286. // on below line we are creating a retrofit
  287. // builder and passing our base url
  288. Retrofit retrofit = new Retrofit.Builder()
  289. .baseUrl("https://ngknn.ru:5001/NGKNN/ЛедровЕИ/api/")
  290. // as we are sending data in json format so
  291. // we have to add Gson converter factory
  292. .addConverterFactory(GsonConverterFactory.create())
  293. // at last we are building our retrofit builder.
  294. .build();
  295. // below line is to create an instance for our retrofit api class.
  296. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
  297. // passing data from our text fields to our modal class.
  298. DataStorage dataStorage = new DataStorage(Integer.parseInt(room), Integer.parseInt(countPeoples), status, encodedImage);
  299. // calling a method to create a post and passing our modal class.
  300. Call<DataStorage> call = retrofitAPI.createPost(dataStorage);
  301. // on below line we are executing our method.
  302. call.enqueue(new Callback<DataStorage>() {
  303. @Override
  304. public void onResponse(Call<DataStorage> call, Response<DataStorage> response) {
  305. // this method is called when we get response from our api.
  306. Toast.makeText(CreatePage.this, "Запись добавлена", Toast.LENGTH_SHORT).show();
  307. // on below line we are setting empty text
  308. // to our both edit text.
  309. inRoom.setText("");
  310. inCountPeoples.setText("");
  311. bStatus.setChecked(false);
  312. startActivity(new Intent(CreatePage.this, MainActivity.class));
  313. finish();
  314. }
  315. @Override
  316. public void onFailure(Call<DataStorage> call, Throwable t) {
  317. // setting text to our text view when
  318. // we get error response from API.
  319. Toast.makeText(CreatePage.this, "Ошибка добавления", Toast.LENGTH_SHORT).show();
  320. }
  321. });
  322. }
  323. public void gotoMain(View v){startActivity(new Intent(this,MainActivity.class)); finish();}
  324. }
  325. -----------------------------------------------------------------------------------
  326. !!!!!DATASTORAGE!!!!!!
  327. public class DataStorage {
  328. private Integer ID;
  329. private Integer Room;
  330. private Integer Count_Peoples;
  331. private String Status;
  332. private String Image;
  333. public DataStorage(Integer ID,Integer Room, Integer Count_Peoples, String Status, String Image){
  334. this.ID = ID;
  335. this.Room = Room;
  336. this.Count_Peoples = Count_Peoples;
  337. this.Status = Status;
  338. this.Image = Image;
  339. }
  340. public DataStorage(Integer Room, Integer Count_Peoples, String Status, String Image){
  341. this.Room = Room;
  342. this.Count_Peoples = Count_Peoples;
  343. this.Status = Status;
  344. this.Image = Image;
  345. }
  346. public Integer getID(){
  347. return ID;
  348. }
  349. public void setID(Integer ID){
  350. this.ID = ID;
  351. }
  352. public Integer getRoom(){
  353. return Room;
  354. }
  355. public void setRoom(Integer Room){
  356. this.Room = Room;
  357. }
  358. public Integer getCount_Peoples(){
  359. return Count_Peoples;
  360. }
  361. public void setCount_Peoples(Integer Count_Peoples){
  362. this.Count_Peoples = Count_Peoples;
  363. }
  364. public String getStatus(){
  365. return Status;
  366. }
  367. public void setStatus(String Status){
  368. this.Status = Status;
  369. }
  370. public String getImage(){
  371. return Image;
  372. }
  373. public void setImage(String Image){
  374. this.Image = Image;
  375. }
  376. }