Jsonファイルから画像ファイルと外部ブラウザリンク先を取得し表示する

<font color="DeepPink">
Jsonファイルから画像ファイルと外部ブラウザリンク先を取得し表示する
Android Studio 2.3.2
</font>

```Json:Jsonファイル
{
"nonPictureURL":"http://mimiphp.is.land.to/noncoin.png",
"nonLinkURL":"http://book.geocities.jp/nonpipo/index.html"
}
```

![00001.png](https://qiita-image-store.s3.amazonaws.com/0/93155/2daa7241-a466-5eb3-a136-ceb3ae01767a.png)

![001.png](https://qiita-image-store.s3.amazonaws.com/0/93155/2b7bdfd9-de54-143a-b1a9-64d2159e2ff5.png)


![002.png](https://qiita-image-store.s3.amazonaws.com/0/93155/09029e95-70c0-72ac-6607-8b356532bfe0.png)

![003.png](https://qiita-image-store.s3.amazonaws.com/0/93155/46f2996d-5403-a3b1-93f5-95e0a9110ef6.png)

```Java:MainActivity
package com.example.non.nonsample;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.non.nonsample.NonImageAsync.NonImageCallBackTask;
import com.example.non.nonsample.NonJsonAsync.NonJsonCallBackTask;

import java.util.ArrayList;
import java.util.List;

/**
 * MainActivity
 */
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    //コンテンツ内容
    private List<ContentsData> contentsDataList;
    //メインのリストビュー
    private ListView mainListView;

    NonLogic nonLogic = new NonLogic();

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

        //メインのリストビュー
        mainListView = (ListView)findViewById(R.id.main_listView);

        //リスト内のコンテンツ
        contentsDataList= new ArrayList<>();
        for(int i =0; i < 20; i++) {
            ContentsData contentsData = new ContentsData();
            contentsData.setName("test:" + i);
            contentsDataList.add(contentsData);
        }
        setNonJson();
    }

    /**
     * setNonJson
     * テキストファイルを取得する
     */
    private void setNonJson(){
        NonJsonAsync nonJsonAsync = new NonJsonAsync();
        nonJsonAsync.setNonJsonOnCallBack(new NonJsonCallBackTask(){

            @Override
            public void NonJsonCallBack(String result) {
                super.NonJsonCallBack(result);
                Log.i("MainActivity", "MainActivity NonJsonAsync end");

                nonLogic.setHeaderJson(result);
                setNonImage();

            }
        });
        nonJsonAsync.execute();
    }

    /**
     * SetNonImage
     * 画像URLからBitMapImageにセットする
     */
    private void setNonImage(){
        NonImageAsync nonImageAsync = new NonImageAsync(nonLogic);
        nonImageAsync.setNonImageOnCallBack(new NonImageCallBackTask(){
            @Override
            public void NonImageCallBack(String result,NonLogic para_nonLogic) {
                super.NonImageCallBack(result,nonLogic);
                nonLogic.setHeader_data(para_nonLogic.getHeader_data());
                Log.i("MainActivity", "MainActivity NonImageAsync end");
                setNonAdapter();
            }
        });
        nonImageAsync.execute();
    }

    /**
     * setNonAdapter
     * Viewセルにセットする
     */
    private void setNonAdapter(){
        //Adapter
        NonAdapter nonadapter = new NonAdapter(this.getApplicationContext(),contentsDataList,nonLogic);
        mainListView.setAdapter(nonadapter);
        //ClickListener
        mainListView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        if(position == 0){
            //先頭行セルClickのみ外部ブラウザで起動する
            startExternalBrowser();
        }
    }

    /**
     * startExternalBrowser 外部ブラウザで起動する
     */
    public void startExternalBrowser(){
        Log.d("MainActivity","startExternalBrowser start");
        try{
            //Link Set
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(nonLogic.getHeader_data().getTargetLinkUrl()));
            intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
            startActivity(intent);
        }catch(Exception e){
            Log.e("startExternalBrowser","Exception:" + e);
        }
    }

}
```

```Java:NonAdapter
package com.example.non.nonsample;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;

/**
 * NonAdapter
 */
public class NonAdapter extends BaseAdapter{
    private Context context;
    private List<ContentsData> contentsDataList;
    private ImageData imageData;
    //viewの数（ヘッダーとコンテンツの２種類）
    private int viewCount = 0;
    //ヘッダー行の数（1行）
    private int headerCount = 0;
    //コンテンツ行の数
    private int contentsCount = 0;
    //全ての行数(ヘッダー行とコンテンツ行の合計行数)
    private int all_dataCount = 0;
    private LayoutInflater inflater;
    private enum ViewTypeMode {
        HEADER, //
        CONTENTS //
        ;
    }

    /**
     * NonAdapter
     * @param context
     * @param para_contentsData
     * @param nonLogic
     */
    public NonAdapter(Context context, List<ContentsData> para_contentsData,NonLogic nonLogic) {
        super();
        this.context = context;
        //引数 コンテンツデータ
        contentsDataList = para_contentsData;
        //引数 ヘッダーデータ
        imageData = nonLogic.getHeader_data();
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if(imageData != null){
            headerCount = 1;
            viewCount = 1;
        }

        if(contentsDataList.size() > 0){
            contentsCount = contentsDataList.size();
            viewCount ++;
        }
        all_dataCount = headerCount + contentsCount;
    }

    /**
     * @return viewの種類数（ヘッダーとコンテンツの２つ）
     */
    @Override
    public int getViewTypeCount(){
        return viewCount;
    }

    /**
     *
     * @return 全ての行数
     */
    @Override
    public int getCount() {
        return all_dataCount;
    }

    /**
     * itemのタイプ
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        return position == 0 ? ViewTypeMode.HEADER.ordinal() : ViewTypeMode.CONTENTS.ordinal();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    /**
     * @param position
     * @param view
     * @param viewGroup
     * @return
     */
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {

        //viewのType
        int viewType = getItemViewType(position);


        if(viewType == ViewTypeMode.HEADER.ordinal()) {
            //Header
            if(view == null || (Integer)view.getTag() == ViewTypeMode.CONTENTS.ordinal()) {
                //viewが変わったら再設定する
                view = setHeaderView(view, viewType);
            }
            //ヘッダー行を設定する
            ImageView imageView =(ImageView) view.findViewById(R.id.lead_imageView);
            //TODO:
            //imageView.setImageBitmap((Bitmap) imageData.getImage());
            imageView.setImageBitmap((Bitmap) imageData.getBitmap_image());
            Log.i("NonAdapter", "NonAdapter getView imageData.getBitmap_image():" +imageData.getBitmap_image());

        }else{
            //ヘッダーを引いた位置
            int index = position - headerCount;
            //Contents
            if(view == null || (Integer)view.getTag() == ViewTypeMode.HEADER.ordinal()) {
                //viewが変わったら再設定する
                view = setContentsView(view, viewType);
            }
            //コンテンツ行を設定する
            TextView contentsView =(TextView) view.findViewById(R.id.contents_cell_text_view);
            ContentsData contentsData = contentsDataList.get(index);
            contentsView.setText(contentsData.getName());
            contentsView.setTextColor(Color.BLACK);
        }

        return view;
    }

    /**
     * setHeaderView ヘッダーview設定
     * @param view
     * @param viewType
     * @return
     */
    private View setHeaderView(View view,int viewType){
        view = inflater.inflate(R.layout.lead_cell, null);
        view.setTag(ViewTypeMode.HEADER.ordinal());
        return view;
    }

    /**
     * setContentsView コンテンツview設定
     * @param view
     * @param viewType
     * @return
     */
    private View setContentsView(View view,int viewType){
        view = inflater.inflate(R.layout.contents_cell, null);
        view.setTag(ViewTypeMode.CONTENTS.ordinal());
        return view;
    }

}
```

```Java:NonImageAsync
package com.example.non.nonsample;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * NonImageAsync
 * 画像URLからBitMapImageにセットする
 */
public class NonImageAsync extends AsyncTask<Void, Void, String> {

    private NonImageCallBackTask nonImageCallBackTask;
    private NonLogic nonLogic;

    public NonImageAsync(NonLogic para_nonLogic){
        super();
        nonLogic = para_nonLogic;
    }

    /**
     * doInBackground
     * @param voids
     * @return
     */
    @Override
    protected String doInBackground(Void... voids) {
        HttpURLConnection con = null;

        try {
            URL url = new URL(nonLogic.getHeader_data().getImageUrl());
            con = (HttpURLConnection) url.openConnection();
            con.connect();
            final int status = con.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = new BufferedInputStream(con.getInputStream());
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                nonLogic.getHeader_data().setBitmap_image(bitmap);
                inputStream.close();
            }
            con.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * onPostExecute
     * @param result
     */
    @Override
    protected void onPostExecute(String result){
        super.onPostExecute(result);
        nonImageCallBackTask.NonImageCallBack(result,nonLogic);
    }

    /**
     * setNonImageOnCallBack
     * @param task
     */
    public void setNonImageOnCallBack(NonImageAsync.NonImageCallBackTask task){
        nonImageCallBackTask = task;
    }

    /**
     * NonImageCallBackTask
     */
    public static class NonImageCallBackTask{
        public void NonImageCallBack(String result,NonLogic nonLogic){}
    }

}

```

```Java:NonJsonAsync
package com.example.non.nonsample;

import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * NonJsonAsync
 * テキストファイルを取得する
 */
public class NonJsonAsync extends AsyncTask<Void, Void, String> {
    private  NonJsonCallBackTask nonJsonCallBackTask;

    @Override
    protected String doInBackground(Void... voids) {
        String result = "";
        StringBuilder stringBuilder = new StringBuilder();
        HttpURLConnection con = null;

        try {
            URL url = new URL("http://mimiphp.is.land.to/nonfile.txt");
            con = (HttpURLConnection) url.openConnection();
            con.connect();

            final int status = con.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                InputStream in = new BufferedInputStream(con.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                reader.close();
                result = stringBuilder.toString();
            }
            con.disconnect();

        } catch (IOException e) {
            Log.d("NonJsonAsync", "Error IOException:" + e);
        }
        return result;
    }

    /**
     * onPostExecute
     * @param result
     */
    @Override
    protected void onPostExecute(String result){
        super.onPostExecute(result);
        nonJsonCallBackTask.NonJsonCallBack(result);
    }

    /**
     * setNonJsonOnCallBack
     * @param task
     */
    public void setNonJsonOnCallBack(NonJsonAsync.NonJsonCallBackTask task){
        nonJsonCallBackTask = task;
    }

    /**
     * NonJsonCallBackTask
     */
    public static class NonJsonCallBackTask{
        public void NonJsonCallBack(String result){}
    }
}

```

```Java:NonLogic
package com.example.non.nonsample;

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * NonLogic
 */
public class NonLogic {

    //先頭行セルimage
    public ImageData header_data;

    public ImageData getHeader_data() {
        return header_data;
    }

    public void setHeader_data(ImageData header_data) {
        this.header_data = header_data;
    }

    protected boolean setHeaderJson(String response){
        Log.d("NonLogic","NonLogic setHeaderJson start");
        Log.d("NonLogic","NonLogic setHeaderJson response:" + response);
        boolean resultFlag = false;
        String nonLinkUrl ="";
        String nonPictureUrl ="";
        header_data = new ImageData();

        if(!response.isEmpty() || !response.equals("")){
            try {
                JSONObject json = new JSONObject(response);
                nonLinkUrl = json.getString("nonLinkURL");
                nonPictureUrl = json.getString("nonPictureURL");

                if(!nonLinkUrl.equals("") && !nonPictureUrl.equals("")){
                    header_data.setImageUrl(nonPictureUrl);
                    //TODO:
                    //imageData.setTargetUrl(nonLinkUrl);
                    header_data.setTargetLinkUrl(nonLinkUrl);
                    resultFlag = true;
                    Log.d("NonLogic","nonPictureUrl:" + nonPictureUrl);
                    Log.d("NonLogic","nonLinkUrl:" + nonLinkUrl);
                }

            } catch (JSONException e) {
                Log.d("NonLogic","setHeaderJson JSONException:" + e);
            }
        }

        return  resultFlag;
    }


}

```

```Java:ContentsData
package com.example.non.nonsample;

/**
 * ContentsData
 */
public class ContentsData {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

```

```Java:ImageData
package com.example.non.nonsample;

import android.graphics.Bitmap;

/**
 * ImageData
 */
public class ImageData {
    // image Url
    private String imageUrl;
    //image BitMap
    private Bitmap bitmap_image;
    // 外部ブラウザ起動先URL
    private String targetLinkUrl;

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getTargetLinkUrl() {
        return targetLinkUrl;
    }

    public void setTargetLinkUrl(String targetLinkUrl) {
        this.targetLinkUrl = targetLinkUrl;
    }

    public Bitmap getBitmap_image() {
        return bitmap_image;
    }

    public void setBitmap_image(Bitmap bitmap_image) {
        this.bitmap_image = bitmap_image;
    }
}

```

```XML:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.non.nonsample.MainActivity">

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent">

      <ListView
          android:id="@+id/main_listView"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
      </ListView>
  </LinearLayout>

</android.support.constraint.ConstraintLayout>

```

```XML:contents_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id ="@+id/contents_cell_layout"
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView
            android:id="@+id/contents_cell_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="30dp"
            android:textStyle="bold" />
    </RelativeLayout>
</LinearLayout>
```

```XML:lead_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id ="@+id/lead_cell_layout"
        android:layout_width="fill_parent"
        android:layout_height="50dp">
       <ImageView
           android:id="@+id/lead_imageView"
           android:scaleType="fitXY"
           android:layout_width="match_parent"
           android:layout_height="match_parent"/>
    </RelativeLayout>
</LinearLayout>
```