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

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