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();
    }
}







2016年11月13日日曜日

Android PULL解析XML文件

PULL解析XML文件

https://developer.android.com/training/basics/network-ops/xml.html
http://cdefgab.web.fc2.com/test.xml



public class MainActivity extends AppCompatActivity {
    private File mainfile;

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

//得到XML文件并保存为文件
    public void getXML(View view) {
        chk c = new chk();
        c.execute("test");
    }

//PULL解析XML文件
    public void pullxml(View view) throws Exception {
        FileInputStream fileInputStream = this.openFileInput("xxxxx.xml");
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(fileInputStream, "utf-8");
        HashMap<Integer, HashMap> data = new HashMap<Integer, HashMap>();
        HashMap<String, String> data2 = null;
        Integer con = new Integer(0);
        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    if ("book".equals(parser.getName())) {
                        data2 = new HashMap<String, String>();
                        data2.put("id", parser.getAttributeValue(0));
                    }
                    if ("author".equals(parser.getName())) {
                        data2.put("author", parser.nextText());
                    }
                    if ("genre".equals(parser.getName())) {
                        data2.put("genre", parser.nextText());
                    }
                    if ("price".equals(parser.getName())) {
                        data2.put("price", parser.nextText());
                    }
                    if ("publish_date".equals(parser.getName())) {
                        data2.put("publish_date", parser.nextText());
                    }
                    if ("description".equals(parser.getName())) {
                        data2.put("description", parser.nextText());
                    }
                    break;
                case XmlPullParser.END_TAG:
                    data.put(con, data2);
                    con++;
                    break;
                case XmlPullParser.END_DOCUMENT:
                    break;
            }
            type = parser.next();
        }
        System.out.println(data.get(0).toString());
    }

    public class chk extends AsyncTask<String, Integer, File> {
        @Override
        protected File doInBackground(String... params) {
            File file_path = null;
            String url_path = "http://cdefgab.web.fc2.com/test.xml";
            String f_name = "xxxxx.xml";
            GetXML getXML = new GetXML(MainActivity.this, url_path, f_name);
            try {
                file_path = getXML.tofile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file_path;
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            mainfile = file;
        }
    }
}



//得到XML文件并保存为文件
public class GetXML {
    private Context context;
    private String url_path;
    private String f_name;
    private InputStream inputStream;
    private FileOutputStream fileOutputStream;

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

    public File tofile() throws IOException {
        URL url = new URL(url_path);
        fileOutputStream = context.openFileOutput(f_name, Context.MODE_PRIVATE);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpURLConnection.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, len);
                fileOutputStream.flush();
            }
        }
        fileOutputStream.close();
        inputStream.close();
        return context.getFileStreamPath(f_name);
    }

}

2016年11月12日土曜日

Android SharedPreferences

Android SharedPreferences

Develop > API Guides >数据存储
https://developer.android.com/guide/topics/data/data-storage.html#pref
https://www.youtube.com/watch?v=HWKcVeNcs20&index=11&list=PLHOqLxXumAI-ASmOAbuV9oD-gxHvjsjUU

文件的写入位置
System.out: /data/data/com.example.e560.m1110a/shared_prefs/xml.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <boolean name="chk" value="true" />
    <string name="key">new value</string>
    <set name="StringSet">
        <string>String1</string>
        <string>String2</string>
    </set>
    <int name="int" value="123" />
</map>




public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setinfo();
        addinfo();
        getinfo();
        File f = new File("/data/data/com.example.e560.m1110a/shared_prefs");
        System.out.println("----------");
        File[] fs = f.listFiles();
        System.out.println(fs.length);
        for (int i = 0; i < fs.length; i++) {
            File temp = fs[i];
            System.out.println(temp.getPath());
        }
    }

    protected void getinfo() {
        SharedPreferences sp = this.getSharedPreferences("xml", MODE_PRIVATE);
        LinearLayout lv = new LinearLayout(this);
        EditText et = new EditText(this);
        et.setText(sp.getAll().toString());
        lv.addView(et);
        setContentView(lv);
    }

    protected void setinfo() {
        SharedPreferences sp = this.getSharedPreferences("xml", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("key", "value");
        edit.putInt("int", 123);
        edit.putBoolean("chk", true);
        edit.commit();
    }

    protected void addinfo() {
        SharedPreferences sp = this.getSharedPreferences("xml", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("key", "new value");
        Set<String> list = new HashSet<String>();
        list.add("String1");
        list.add("String2");
        edit.putStringSet("StringSet", list);
        edit.commit();
    }
}

2016年11月9日水曜日

Thread 練習

Thread 練習

https://paiza.io/projects/xrf-cg825CeFPxNDEjnKlg


import java.io.*;
import java.net.*;

public class Main {
public static void main(String[] args) throws Exception {
int i = 0;
for (i = 0; i < 90; i++) {
new Thread(new Runnable() {
public void run() {
long x = Thread.currentThread().getId();
new D().Down(x);
}
} ).start();
}
}
}

class D {
public D() {
}
public void Down(Long x) {
try {
URL u = new URL("http://www.yahoo.co.jp");
HttpURLConnection c = (HttpURLConnection)u.openConnection();
c.setConnectTimeout(3000);
c.setReadTimeout(3000);
c.setDoInput(true);
InputStream is = null;
c.setRequestMethod("GET");
if (c.getResponseCode() == 200) {
is = c.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
System.out.println(Thread.currentThread().getName() + "  :  " + br.readLine());
// byte[] buf = new byte[1024];
// int len = 0;
// while((len = is.read(buf)) != -1 ){
//     System.out.println("Thread:"+ x +"->"+ new String(buf,0,len));
//     System.out.println(x);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
}
}