123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446 |
- !!!!!ПОДКЛЮЧЕНИЕ 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<DataStorage> createPost(@Body DataStorage dataStorage);
- @GET("Hotels/{id}")
- Call<DataStorage> getData(@Query("id") int id);
- @PUT("Hotels/{id}")
- Call<DataStorage> updateData(@Path("id") int id, @Body DataStorage dataModal);
- @DELETE("Hotels/{id}")
- Call<Void> 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<DataStorage> hotelList;
- public AdapterHotel(Context mContext, List<DataStorage> 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<DataStorage> 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<Void, Void, String> {
- @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<tempArray.length();i++)
- {
- JSONObject productJson = tempArray.getJSONObject(i);//Преобразование json объекта в нашу структуру
- DataStorage tempProduct = new DataStorage(
- productJson.getInt("ID"),
- productJson.getInt("Room"),
- productJson.getInt("Count_Peoples"),
- productJson.getString("Status"),
- productJson.getString("Image")
- );
- listProduct.add(tempProduct);
- pAdapter.notifyDataSetInvalidated();
- }
- } catch (Exception ignored) {
- }
- }
- }
- public void gotoaddRooms(View v){startActivity(new Intent(this,CreatePage.class)); finish();}
- }
- -----------------------------------------------------------------------------------
- !!!!!CREATEPAGE!!!!!
- import androidx.activity.result.ActivityResultLauncher;
- import androidx.activity.result.contract.ActivityResultContracts;
- import androidx.appcompat.app.AppCompatActivity;
- import retrofit2.Call;
- import retrofit2.Callback;
- import retrofit2.Response;
- import retrofit2.Retrofit;
- import retrofit2.converter.gson.GsonConverterFactory;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Bundle;
- import android.provider.MediaStore;
- import android.view.View;
- import android.widget.Button;
- import android.widget.CheckBox;
- import android.widget.EditText;
- import android.widget.ImageButton;
- import android.widget.ImageView;
- import android.widget.Toast;
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.util.Base64;
- public class CreatePage extends AppCompatActivity {
- private EditText inRoom;
- private EditText inCountPeoples;
- private CheckBox bStatus;
- private Button btnCreate;
- private String status;
- private ImageView image;
- private String encodedImage;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_create_page);
- inRoom = findViewById(R.id.RoomInput);
- inCountPeoples =findViewById(R.id.CountPeopleInput);
- bStatus = findViewById(R.id.BoxStatus);
- btnCreate = findViewById(R.id.btn_create);
- image = findViewById(R.id.img);
- image.setOnClickListener(v -> {
- 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<Intent> 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<DataStorage> call = retrofitAPI.createPost(dataStorage);
- // on below line we are executing our method.
- call.enqueue(new Callback<DataStorage>() {
- @Override
- public void onResponse(Call<DataStorage> call, Response<DataStorage> 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<DataStorage> 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;
- }
- }
|