Newer
Older
CosmosClient / app / src / main / java / com / example / cosmosclient / views / AddRequestActivity.java
k-morimoto on 17 Oct 2019 10 KB baseUrlをcosmos/rest/に変更
package com.example.cosmosclient.views;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.cosmosclient.R;
import com.example.cosmosclient.app.Cosmos;
import com.example.cosmosclient.entities.AddRequestsResponse;
import com.example.cosmosclient.resources.GroupsRest;
import com.example.cosmosclient.yolp.Yolp;

import java.io.IOException;
import java.util.Calendar;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;


public class AddRequestActivity extends AppCompatActivity {
    private InputMethodManager inputMethodManager;

    private ImageButton calenderButton;

    private Integer deadlineYear;
    private Integer deadlineMonth;
    private Integer deadlineDayOfMonth;

    private EditText editTextProduct;
    private EditText editTextDeadline;

    private Spinner category;
    private Spinner subCategory;

    private String selectedSubCategory;

    private Button addButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_request);

        //キーボード表示を制御するためのオブジェクト
        inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

        calenderButton = findViewById(R.id.calenderButton);

        editTextProduct = findViewById(R.id.editTextProduct);
        editTextDeadline = findViewById(R.id.editTextDeadline);

        category = findViewById(R.id.spinnerLocationCategory);
        subCategory = findViewById(R.id.spinnerLocationSubCategory);

        setSpinner(category, Yolp.getInstance().getCategoryNames());

        addButton = findViewById(R.id.buttonAdd);

        calenderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //キーボードを閉じる
                inputMethodManager.hideSoftInputFromWindow(editTextProduct.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);

                //Calendarインスタンスを取得
                final Calendar calender = Calendar.getInstance();

                //DatePickerDialogインスタンスを取得
                DatePickerDialog datePickerDialog = new DatePickerDialog(AddRequestActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        deadlineYear = year;
                        deadlineMonth = month;
                        deadlineDayOfMonth = dayOfMonth;

                        //setした日付を取得して表示
                        editTextDeadline.setText(String.format("%d / %02d / %02d", year, month+1, dayOfMonth));
                    }
                },
                        calender.get(Calendar.YEAR),
                        calender.get(Calendar.MONTH),
                        calender.get(Calendar.DATE)
                );

                //dialogを表示
                datePickerDialog.show();
            }
        });

        //editTextDeadlineにリスナーをセット
        editTextDeadline.setOnKeyListener(new View.OnKeyListener() {
            //コールバックとしてonKey()メソッドを定義
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //イベントを取得するタイミングには、ボタンが押されてなおかつエンターキーだったときを指定
                if((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)){
                    //キーボードを閉じる
                    inputMethodManager.hideSoftInputFromWindow(editTextProduct.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);

                    return true;
                }
                return false;
            }
        });

        // 追加ボタン
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //ボタン連打防止
                addButton.setEnabled(false);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        addButton.setEnabled(true);
                    }
                }, 3000L);

                // エディットテキストのテキストを取得
                String inputProduct = editTextProduct.getText().toString();

                //retrofitの処理
                final Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://nitta-lab-www.is.konan-u.ac.jp/cosmos/rest/")
//                        .baseUrl("http://10.0.2.2:8080/")
                        .addConverterFactory(JacksonConverterFactory.create())
                        .build();

                //interfaceから実装を取得
                final GroupsRest addRequestsService = retrofit.create(GroupsRest.class);

                //RequestList取得するための必要な情報
                Cosmos app = (Cosmos) getApplication();
                final String uId = app.getuId();
                final String gId = app.getCurentGroup().getgId();
                final String token = app.getToken();
                final boolean detail = true;
                String deadline = null;

                if(deadlineYear != null && deadlineMonth != null && deadlineDayOfMonth != null) {
                    deadline = String.format("%d-%02d-%02d %02d:%02d:%02d", deadlineYear, deadlineMonth +1, deadlineDayOfMonth, 23, 59, 59);
                }
                Call<AddRequestsResponse> call = addRequestsService.addRequests(gId, uId, inputProduct, deadline, Yolp.getInstance().getCodeBySubcategory(selectedSubCategory), token);
//                Call<AddRequestsResponse> call = addRequestsService.addRequests(gId, uId, inputProduct, new Date(deadlineYear, deadlineMonth, deadlineDayOfMonth), Yolp.getInstance().getCodeBySubcategory(selectedSubCategory), token);
//                Call<AddRequestsResponse> call = addRequestsService.addRequests(gId, uId, inputProduct, Yolp.getInstance().getCodeBySubcategory(selectedSubCategory), token);

                //サーバからのレスポンス
                call.enqueue(new Callback<AddRequestsResponse>() {
                    //成功時
                     @Override
                     public void onResponse(Call<AddRequestsResponse> call, Response<AddRequestsResponse> response) {
                         if (response.isSuccessful()) {
                             AddRequestsResponse result = response.body();
                             finish();

                             Toast.makeText(AddRequestActivity.this, "RequestListに追加しました", Toast.LENGTH_SHORT).show();
                         } else {
                             try {
                                 System.out.println(response.errorBody().string());
                             } catch (IOException e) {
                                 e.printStackTrace();
                             }

                             //onFailureでキャッチできないエラーの処理
                             Toast.makeText(AddRequestActivity.this, "通信エラー", Toast.LENGTH_SHORT).show();
                         }
                     }

                     //失敗時
                     @Override
                     public void onFailure(Call<AddRequestsResponse> call, Throwable t) {
                         t.printStackTrace();
                         Toast.makeText(AddRequestActivity.this, "RequestListの追加失敗しました", Toast.LENGTH_SHORT).show();
                     }
                });
            }
        });

        // リスナーを登録
        category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            // アイテムが選択された時
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Spinner spinner = (Spinner)parent;
                String selectedCategory = (String)spinner.getSelectedItem();
                SearchSubCategory(selectedCategory);
            }

            // アイテムが選択されなかった
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // リスナーを登録
        subCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            // アイテムが選択された時
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Spinner spinner = (Spinner)parent;
                selectedSubCategory = (String)spinner.getSelectedItem();
            }

            // アイテムが選択されなかった
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    private void SearchSubCategory(String selectedCategory) {
        switch(selectedCategory) {
            case "家電・携帯電話":
                setSpinner(subCategory, Yolp.getInstance().getCategoryByName("家電・携帯電話").getSubCategoryNames().toArray(new String[0]));
                break;
            case "コンビニ・スーパー":
                setSpinner(subCategory, Yolp.getInstance().getCategoryByName("コンビニ・スーパー").getSubCategoryNames().toArray(new String[0]));
                break;
        }
    }

    private void setSpinner(Spinner spinner, String[] arr){
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }


}