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年11月2日水曜日

ByteArrayOutputStream 练习

ByteArrayOutputStream 练习


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

public class Main {
    public static void main(String[] args) throws Exception {

    // https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be
    // https://images-na.ssl-images-amazon.com/images/I/81M-I12yh7L._SL1500_.jpg
    // http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip
    // http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip
    // http://cdefgab.web.fc2.com/song.json

    httpd h = new httpd("http://cdefgab.web.fc2.com/song.json");
    h.std();
    }
}

class httpd{
    private String durl;
 
    public httpd(String durl){
        this.durl = durl;
    }

    public void std(){
        System.out.println("sdt()-start");
        try{
        FileOutputStream fis = new FileOutputStream("demo.db");
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        InputStream is = dis();
        byte[] buff = new byte[10240];
        int len = 0;
     
        System.out.println("koko");
        while( (len = is.read(buff)) != -1){
            fis.write(buff,0,len);
            fis.flush();
            bao.write(buff,0,len);
            System.out.println(len);
        }
     
        fis.close();
        System.out.println(bao.toString());
        }catch(Exception e){
         
        }finally{
            File f = new File("demo.db");
            System.out.println(f.getName());
            System.out.println(f.getAbsolutePath());
        }
    }

    public InputStream dis(){
        InputStream inputStream = null;
        try{
            URL url = new URL(durl);
            System.out.println("url = " + durl);
            HttpURLConnection httpurl = (HttpURLConnection)url.openConnection();
            httpurl.setConnectTimeout(3000);
            httpurl.setDoInput(true);
            httpurl.setReadTimeout(3000);
            httpurl.setRequestMethod("GET");
            if(httpurl.getResponseCode() == 200){
                System.out.println("paus" + httpurl.getResponseCode());
                inputStream = httpurl.getInputStream();
            }
        }catch(Exception e){
        }
        return inputStream;
    }
}

2016年11月1日火曜日

HttpFileDownload 练习

HttpFileDownload 练习

https://paiza.io/projects/6lTQWbqAzvT-IEAHaRl4AA



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

public class Main {
    public static void main(String[] args) throws Exception {

    // https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be
    // https://images-na.ssl-images-amazon.com/images/I/81M-I12yh7L._SL1500_.jpg
    // http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip

    httpd h = new httpd("https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be");
    h.std();
    }
}

class httpd{
    private String durl;
   
    public httpd(String durl){
        this.durl = durl;
    }

    public void std(){
        System.out.println("sdt()-start");
        try{
        FileOutputStream fis = new FileOutputStream("demo.db");
        InputStream is = dis();
        byte[] buff = new byte[10240];
        int len = 0;
       
        System.out.println("koko");
        while( (len = is.read(buff)) != -1){
            fis.write(buff,0,len);
            fis.flush();
            System.out.println(len);
        }
       
        fis.close();
        }catch(Exception e){
           
        }finally{
            File f = new File("demo.db");
            System.out.println(f.getName());
            System.out.println(f.getAbsolutePath());
        }
    }

    public InputStream dis(){
        InputStream inputStream = null;
        try{
            URL url = new URL(durl);
            System.out.println("url = " + durl);
            HttpURLConnection httpurl = (HttpURLConnection)url.openConnection();
            httpurl.setConnectTimeout(3000);
            httpurl.setDoInput(true);
            httpurl.setReadTimeout(3000);
            httpurl.setRequestMethod("GET");
            if(httpurl.getResponseCode() == 200){
                System.out.println("paus" + httpurl.getResponseCode());
                inputStream = httpurl.getInputStream();
            }
        }catch(Exception e){
        }
        return inputStream;
    }
}