ラベル Android の投稿を表示しています。 すべての投稿を表示
ラベル Android の投稿を表示しています。 すべての投稿を表示

2016年11月23日水曜日

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月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日月曜日

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日水曜日

Android 文件保存,文件读取

Android 文件保存,文件读取
使用内部存储
https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

使用文件名称和操作模式调用 openFileOutput()。 这将返回一个 FileOutputStream。
使用 write() 写入到文件。
使用 close() 关闭流式传输。


public class MainActivity extends AppCompatActivity {

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

    protected void GetUser() {
        try {
            FileInputStream fis = new FileInputStream(new File(this.getFilesDir(), "user.csv"));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = fis.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }
            System.out.println(baos.toString());
            JSONObject jde = new JSONObject(baos.toString());
            TextView tv1 = (TextView) findViewById(R.id.textView2);
            tv1.setText(jde.getString("userName"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void Userinfo() {
        JSONObject j = new JSONObject();
        JSONObject j2 = new JSONObject();
        try {
            j.put("userName", "sun");
            j.put("password", "12345");
            j2.put("phone1", "99999");
            j2.put("Phone2", "88808880");
            j.put("Phones", j2);
            File f = new File(this.getFilesDir(), "user.csv");
            FileOutputStream fos = new FileOutputStream(f);
            fos.write((j.toString()).getBytes());
            fos.close();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2016年11月8日火曜日

Android 下载JSON文体,解析为数组,自定义Adapter显示

Android 下载JSON文体,解析为数组,自定义Adapter显示



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.button2);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyasyncTask().execute("http://cdefgab.web.fc2.com/song.json");
            }
        });
    }

//   下载JSON文体,解析为数组,自定义Adapter显示。
    public class MyasyncTask extends AsyncTask<String, Integer, List<String>> {
        @Override
        protected List<String> doInBackground(String... params) {
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            List<String> data = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");
                baos = new ByteArrayOutputStream();
                if (huc.getResponseCode() == 200) {
                    is = huc.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                    JSONObject js = new JSONObject(baos.toString());
                    JSONObject js2 = js.getJSONObject("photos");
                    JSONArray ja1 = js2.getJSONArray("photo");
                    data = new ArrayList<String>();
                    for (int i = 0; i < ja1.length(); i++) {
                        JSONObject js3 = ja1.getJSONObject(i);
                        data.add(js3.getString("title"));
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return data;
        }

        @Override
        protected void onPostExecute(final List<String> strings) {
            super.onPostExecute(strings);
            ListView lv = (ListView) findViewById(R.id.listview);
//            lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,strings));
            mya m = new mya(strings);
            m.notifyDataSetChanged();
            lv.setAdapter(m);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(MainActivity.this, strings.get(position), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public class mya extends BaseAdapter {
        private List<String> temp;

        public mya(List<String> temp) {
            this.temp = temp;
        }

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

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;
            if (convertView == null) {
                view = LayoutInflater.from(MainActivity.this).inflate(R.layout.myadapter1, null);
            } else {
                view = convertView;
            }
            TextView tv = (TextView) view.findViewById(R.id.textView5);
            tv.setText(temp.get(position));
            return view;
        }
    }
}

2016年11月7日月曜日

字节流转换字符流

字节流转换字符流




public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new XML().execute("null");
    }

    public class XML extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            try {
//                URL u = new URL("http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip");
                URL u = new URL("http://cdefgab.web.fc2.com/song.json");
                HttpURLConnection huc = (HttpURLConnection) u.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");
//                字节流转换字符流方法
//                if(huc.getResponseCode() == 200) {
//                    BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream(),"utf-8"));
//                    InputStream is = huc.getInputStream();
//                    InputStreamReader isr = new InputStreamReader(is,"utf-8");
//                    BufferedReader br = new BufferedReader(isr);
//                    String temp = null;
//                    while((temp = br.readLine()) != null){
//                        System.out.println("--------------");
//                        System.out.println(temp);
//                    }
//                }

//                字节流缓冲方法
                if (huc.getResponseCode() == 200) {
                    System.out.println("-----Astart");
                    BufferedInputStream bis = new BufferedInputStream(huc.getInputStream());
                    int i = 0;
                    byte[] buff = new byte[1024];
                    while ((i = bis.read(buff)) != -1) {
                        System.out.println("deta.length--" + i);
                        System.out.println(new String(buff, 0, i));
                    }
                    System.out.println("-----Aend");
                }

                if (huc.getResponseCode() == 200) {
                    System.out.println("-----Bstart");
                    InputStream is = huc.getInputStream();
                    byte[] buff = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buff)) != -1) {
                        System.out.println("data.lenght" + len);
                        System.out.println(new String(buff, 0, len));
                    }
                    System.out.println("-----Bend");
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

2016年11月6日日曜日

AscnyTask 练习

AscnyTask 练习



public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ProgressDialog pd;

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

        //设置一个下载进度条
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(0);
        pd.setTitle("Downloadnow");

        //设置响应事件
        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(this);
        Button bt2 = (Button) findViewById(R.id.button2);
        bt2.setOnClickListener(this);
        Button bt3 = (Button) findViewById(R.id.button3);
        bt3.setOnClickListener(this);
        Button bt4 = (Button) findViewById(R.id.button4);
        bt4.setOnClickListener(this);
        Button bt5 = (Button) findViewById(R.id.button5);
        bt5.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Img i = new Img();
        System.out.println(v.getId());
        switch (v.getId()) {
            case R.id.button:
                i.execute("http://image.i-voce.jp/files/article/main/s8AO3sFN_1438142266.jpg");
                break;
            case R.id.button2:
                i.execute("http://pic.prepics-cdn.com/d75526b7cc13/41938040.jpeg");
                break;
            case R.id.button3:
                i.execute("http://entertainment.rakuten.co.jp/movie/interview/kiritanimirei/img/interviewimg001.jpg");
                break;
            case R.id.button4:
                i.execute("http://up.gc-img.net/post_img_web/2015/09/32f61210611d358bddc2784d875cf65e_4238.jpeg");
                break;
            case R.id.button5:
                i.execute("http://lwoyr.com/wp-content/uploads/2015/06/20150618_5.jpg");
                break;
        }
    }

    public class Img extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            byte[] reBate = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");

                //用文件长度设置进度条的最大值
                pd.setMax(huc.getContentLength());
                if (huc.getResponseCode() == 200) {
                    InputStream is = huc.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        baos.write(buf, 0, len);
                        publishProgress(baos.size());
                    }
                    reBate = baos.toByteArray();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return reBate;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            ImageView iv = (ImageView) findViewById(R.id.imageView2);
            iv.setImageBitmap(bitmap);
            pd.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pd.setProgress(values[0]);
        }
    }
}

Android AsyncTask 异步任务下载图片并显示咋UI线程

Android AsyncTask 异步任务下载图片并显示咋UI线程



public class MainActivity extends AppCompatActivity {
    private ImageView iv;

    @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() {
            @Override
            public void onClick(View v) {
                iv = (ImageView) findViewById(R.id.imageView);
                DownImg di = new DownImg(MainActivity.this, iv);
                di.execute("url");
            }
        });
    }
}



public class DownImg extends AsyncTask<String, Integer, byte[]> {
    private ImageView iv;
    private int file_length;
    private Context context;
    protected ProgressDialog pd;

    public DownImg(Context context, ImageView iv) {
        this.iv = iv;
        this.context = context;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        ByteArrayOutputStream bos = null;
        try {
            URL url = new URL("http://prw.kyodonews.jp/prwfile/release/M102245/201403149047/_prw_PI1fl_2o2KuN2D.jpg");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            file_length = httpURLConnection.getContentLength();
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = httpURLConnection.getInputStream();
                bos = new ByteArrayOutputStream();
                byte[] buff =  new byte[1024];
                int len = 0;
                while ((len = is.read(buff)) != -1) {
                    bos.write(buff, 0, len);
                    publishProgress(file_length,bos.size());
                }
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos.toByteArray();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setTitle("test");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);
        pd.setMax(100);
        pd.setProgress(0);
        pd.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        pd.setMax(values[0]);
        pd.setProgress(values[1]);
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        Bitmap bt = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        iv.setImageBitmap(bt);
        pd.dismiss();
    }
}



2016年11月4日金曜日

Android JSONObject 练习

Android JSONObject 练习

1.  JSON链接
     http://cdefgab.web.fc2.com/song.json


public class DownJson {

    public void ejson() {
        String data = jsonString();
        HashMap<String, String> hh = new HashMap<String, String>();
        HashMap<Integer, HashMap<String, String>> hl = new HashMap<Integer, HashMap<String, String>>();

        try {
            JSONObject js = new JSONObject(data);
            JSONObject js2 = js.getJSONObject("photos");
            hh.put("stat", js.getString("stat"));
            hh.put("page", js2.getString("page"));
            hh.put("pages", js2.getString("pages"));
            hh.put("perpage", js2.getString("perpage"));
            hh.put("total", js2.getString("total"));

            String ja = js2.getString("photo");
            JSONArray jaa = new JSONArray(ja);

            for (int i = 0; i < jaa.length(); i++) {
                JSONObject t1 = jaa.getJSONObject(i);
                HashMap<String, String> hmt = new HashMap<String, String>();
                hmt.put("id", t1.getString("id"));
                hmt.put("owner", t1.getString("owner"));
                hmt.put("secret", t1.getString("secret"));
                hmt.put("server", t1.getString("server"));
                hmt.put("farm", t1.getString("farm"));
                hmt.put("title", t1.getString("title"));
                hmt.put("ispublic", t1.getString("ispublic"));
                hmt.put("isfriend", t1.getString("isfriend"));
                hmt.put("isfamily", t1.getString("isfamily"));
                hl.put(i, hmt);
            }

            System.out.println("-----------------------");
            System.out.println(hl.get(0).get("title"));
            System.out.println("-----------------------");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public static String jsonString() {
        String jstring = null;
        InputStream is = null;
        try {
            URL u = new URL("http://cdefgab.web.fc2.com/song.json");
            HttpURLConnection h = (HttpURLConnection) u.openConnection();
            h.setRequestMethod("GET");
            h.setDoInput(true);
            h.setConnectTimeout(3000);
            h.setReadTimeout(3000);
            if (h.getResponseCode() == 200) {
                byte[] buff = new byte[1024];
                int len = 0;
                is = h.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((len = is.read(buff)) != -1) {
                    baos.write(buff, 0, len);
                }
                jstring = baos.toString("utf-8");
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jstring;
    }
}


2016年10月31日月曜日

Android FileWriter,FileReader

Android FileWriter,FileReader

文件的保存位置有要求
   String path ="/data/data/" + this.getPackageName() +"/demo.txt";



import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Test();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void Test() throws IOException {
        final String tag = "testFile";
        String path ="/data/data/" + this.getPackageName() +"/demo.txt";
        FileWriter fileWriter = new FileWriter(path);

        for( int i = 0; i <102; i++){
            fileWriter.write(String.valueOf(i));
        }
        fileWriter.flush();
        fileWriter.close();

        FileReader fileReader = new FileReader(path);
        char[] buf = new char[24];
        int num;
        while(((num = fileReader.read(buf)) != 0)){
            System.out.println("---" + new String(buf,0,num));
        }
        fileReader.close();
    }
}


结果
com.example.java.m1031a I/System.out: ---012345678910111213141516
com.example.java.m1031a I/System.out: ---171819202122232425262728
com.example.java.m1031a I/System.out: ---293031323334353637383940
com.example.java.m1031a I/System.out: ---414243444546474849505152
com.example.java.m1031a I/System.out: ---535455565758596061626364
com.example.java.m1031a I/System.out: ---656667686970717273747576
com.example.java.m1031a I/System.out: ---777879808182838485868788
com.example.java.m1031a I/System.out: ---899091929394959697989910
com.example.java.m1031a I/System.out: ---0101





2016年10月30日日曜日

Android應用開發視頻教程

黑马程序员 毕向东 Java基础视频教程
https://www.youtube.com/playlist?list=PLvswSo32Xlu_ctuWa-7-huGYUlsslzVhi


Android應用開發視頻教程
https://www.youtube.com/playlist?list=PLvswSo32Xlu8EVeS2RZvTg30M78WLROkT





2016年10月27日木曜日

Grid View 自定义布局

Grid View 自定义布局

1.   选择 Grid View 的布局位置
2.   自定义Adapter
3.   设置数据




public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gv = (GridView) findViewById(R.id.gv);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view.findViewById(R.id.grid_textview);
                String s = tv.getText().toString();
                Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
        imgAdapter imgadapter = new imgAdapter();
        gv.setAdapter(imgadapter);
    }

    class imgAdapter extends BaseAdapter {
        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = LayoutInflater.from(getApplication()).inflate(R.layout.gridview, null);
            ImageView iv = (ImageView) v.findViewById(R.id.grid_img);
            TextView tv = (TextView) v.findViewById(R.id.grid_textview);
            iv.setImageResource(mThumbIds[position]);
            tv.setText(getString(mThumbIds[position]));
            return v;
        }

        private Integer[] mThumbIds = {
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7
        };
    }
}


Activity 布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.e560.m1026gridview.MainActivity">

    <GridView
        android:id="@+id/gv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
        />
</RelativeLayout>


自定义布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <ImageView
            android:id="@+id/grid_img"
            android:layout_width="400dp"
            android:layout_height="140dp"
            android:background="#CCCCCC" />

        <TextView
            android:id="@+id/grid_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFCCCC"
            android:textSize="20dp" />

</RelativeLayout>





2016年10月24日月曜日

Android 生命周期

Android 生命周期



第一次启动
MainActivity: --1--onCreate
MainActivity: --2--onStart
MainActivity: --3--onResume

跳到其他Activity
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

返回键返回
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume

接电话
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState  有延迟

挂电话
MainActivity: --3--onResume

按返回键推出到Android界面
MainActivity: --4--onPause
MainActivity: --5--onStop
MainActivity: --7--onDestroy

重新启动
MainActivity: --1--onCreate
MainActivity: --2--onStart
MainActivity: --3--onResume

旋转屏幕
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop
MainActivity: --7--onDestroy
MainActivity: --1--onCreate
MainActivity: --2--onStart
MainActivity: --8--onRestoreInstanceState
MainActivity: --3--onResume

按Home键
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

按APP图标开启
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume

按Power键,关屏幕
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

按Power键,开屏幕
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume

按方块键
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

按方块键,重新回到App
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume



public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "--1--onCreate");

        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NewActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "--2--onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "--3--onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "--4--onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "--5--onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "--6--onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "--7--onDestroy");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG, "--8--onRestoreInstanceState");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(TAG,"--9--onSaveInstanceState");
    }
}