!!!!!ПОДКЛЮЧЕНИЕ RETROFIT В BUILD.GRADLE (MODULE:___.APP)!!!!! implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' ----------------------------------------------------------------------------------- !!!!!RETROFITAPI!!!!! import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; import retrofit2.http.Query; public interface RetrofitAPI { @POST("Hotels") Call createPost(@Body DataStorage dataStorage); @GET("Hotels/{id}") Call getData(@Query("id") int id); @PUT("Hotels/{id}") Call updateData(@Path("id") int id, @Body DataStorage dataModal); @DELETE("Hotels/{id}") Call deleteData(@Path("id") int id); } ----------------------------------------------------------------------------------- !!!ADAPTER!!! import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class AdapterHotel extends BaseAdapter { private Context mContext; List hotelList; public AdapterHotel(Context mContext, List listProduct) { this.mContext = mContext; this.hotelList = listProduct; } @Override public int getCount() { return hotelList.size(); } @Override public Object getItem(int i) { return hotelList.get(i); } @Override public long getItemId(int i) { return hotelList.get(i).getID(); } @Override public View getView(int i, View view, ViewGroup viewGroup) { View v = View.inflate(mContext,R.layout.item_layout,null); TextView tRoom = v.findViewById(R.id.txtRoom); TextView tCountPeoples = v.findViewById(R.id.txtCountPeoples); TextView tStatus = v.findViewById(R.id.txtStatus); ImageView img = v.findViewById(R.id.imgV); DataStorage dataStorage = hotelList.get(i); tRoom.setText(String.valueOf(dataStorage.getRoom())); tCountPeoples.setText(String.valueOf(dataStorage.getCount_Peoples())); tStatus.setText(dataStorage.getStatus()); if(dataStorage.getImage().equals("null")){ img.setImageResource(R.drawable.picture); } else { img.setImageBitmap(getUserImage(dataStorage.getImage())); } return v; } private Bitmap getUserImage(String encodedImg) { if(encodedImg!=null&& !encodedImg.equals("null")) { byte[] bytes = Base64.decode(encodedImg, Base64.DEFAULT); return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } else { return null; } } } ----------------------------------------------------------------------------------- !!!!!MAIN!!!!! import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private AdapterHotel pAdapter; private List listProduct = new ArrayList<>(); public static Integer index; public EditText searchtxt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView ivHotel = findViewById(R.id.LV_HOTEL);//Находим лист в который будем класть наши объекты pAdapter = new AdapterHotel(MainActivity.this, listProduct); //Создаем объект нашего адаптера ivHotel.setAdapter(pAdapter); //Cвязывает подготовленный список с адаптером new GetProducts().execute(); //Подключение к нашей API в отдельном потоке searchtxt = findViewById(R.id.Searchtxt); searchtxt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { new GetProducts().execute(); } @Override public void afterTextChanged(Editable editable) { } }); ivHotel.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { index = (int) l; startActivity(new Intent(MainActivity.this,ChangePage.class)); finish(); } }); } public class GetProducts extends AsyncTask { @Override protected String doInBackground(Void... voids) { try { URL url = new URL("https://ngknn.ru:5001/NGKNN/ЛедровЕИ/api/apps/search?searchstring="+searchtxt.getText().toString());//Строка подключения к нашей API HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //вызываем нашу API BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); /* BufferedReader успрощает чтение текста из потока символов InputStreamReader преводит поток байтов в поток символов connection.getInputStream() получает поток байтов */ StringBuilder result = new StringBuilder(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line);//кладет строковое значение в потоке } return result.toString(); } catch (Exception exception) { return null; } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); try { listProduct.clear(); JSONArray tempArray = new JSONArray(s);//преоброзование строки в json массив for (int i = 0;i { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); pickImg.launch(intent); }); btnCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // validating if the text field is empty or not. if (inRoom.getText().toString().isEmpty() && inCountPeoples.getText().toString().isEmpty()) { Toast.makeText(CreatePage.this, "Все текстовые поля должны быть заполнены", Toast.LENGTH_SHORT).show(); return; } // calling a method to post the data and passing our name and job. postData(inRoom.getText().toString(), inCountPeoples.getText().toString(),bStatus.isChecked()); } }); } private final ActivityResultLauncher pickImg = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == RESULT_OK) { if (result.getData() != null) { Uri uri = result.getData().getData(); try { InputStream is = getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(is); image.setImageBitmap(bitmap); encodedImage = encodeImage(bitmap); } catch (Exception e) { } } } }); private String encodeImage(Bitmap bitmap) { int prevW = 150; int prevH = bitmap.getHeight() * prevW / bitmap.getWidth(); Bitmap b = Bitmap.createScaledBitmap(bitmap, prevW, prevH, false); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream); byte[] bytes = byteArrayOutputStream.toByteArray(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return Base64.getEncoder().encodeToString(bytes); } return ""; } private void postData(String room, String countPeoples, boolean check) { if(check){ status = "Занято"; } else{ status = "Свободно"; } // on below line we are creating a retrofit // builder and passing our base url Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://ngknn.ru:5001/NGKNN/ЛедровЕИ/api/") // as we are sending data in json format so // we have to add Gson converter factory .addConverterFactory(GsonConverterFactory.create()) // at last we are building our retrofit builder. .build(); // below line is to create an instance for our retrofit api class. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class); // passing data from our text fields to our modal class. DataStorage dataStorage = new DataStorage(Integer.parseInt(room), Integer.parseInt(countPeoples), status, encodedImage); // calling a method to create a post and passing our modal class. Call call = retrofitAPI.createPost(dataStorage); // on below line we are executing our method. call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { // this method is called when we get response from our api. Toast.makeText(CreatePage.this, "Запись добавлена", Toast.LENGTH_SHORT).show(); // on below line we are setting empty text // to our both edit text. inRoom.setText(""); inCountPeoples.setText(""); bStatus.setChecked(false); startActivity(new Intent(CreatePage.this, MainActivity.class)); finish(); } @Override public void onFailure(Call call, Throwable t) { // setting text to our text view when // we get error response from API. Toast.makeText(CreatePage.this, "Ошибка добавления", Toast.LENGTH_SHORT).show(); } }); } public void gotoMain(View v){startActivity(new Intent(this,MainActivity.class)); finish();} } ----------------------------------------------------------------------------------- !!!!!DATASTORAGE!!!!!! public class DataStorage { private Integer ID; private Integer Room; private Integer Count_Peoples; private String Status; private String Image; public DataStorage(Integer ID,Integer Room, Integer Count_Peoples, String Status, String Image){ this.ID = ID; this.Room = Room; this.Count_Peoples = Count_Peoples; this.Status = Status; this.Image = Image; } public DataStorage(Integer Room, Integer Count_Peoples, String Status, String Image){ this.Room = Room; this.Count_Peoples = Count_Peoples; this.Status = Status; this.Image = Image; } public Integer getID(){ return ID; } public void setID(Integer ID){ this.ID = ID; } public Integer getRoom(){ return Room; } public void setRoom(Integer Room){ this.Room = Room; } public Integer getCount_Peoples(){ return Count_Peoples; } public void setCount_Peoples(Integer Count_Peoples){ this.Count_Peoples = Count_Peoples; } public String getStatus(){ return Status; } public void setStatus(String Status){ this.Status = Status; } public String getImage(){ return Image; } public void setImage(String Image){ this.Image = Image; } }