2016年11月20日日曜日

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"));



2016年11月14日月曜日

Java HashMap 遍历 练习

Java HashMap 遍历 练习



    protected void HSM() {
        Map<String, String> x = new HashMap<String, String>();
        x.put("a", "aa");
        x.put("b", "bb");
        x.put("c", "cc");
        x.put("d", "dd");
        System.out.println(x);

        System.out.println("1111111111111111");
        Set<String> setk = x.keySet();
        Iterator ite = setk.iterator();
        while (ite.hasNext()) {
            String temp = (String) ite.next();
            System.out.println(temp);
            System.out.println(x.get(temp));
        }


        System.out.println("22222222222222");
        for (String String : setk) {
            System.out.println(String);
            System.out.println(x.get(String));
        }
    }

Android SharedPreferences HashSet练习

Android SharedPreferences  HashSet练习

SharedPreferences sp = this.getSharedPreferences("xxx.xml", MODE_PRIVATE);
不需要文件扩展名

public class MainActivity extends AppCompatActivity {

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

    protected void t1() {
        SharedPreferences sp = this.getSharedPreferences("xxx.xml", MODE_PRIVATE);
        SharedPreferences.Editor spe = sp.edit();
        spe.putBoolean("a", true);
        spe.putFloat("f", 2222.999f);
        spe.putInt("int", new Integer(22));
        spe.putString("String", "testXML");
        Set<String> xx = new HashSet<String>();
        xx.add("a");
        xx.add("b");
        xx.add("c");
        xx.add("d");
        spe.putStringSet("set", xx);
        spe.commit();
    }






    protected void t2() {
        SharedPreferences sp = getSharedPreferences("xxx.xml", MODE_PRIVATE);
        TextView tv = (TextView) findViewById(R.id.t1);
        HashSet<String> sset = (HashSet<String>) sp.getStringSet("set", null);
        Iterator<String> index = sset.iterator();
        while (index.hasNext()) {
            String temp = index.next();
            if (temp.equals("a")) {
                System.out.println(temp);
            }
        }
        System.out.println(sp.getBoolean("a",true));
        System.out.println(sp.getFloat("f",0));
        System.out.println(sp.getInt("int",0));
        System.out.println(sp.getInt("int",0));
    }
}

Android xml文件的序列化

Android  xml文件的序列化

https://youtu.be/2IatWH5EQQA?t=23m13s
android視頻教程 29 xml文件的序列化



public class XmlnewSerializer {

    private Context context;

    public XmlnewSerializer(Context context) {
        this.context = context;
    }

    public void create() throws Exception {
        XmlSerializer xmlSerializer = Xml.newSerializer();
        CharArrayWriter temp = new CharArrayWriter();
        ByteArrayOutputStream temp2 = new ByteArrayOutputStream();
        xmlSerializer.setOutput(temp2, "utf-8");

        xmlSerializer.startDocument("utf-8", true);
        xmlSerializer.startTag(null, "test");
        for (int i = 0; i < 5; i++) {
            xmlSerializer.startTag(null, "book");
            xmlSerializer.attribute(null, "id", i + "");
            xmlSerializer.startTag(null, "author");
            xmlSerializer.text("Gambardella, Matthew");
            xmlSerializer.endTag(null, "author");
            xmlSerializer.endTag(null, "book");
        }
        xmlSerializer.endTag(null, "test");
        xmlSerializer.endDocument();

        System.out.println(temp);

        FileOutputStream fs = context.openFileOutput("newxml.xml", Context.MODE_PRIVATE);
        fs.write(temp2.toByteArray());
        fs.close();
    }
}