Java BackCall 的返回值运行在新的Thread上。
所以,在Android 上不能咋 BackCall上更新 主线程。
https://paiza.io/projects/dBt6EFZZnt8GdS0MDW8I-g
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
// Here your code !
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
Handel h = new Handel();
System.out.println("Call by BackCall thread name >>" + Thread.currentThread().getName());
h.Down(new Handel.BackCall() {
public void restout(String xx) {
System.out.println("BackCall thread name >>" + Thread.currentThread().getName());
System.out.println(xx);
}
});
}
}
class Handel {
public interface BackCall {
public void restout (String json);
}
public void Down(BackCall bc) {
new Thread(new Runnable() {
public void run() {
try {
URL u = new URL("http://www.yahoo.co.jp");
HttpURLConnection c = (HttpURLConnection)u.openConnection();
c.setConnectTimeout(3000);
c.setReadTimeout(3000);
c.setDoInput(true);
c.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.6) Gecko/20040225 Firefox/0.8");
InputStream is = null;
c.setRequestMethod("GET");
String bbb = "";
if (c.getResponseCode() == 200) {
is = c.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
bbb = br.readLine();
}
bc.restout(bbb);
} catch (Exception e) {
e.printStackTrace();
}
}
} ).start();
}
}
2016年11月30日水曜日
2016年11月29日火曜日
Android_Layout 用代码得到对象的高宽
Android_Layout 用代码得到对象的高宽
当设定 ViewGroup.LayoutParams 的设定优先。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
// viewGroup.addView(button);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams rl = (RelativeLayout.LayoutParams) ((Button) v).getLayoutParams();
System.out.println(rl.height);
System.out.println(rl.width);
System.out.println(((Button) v).getHeight());
System.out.println(((Button) v).getWidth());
}
});
}
当>>>>
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button, layoutParams);
结果
I/System.out: 500
I/System.out: 500
I/System.out: 500
I/System.out: 500
当>>>>
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button);
结果
I/System.out: -2
I/System.out: -2
I/System.out: 400
I/System.out: 400
当设定 ViewGroup.LayoutParams 的设定优先。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
// viewGroup.addView(button);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams rl = (RelativeLayout.LayoutParams) ((Button) v).getLayoutParams();
System.out.println(rl.height);
System.out.println(rl.width);
System.out.println(((Button) v).getHeight());
System.out.println(((Button) v).getWidth());
}
});
}
当>>>>
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button, layoutParams);
结果
I/System.out: 500
I/System.out: 500
I/System.out: 500
I/System.out: 500
当>>>>
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button);
结果
I/System.out: -2
I/System.out: -2
I/System.out: 400
I/System.out: 400
Android_Layout 用代码添加对象
Android LayoutParams
用代码添加对象(按键),并设置LayoutParames,
当按键Click时,变更LayoutParames 的值。
public class MainActivity extends AppCompatActivity {
/**
* https://www.youtube.com/watch?v=QSsvUbPVHOU&index=3&list=PLTstZD3AK3S9sR6uiKzmNtgnY5p4nMT3Z
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
// "NG>>" ViewGroup viewGroup = (ViewGroup) findViewById(R.layout.activity_main);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
((Button) v).setLayoutParams(layoutParams1);
// java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
// "NG>>" ViewGroup.LayoutParams layoutParams1 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// Button bbt = (Button) v;
// bbt.setLayoutParams(layoutParams1);
}
});
}
}
用代码添加对象(按键),并设置LayoutParames,
当按键Click时,变更LayoutParames 的值。
public class MainActivity extends AppCompatActivity {
/**
* https://www.youtube.com/watch?v=QSsvUbPVHOU&index=3&list=PLTstZD3AK3S9sR6uiKzmNtgnY5p4nMT3Z
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
// "NG>>" ViewGroup viewGroup = (ViewGroup) findViewById(R.layout.activity_main);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
((Button) v).setLayoutParams(layoutParams1);
// java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
// "NG>>" ViewGroup.LayoutParams layoutParams1 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// Button bbt = (Button) v;
// bbt.setLayoutParams(layoutParams1);
}
});
}
}
2016年11月27日日曜日
Android SQL
Android SQL
package com.example.e560.m1126a.ToolsClass;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Created by E560 on 2016/11/26.
*/
public class FlickrSQL {
/**
*
*/
private Context context;
private final String TAG = "FlickrSQL";
private final String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
private final String DB_NAME = "IdolAPP.db";
private final int DB_VERSION = 1;
private mSQL mSQL_db;
/**
* @param context
*/
public FlickrSQL(Context context) {
this.context = context;
mSQL_db = new mSQL(context, DB_NAME, null, DB_VERSION);
}
/**
* 檢查Name是否存在。count = 1 存在,0 不存在。
*
* @param name
* @return
* @throws Exception
*/
public int check_name(String name) throws Exception {
int count = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "select name from toplist where name = ?";
Cursor cursor = db.rawQuery(sql_cmd, new String[]{name});
count = cursor.getCount();
cursor.close();
db.close();
return count;
}
/**
* 返回Name個數。
*
* @return
*/
public int db_count() {
int count = 0;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select count(*) from toplist";
Cursor cursor = db.rawQuery(sql_cmd, null);
while (cursor.moveToNext()) {
count = Integer.parseInt(cursor.getString(cursor.getColumnIndex("count(*)")));
}
cursor.close();
Log.i(TAG, "db_idols_count: " + count);
db.close();
return count;
}
/**
* 返回所有條目。
*
* @return
*/
public Cursor Selectall() {
Cursor cursor = null;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select * from toplist WHERE active NOT IN(?) ORDER BY up_date DESC ";
cursor = db.rawQuery(sql_cmd, new String[]{"false"});
return cursor;
}
/**
* 從JSON_PATH 更新客戶端數據庫。
* String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
*
* @throws Exception
*/
public void sysdb() throws Exception {
int insertcount = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String json = FlickrHttp.GetResultstring(JSON_PATH);
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("idolnames");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (check_name(jsonObject1.getString("name")) == 1) {
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
} else {
insertcount++;
insert(jsonObject1.getString("name"), jsonObject1.getString("img"));
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
}
}
Log.i(TAG, "sysdb: new Insert " + insertcount);
db.close();
}
public void insert(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "insert into toplist(name,img_url) values (? ,?)";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_imgurl(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set img_url = ? where name = ?";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_active(String name, String active) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set active = ? where name = ?";
db.execSQL(sql_cmd, new String[]{active, name});
db.close();
}
public class mSQL extends SQLiteOpenHelper {
/**
* mSQL_db = new mSQL(context, db_pak_name, null, db_version);
* https://farm8.staticflickr.com/7566/15949681296_b6a869bdfd_q.jpg
* https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg
*/
public mSQL(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String topidoltable = "create table toplist (rowid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL,up_date TEXT default current_timestamp,img_url TEXT NOT NULL, accc INTEGER DEFAULT 0, Active TEXT DEFAULT 'ture')";
String setimgurl = "update toplist set img_url = ?";
db.execSQL(topidoltable);
db.execSQL(setimgurl, new String[]{"https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg"});
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
/**
* Created by E560 on 2016/11/26.
*/
public class test_FlickrSQL extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
new Th().start();
}
class Th extends Thread {
@Override
public void run() {
try {
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
// flickrSQL.sysdb();
// flickrSQL.db_count();
Cursor cursor = flickrSQL.Selectall();
while (cursor.moveToNext()) {
String rowid = cursor.getString(cursor.getColumnIndex("rowid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String up_date = cursor.getString(cursor.getColumnIndex("up_date"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
String accc = cursor.getString(cursor.getColumnIndex("accc"));
String Active = cursor.getString(cursor.getColumnIndex("Active"));
System.out.println(rowid);
System.out.println(name);
System.out.println(up_date);
System.out.println(img_url);
System.out.println(accc);
System.out.println(Active);
}
// cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.example.e560.m1126a.ToolsClass;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Created by E560 on 2016/11/26.
*/
public class FlickrSQL {
/**
*
*/
private Context context;
private final String TAG = "FlickrSQL";
private final String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
private final String DB_NAME = "IdolAPP.db";
private final int DB_VERSION = 1;
private mSQL mSQL_db;
/**
* @param context
*/
public FlickrSQL(Context context) {
this.context = context;
mSQL_db = new mSQL(context, DB_NAME, null, DB_VERSION);
}
/**
* 檢查Name是否存在。count = 1 存在,0 不存在。
*
* @param name
* @return
* @throws Exception
*/
public int check_name(String name) throws Exception {
int count = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "select name from toplist where name = ?";
Cursor cursor = db.rawQuery(sql_cmd, new String[]{name});
count = cursor.getCount();
cursor.close();
db.close();
return count;
}
/**
* 返回Name個數。
*
* @return
*/
public int db_count() {
int count = 0;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select count(*) from toplist";
Cursor cursor = db.rawQuery(sql_cmd, null);
while (cursor.moveToNext()) {
count = Integer.parseInt(cursor.getString(cursor.getColumnIndex("count(*)")));
}
cursor.close();
Log.i(TAG, "db_idols_count: " + count);
db.close();
return count;
}
/**
* 返回所有條目。
*
* @return
*/
public Cursor Selectall() {
Cursor cursor = null;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select * from toplist WHERE active NOT IN(?) ORDER BY up_date DESC ";
cursor = db.rawQuery(sql_cmd, new String[]{"false"});
return cursor;
}
/**
* 從JSON_PATH 更新客戶端數據庫。
* String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
*
* @throws Exception
*/
public void sysdb() throws Exception {
int insertcount = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String json = FlickrHttp.GetResultstring(JSON_PATH);
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("idolnames");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (check_name(jsonObject1.getString("name")) == 1) {
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
} else {
insertcount++;
insert(jsonObject1.getString("name"), jsonObject1.getString("img"));
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
}
}
Log.i(TAG, "sysdb: new Insert " + insertcount);
db.close();
}
public void insert(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "insert into toplist(name,img_url) values (? ,?)";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_imgurl(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set img_url = ? where name = ?";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_active(String name, String active) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set active = ? where name = ?";
db.execSQL(sql_cmd, new String[]{active, name});
db.close();
}
public class mSQL extends SQLiteOpenHelper {
/**
* mSQL_db = new mSQL(context, db_pak_name, null, db_version);
* https://farm8.staticflickr.com/7566/15949681296_b6a869bdfd_q.jpg
* https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg
*/
public mSQL(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String topidoltable = "create table toplist (rowid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL,up_date TEXT default current_timestamp,img_url TEXT NOT NULL, accc INTEGER DEFAULT 0, Active TEXT DEFAULT 'ture')";
String setimgurl = "update toplist set img_url = ?";
db.execSQL(topidoltable);
db.execSQL(setimgurl, new String[]{"https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg"});
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
/**
* Created by E560 on 2016/11/26.
*/
public class test_FlickrSQL extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
new Th().start();
}
class Th extends Thread {
@Override
public void run() {
try {
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
// flickrSQL.sysdb();
// flickrSQL.db_count();
Cursor cursor = flickrSQL.Selectall();
while (cursor.moveToNext()) {
String rowid = cursor.getString(cursor.getColumnIndex("rowid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String up_date = cursor.getString(cursor.getColumnIndex("up_date"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
String accc = cursor.getString(cursor.getColumnIndex("accc"));
String Active = cursor.getString(cursor.getColumnIndex("Active"));
System.out.println(rowid);
System.out.println(name);
System.out.println(up_date);
System.out.println(img_url);
System.out.println(accc);
System.out.println(Active);
}
// cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2016年11月23日水曜日
Android Handler
Android Handler
public class MainActivity extends AppCompatActivity {
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nThread n = new nThread();
n.start();
Button bt = (Button) findViewById(R.id.Bub);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message msg = handler.obtainMessage();
msg.obj = "SandMessage";
handler.sendMessage(msg);
}
});
}
class nThread extends Thread {
@Override
public void run() {
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println(msg.obj);
System.out.println(Thread.currentThread().getName());
}
};
Looper.loop();
}
}
}
public class MainActivity extends AppCompatActivity {
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nThread n = new nThread();
n.start();
Button bt = (Button) findViewById(R.id.Bub);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message msg = handler.obtainMessage();
msg.obj = "SandMessage";
handler.sendMessage(msg);
}
});
}
class nThread extends Thread {
@Override
public void run() {
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println(msg.obj);
System.out.println(Thread.currentThread().getName());
}
};
Looper.loop();
}
}
}
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));
}
}
}
}
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月20日日曜日
Javascript Json
Json String
function getjson(){
var idolname = document.getElementsByClassName('idolname');
var idolnames ={};
var list = [];
for(var i = 0; i < idolname.length; i++){
var item = {};
item.name = idolname[i].innerText;
item.img = "https://farm4.staticflickr.com/3239/2897452239_d2cf730467_s.jpg";
item.count = "10";
item.active = "0";
list.push(item);
}
idolnames.total = idolname.length;
idolnames.idolnames = list;
console.log(JSON.stringify(idolnames));
}
function getjson(){
var idolname = document.getElementsByClassName('idolname');
var idolnames ={};
var list = [];
for(var i = 0; i < idolname.length; i++){
var item = {};
item.name = idolname[i].innerText;
item.img = "https://farm4.staticflickr.com/3239/2897452239_d2cf730467_s.jpg";
item.count = "10";
item.active = "0";
list.push(item);
}
idolnames.total = idolname.length;
idolnames.idolnames = list;
console.log(JSON.stringify(idolnames));
}
java 字符串分割,得到文件名
java 字符串分割
得到URL的文件名
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg";
String[] sa = s.split("/");
System.out.println(sa[sa.length-1]);
}
}
得到URL的文件名
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg";
String[] sa = s.split("/");
System.out.println(sa[sa.length-1]);
}
}
2016年11月19日土曜日
Android Flickr API 显示缩略图
两个后台任务,一个负责得到列表,另一个下载每一个图片。
保存缩略图到getApplication().getCacheDir(),如果文件存在就读Cache,
不存在时从网络下载。
/**
* Created by E560 on 2016/11/19.
*/
public class Mlistview extends AppCompatActivity {
private GridView gridView;
private final String imgsize = "s";
private final String test_url = "http://cdefgab.web.fc2.com/song.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mlistview);
new getlistmap().execute(test_url);
}
protected class getlistmap extends AsyncTask<String, Integer, List<String>> {
/*
* 返回所以縮圖,最長邊為 100的URL;
*/
@Override
protected List<String> doInBackground(String... params) {
GetJson getJson = new GetJson(params[0]);
List<String> listurl = new ArrayList<String>();
try {
HashMap<Integer, HashMap> items_map = getJson.jsonMap();
for (int i = 0; i < items_map.size(); i++) {
listurl.add(GetJson.img_url(items_map.get(i), imgsize));
}
} catch (Exception e) {
e.printStackTrace();
}
return listurl;
}
@Override
protected void onPostExecute(List<String> strings) {
super.onPostExecute(strings);
gridView = (GridView) findViewById(R.id.mlistview);
myAdapter my = new myAdapter(strings);
my.notifyDataSetChanged();
gridView.setAdapter(my);
}
}
protected class myAdapter extends BaseAdapter {
private List<String> list;
public myAdapter(List<String> list) {
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
View v = new View(getApplication());
if (convertView == null) {
v = LayoutInflater.from(getApplication()).inflate(R.layout.ladapter, null);
} else {
v = convertView;
}
ImageView iv = (ImageView) v.findViewById(R.id.imageView2);
iv.setImageBitmap(bitmap);
GG gg = new GG(iv);
gg.execute(list.get(position));
return v;
}
public class GG extends AsyncTask<String, Integer, Bitmap> {
private Bitmap bitmap;
private ImageView iv;
public GG(ImageView iv) {
this.iv = iv;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
// https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg
String[] sa = params[0].split("/");
File file = new File(getApplication().getCacheDir(), sa[sa.length - 1]);
if (file.isFile()) {
FileInputStream fin = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fin);
fin.close();
} else {
bitmap = GetJson.getBitmap(params[0]);
FileOutputStream fon = new FileOutputStream(file);
ByteArrayOutputStream bas = GetJson.getBAOS(params[0]);
fon.write(bas.toByteArray());
fon.flush();
fon.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
iv.setImageBitmap(bitmap);
}
}
}
}
2016年11月17日木曜日
Android BitmapFactory 文件下载前得到文件宽高
Android BitmapFactory 文件下载前得到文件宽高
http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG
com.example.java.m1117a I/System.out: 4737
com.example.java.m1117a I/System.out: 3264
com.example.java.m1117a I/System.out: image/jpeg
https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg
com.example.java.m1117a I/System.out: 1024
com.example.java.m1117a I/System.out: 682
com.example.java.m1117a I/System.out: image/jpeg
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 t = new T1();
t.execute("test");
}
class T1 extends AsyncTask<String, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
// InputStream is = HttpTool.gis("https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg");
InputStream is = HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
System.out.println(options.outHeight);
System.out.println(options.outWidth);
System.out.println(options.outMimeType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
}
}
}
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();
}
}
得到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();
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"));
也可以直接加载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));
}
}
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));
}
}
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();
}
}
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);
}
}
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();
}
}
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();
}
}
}
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();
}
}
}
使用内部存储
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;
}
}
}
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;
}
}
}
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;
}
}
}
登録:
投稿 (Atom)