読者です 読者をやめる 読者になる 読者になる

【Android】ListView(独自Adapter)

Android

 

f:id:stanleyblenz:20161110001142j:plain

 

 

■登場人物

・activity_main.xml ※LisvView

・main_adapter.xml ※ListViewの中身

・MainParcel.java ※main_adapter.xmlにセットするクラス(独自Adapter)

・MainAdapter.java  ※アダプター

・MainModel.java ※(Observableを継承+AsyncTaskクラス) 

・MainFragment.java  ※Modelの呼び出し元

----------------------------------------------------------------------------------------------------------------

activity_main.xml ※LisvView

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">
  <ListView
    android:id="@+id/listview01"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:dividerHeight="1dp"/>
</LinearLayout>

 

main_adapter.xml ※ListViewの中身

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView
    android:id="@+id/title"
    android:textSize ="16dp"
    android:textStyle ="bold"
    android:textColor="#999999"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"/>
  <ImageView
    android:id="@+id/thumbnails"
    androidlayout_below="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"/>
</RelativeLayout>

 

MainParcel.java ※main_adapter.xmlにセットするクラス(独自Adapter)

(アプリがバックグランドにまわる場合など、Bundleに保持させるためParcelable化)★

public class MainParcel implements Parcelable {

  String title;
  Bitmap thumbnails;

  public MainParcel(String title, Bitmap thumbnails) {

    this.title = title;
    this.thumbnails = thumbnails;
  }
  protected MainParcel(Parcel in) {
    this.title = in.readString();
    this.thumbnails = in.readParcelable(Bitmap.class.getClassLoader());
  }
  @Override
  public int describeContents() {
    return 0;
  }
  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(title);
    dest.writeParcelable(thumbnails, flags);
  }
  public static final Parcelable.Creator CREATOR

      = new Parcelable.Creator() {
    public MainParcel createFromParcel(Parcel in) {
      return new MainParcel(in);
    }
    public MainParcel[] newArray(int size) {
      return new MainParcel[size];
    }
  };
}

----------------------------------------------------------------------------------------------------------------

MainAdapter.java  ※アダプター

public class MainAdapter extends ArrayAdapter<MainParcel> {

  LayoutInflater layoutInflater;
  Activity activity;

  public MainAdapter(Activity activity, int id, ArrayList<MainParcel> mainparcel){
    super(activity, id, mainMytube);
    this.layoutInflater = (LayoutInflater)activity.getSystemService(

              Context.LAYOUT_INFLATER_SERVICE);

    this.activity = activity;
  }
  @Override
  public View getView(int position, View view, ViewGroup parent) {
    view = layoutInflater.inflate(R.layout.main_adapter, parent, false);
    //getView内ではBitmap化できない為(imageUrl.openStream();でエラーになる)
    //Parcelableクラスの作成時(後述)のdoInBackground内で行う
    MainParcel item = getItem(position);
    TextView title = *1;
    ImageView thumbnails = *2;
    title.setText(item.title);
    thumbnails.setImageBitmap(item.thumbnails);
    return view;
  }
}

 

MainModel.java ※(Observableを継承+AsyncTaskクラス) 

データ取得はここで行う

public class MainModel extends Observable {

  ArrayList<MainParcel> list;
  public enum Event {
    START, FINISH,
  }
  public void asyncTask(String searchWord, String pagetoken) {
    //Observer通知
    setChanged();
    notifyObservers(Event.START);
    //AsyncTask実行
    MyTask mytask = new MyTask();
    mytask.execute(searchWord, pagetoken);
  }
  public ArrayList<MainParcel> getResutl() {//ゲッター
    return this.list;
  }
  public void setResult(ArrayList<MainMytube> list) {//セッター
    this.list = list;
    //Observer通知
    setChanged();
    notifyObservers(Event.FINISH);
  }
  //第1引数 パラメータ
  //第2引数 プログレ
  //第3引数 返却値
  class MyTask extends AsyncTask<String, Integer, ArrayList<MainParcel>> {

    @Override protected void onPreExecute() {
    }
    @Override
    protected ArrayList<MainParcel> doInBackground(String... value) {

      ArrayList<MainParcel> list = new ArrayList<MainParcel>();
      try {
        String searchWord = value[0];
        String pagetoken = value[1];

        Thread.sleep(1000); //1秒停止
        String apikey = "API_KEY";
        String API_1 = "https://www.googleapis.com/youtube/v3/search?key=";
        String API_2 = "&q=";
        String API_3 = "&part=id,snippet&maxResults=20&pageToken=";
        String url = API_1 + apikey + API_2 + searchWord + API_3

            + pagetoken;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
          .url(url)
          .build();
        try {
          Response response = client.newCall(request).execute();
          String result = response.body().string();
          try {
            JSONObject resJson = new JSONObject(result);

            JSONArray items = resJson.getJSONArray("items");

            int count = items.length();
            for (int i = 0; i < count; i++) {
            JSONObject item = items.getJSONObject(i);
            try {

              //snippet-title

              String snippet = item.getString("snippet");
              JSONObject snippetJson = new JSONObject(snippet);
              String title = snippetJson.getString("title");

              //snippet-thumbnails-medium-url

              String thumbnails = snippetJson.getString("thumbnails");
              JSONObject thumbnailsJson =

                 new JSONObject(thumbnails);
              String medium = thumbnailsJson.getString("medium");
              JSONObject mediumJson = new JSONObject(medium);
              String thumbnailsUrl = mediumJson.getString("url");

              URL imageUrl = new URL(thumbnailsUrl);
              InputStream imageIs = imageUrl.openStream();
              Bitmap image = BitmapFactory.decodeStream(imageIs);

              MainParcel mt = new MainParcel(title, image);
              list.add(mt);
            } catch (JSONException e) {
              continue;
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return list;
    }
    @Override
    protected void onPostExecute(ArrayList<MainParcel> list) {
      setResult(list);
    }
  }
}

MainFragment.java  ※Modelの呼び出し元

public MainFragment extends Fragment {

  MainModel model = new MainModel();

  private void getSearch(String pagetoken) {
    ~

    ~
    //ObserverパターンでAsyncTaskを実行
    model.addObserver(observer);
    model.asyncTask(searchWord, pagetoken);
  }
  private Observer observer = new Observer() {
    @Override
    public void update(Observable observable, Object data) {
      if (!(data instanceof MainModel.Event)) {
        return;
      }
      switch *3;
  }

}

 

------------------------------------------------------------------------------------------------------

progressDialogStart();//プログレスダイアログ開始
progressDialogEnd();//プログレスダイアログ終了 

プログレスダイアログは、過去記事をご参考にどうぞ。 

stanleyblenz.hatenablog.com

 

 

以上です。

 

 

*1:TextView)view.findViewById(R.id.title

*2:ImageView)view.findViewById(R.id.thumbnails

*3:MainModel.Event)data) {
        case START:
          progressDialogStart();//プログレスダイアログ開始
          break;
        case FINISH:
          progressDialogEnd();//プログレスダイアログ終了
          showList();//結果のリストをもとに表示
        break;
      }
    }
  };

  public void showList() {
    ArrayList<MainParcel> list = model.getResutl();★
    if (list == null || list.size() == 0) {
      Toast.makeText(getActivity(),

              "該当データがありません",

              Toast.LENGTH_SHORT).show();
      return;
    }
    //アダプターやクリックリスナーなど
    this.makeMainListView(list);
  }
  MainAdapter adapter;
  private void makeMainListView(ArrayList<MainParcel> list) {
    if (list != null) {
      adapter = new MainAdapter(getActivity(), 0, list);
      ListView lv = (ListView)getActivity().findViewById(R.id.mainlistview);
      lv.setAdapter(adapter);
      lv.setOnItemClickListener(this);//クリックリスナー
    }
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
      ArrayList<MainParcel> list =   

        savedInstanceState.getParcelableArrayList("MainParcel");

        this.makeMainListView(list);
    }
  }
  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList("MainParcel", model.getResutl(