2016年11月23日水曜日

Android Handler

Android Handler



public class MainActivity extends AppCompatActivity {

    private Handler handler;

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

        nThread n = new nThread();
        n.start();

        Button bt = (Button) findViewById(R.id.Bub);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = handler.obtainMessage();
                msg.obj = "SandMessage";
                handler.sendMessage(msg);
            }
        });
    }

    class nThread extends Thread {
        @Override
        public void run() {
            Looper.prepare();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    System.out.println(msg.obj);
                    System.out.println(Thread.currentThread().getName());
                }
            };
            Looper.loop();
        }
    }
}

Android Handler

Android Handler




public class MainActivity extends AppCompatActivity {

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

        HttpHandelar httpHandelar = new HttpHandelar();
        HttpThread h = new HttpThread(httpHandelar);
        h.start();
    }

    class HttpThread extends Thread {
        public Handler handler;

        public HttpThread(Handler handler) {
            this.handler = handler;
        }

        @Override
        public void run() {
            super.run();
            Message m = handler.obtainMessage();
            HashMap<String, String> h = new HashMap<String, String>();
            h.put("a", "aa");
            h.put("b", "bb");
            h.put("c", "cc");
            h.put("d", "dd");
            m.obj = h;
            handler.sendMessage(m);
        }
    }

    class HttpHandelar extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HashMap<String, String> mh = (HashMap) msg.obj;
            Set<String> key = mh.keySet();
            for (String gk : key) {
                System.out.println(mh.get(gk));
            }
        }
    }
}

2016年11月20日日曜日

Javascript Json

Json String



function getjson(){
var idolname = document.getElementsByClassName('idolname');
var idolnames ={};
var list = [];
for(var i = 0; i < idolname.length; i++){
var item = {};
item.name = idolname[i].innerText;
item.img = "https://farm4.staticflickr.com/3239/2897452239_d2cf730467_s.jpg";
item.count = "10";
item.active = "0";
list.push(item);
}
idolnames.total = idolname.length;
idolnames.idolnames = list;
console.log(JSON.stringify(idolnames));
}

java 字符串分割,得到文件名

java 字符串分割
得到URL的文件名

public class test {

public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg";
String[] sa = s.split("/");
System.out.println(sa[sa.length-1]);
}

}

2016年11月19日土曜日

Android Flickr API 显示缩略图



两个后台任务,一个负责得到列表,另一个下载每一个图片。
保存缩略图到getApplication().getCacheDir(),如果文件存在就读Cache,
不存在时从网络下载。



/**
 * Created by E560 on 2016/11/19.
 */

public class Mlistview extends AppCompatActivity {
    private GridView gridView;
    private final String imgsize = "s";
    private final String test_url = "http://cdefgab.web.fc2.com/song.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mlistview);
        new getlistmap().execute(test_url);
    }

    protected class getlistmap extends AsyncTask<String, Integer, List<String>> {
        /*
        * 返回所以縮圖,最長邊為 100的URL;
         */
        @Override
        protected List<String> doInBackground(String... params) {
            GetJson getJson = new GetJson(params[0]);
            List<String> listurl = new ArrayList<String>();
            try {
                HashMap<Integer, HashMap> items_map = getJson.jsonMap();
                for (int i = 0; i < items_map.size(); i++) {
                    listurl.add(GetJson.img_url(items_map.get(i), imgsize));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return listurl;
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            super.onPostExecute(strings);
            gridView = (GridView) findViewById(R.id.mlistview);
            myAdapter my = new myAdapter(strings);
            my.notifyDataSetChanged();
            gridView.setAdapter(my);
        }
    }

    protected class myAdapter extends BaseAdapter {
        private List<String> list;

        public myAdapter(List<String> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
            View v = new View(getApplication());
            if (convertView == null) {
                v = LayoutInflater.from(getApplication()).inflate(R.layout.ladapter, null);
            } else {
                v = convertView;
            }
            ImageView iv = (ImageView) v.findViewById(R.id.imageView2);
            iv.setImageBitmap(bitmap);
            GG gg = new GG(iv);
            gg.execute(list.get(position));
            return v;
        }

        public class GG extends AsyncTask<String, Integer, Bitmap> {
            private Bitmap bitmap;
            private ImageView iv;

            public GG(ImageView iv) {
                this.iv = iv;
            }

            @Override
            protected Bitmap doInBackground(String... params) {
                try {
//                     https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg
                    String[] sa = params[0].split("/");
                    File file = new File(getApplication().getCacheDir(), sa[sa.length - 1]);
                    if (file.isFile()) {
                        FileInputStream fin = new FileInputStream(file);
                        bitmap = BitmapFactory.decodeStream(fin);
                        fin.close();
                    } else {
                        bitmap = GetJson.getBitmap(params[0]);
                        FileOutputStream fon = new FileOutputStream(file);
                        ByteArrayOutputStream bas = GetJson.getBAOS(params[0]);
                        fon.write(bas.toByteArray());
                        fon.flush();
                        fon.close();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                iv.setImageBitmap(bitmap);
            }
        }
    }
}




2016年11月17日木曜日

Android BitmapFactory 文件下载前得到文件宽高

Android  BitmapFactory  文件下载前得到文件宽高



http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG
com.example.java.m1117a I/System.out: 4737
com.example.java.m1117a I/System.out: 3264
com.example.java.m1117a I/System.out: image/jpeg


https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg
com.example.java.m1117a I/System.out: 1024
com.example.java.m1117a I/System.out: 682
com.example.java.m1117a I/System.out: image/jpeg





public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        T1 t = new T1();
        t.execute("test");
    }

    class T1 extends AsyncTask<String, Integer, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {
//                InputStream is =  HttpTool.gis("https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg");
                InputStream is = HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG");
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, options);
                System.out.println(options.outHeight);
                System.out.println(options.outWidth);
                System.out.println(options.outMimeType);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
        }
    }
}

2016年11月16日水曜日

Android flickr 工具类

Android flickr 工具类

得到Json的 字节输入流,Byte数组输出流,JSON的字符串。
http://cdefgab.web.fc2.com/song.json  JSON文件样本。


package com.example.java.m1115a.Tools;

import android.content.Context;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by java on 2016/11/15.
 */

public class HttpTools {
    private String url_path;
    private Context context;

    public HttpTools(String url_path) {
        this.url_path = url_path;
    }

    public HttpTools(String url_path, Context context) {
        this.url_path = url_path;
        this.context = context;
    }

    public InputStream getnetInputStream() throws Exception {
        URL url = new URL(url_path);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(10000);
        httpURLConnection.setReadTimeout(10000);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("GET");

        InputStream inputStream = null;
        if (httpURLConnection.getResponseCode() == 200) {
            inputStream = httpURLConnection.getInputStream();
        }
        return inputStream;
    }

    public ByteArrayOutputStream getbyteArrayOutputStream() throws Exception {
        InputStream inputStream = getnetInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buff)) != -1) {
            byteArrayOutputStream.write(buff, 0, len);
        }
        inputStream.close();
        return byteArrayOutputStream;
    }

    public String getjsonString() throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = getbyteArrayOutputStream();
        return byteArrayOutputStream.toString();
    }
}


继承HttpTools类
得到JSON的数字HashMap,得到Item的图片URL,得到图片的Bitmap


package com.example.java.m1115a.Tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by java on 2016/11/15.
 */

public class GetJson extends HttpTools {
    public GetJson(String url_path) {
        super(url_path);
    }

    public HashMap<Integer, HashMap> jsonMap() throws Exception {
        String jsonString = getjsonString();
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject jsonObject1 = jsonObject.getJSONObject("photos");
        JSONArray jsonArray = jsonObject1.getJSONArray("photo");
        HashMap<Integer, HashMap> jMap = new HashMap<Integer, HashMap>();

        for (int i = 0; i < jsonArray.length(); i++) {
            HashMap<String, String> item = new HashMap<String, String>();
            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
            Iterator<String> iterator = jsonObject2.keys();
            while (iterator.hasNext()) {
                String temp = iterator.next();
                item.put(temp, jsonObject2.getString(temp));
            }
            jMap.put(i, item);
        }
        return jMap;
    }

    public static String img_url(HashMap<String, String> item_hashMap) throws Exception {
        /*
        *
        * https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
        * https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
        * https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
        *
        * String farmid = item_hashMap.get("farm");
        * String Serverid = item_hashMap.get("server");
        * String id = item_hashMap.get("id");
        * String secret = item_hashMap.get("secret");
        * String img_url = "https://farm" + farmid + ".staticflickr.com/" + Serverid + "/" + id + "_" + secret + ".jpg";
        * System.out.println(img_url);
        */

        HashMap<String, String> temp_map = item_hashMap;
        return "https://farm" + item_hashMap.get("farm") + ".staticflickr.com/" + item_hashMap.get("server") + "/" + item_hashMap.get("id") + "_" + item_hashMap.get("secret") + ".jpg";
    }

    public static Bitmap getBitmap(String img_url) throws Exception {
        URL url = new URL(img_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(10000);
        httpURLConnection.setReadTimeout(10000);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("GET");
        Bitmap bitmap = null;
        if (httpURLConnection.getResponseCode() == httpURLConnection.HTTP_OK) {
            InputStream inputStream = httpURLConnection.getInputStream();
            if (inputStream != null) {
                byte[] buf = new byte[1024];
                int len = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                while ((len = inputStream.read(buf)) != -1) {
                    byteArrayOutputStream.write(buf, 0, len);
                    byteArrayOutputStream.flush();
                }
                bitmap = BitmapFactory.decodeByteArray(byteArrayOutputStream.toByteArray(), 0, byteArrayOutputStream.size());
                inputStream.close();
                byteArrayOutputStream.close();
            }
        }
        return bitmap;
    }
}



完成的例子,测试
每按一次按键,更换下一张图片。
应该不需要每次后 New URL.







package com.example.java.m1115a;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.java.m1115a.Tools.GetJson;


public class MainActivity extends AppCompatActivity {

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

        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            private int cont;

            @Override
            public void onClick(View v) {
                new img().execute("http://cdefgab.web.fc2.com/song.json", String.valueOf(cont));
                cont++;
            }
        });
    }

    public class img extends AsyncTask<String, Integer, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {

            GetJson json = new GetJson(params[0]);
            int cont = Integer.parseInt(params[1]);
            Bitmap bitmap = null;
            try {
                bitmap = GetJson.getBitmap(GetJson.img_url(json.jsonMap().get(cont)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap == null) {
                Toast.makeText(MainActivity.this, "noImg", Toast.LENGTH_SHORT).show();
            }
            ImageView iv = (ImageView) findViewById(R.id.imageView);
            iv.setImageBitmap(bitmap);
        }
    }
}



2016/11/18
也可以直接加载InputStream的方式
bitmap = BitmapFactory.decodeStream(HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG"));