Android 的第一款軟體誕生。利用了Flickr提供的圖片查詢API按照名稱
查詢圖片,並顯示在手機上。
2016年5月開始接觸JAVA, 本軟體是邊學邊用的結果。
下一款軟體爭取能夠公開在GooglePlay上。
下載地址
app-free-release.apk
https://www.asuswebstorage.com/navigate/s/181301E935CB4FD480EB2D54B763A9A9Y
2017年3月6日月曜日
2017年2月24日金曜日
Android MediaPlayer
Android MediaPlayer
protected void t1() {
try {
String url = "http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3";
// Uri mu = Uri.parse("http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3");
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
// mediaPlayer.setDataSource(getApplicationContext(), mu);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void t1() {
try {
String url = "http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3";
// Uri mu = Uri.parse("http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3");
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
// mediaPlayer.setDataSource(getApplicationContext(), mu);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
}
2017年2月7日火曜日
2016年12月25日日曜日
Android 外部存储
Android 外部存储
https://developer.android.com/guide/topics/data/data-storage.html
protected void saveto() {
// I/System.out: this.getDatabasePath("test")
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
File f1 = this.getDatabasePath("test");
System.out.println("this.getDatabasePath(\"test\")");
System.out.println(f1.getAbsolutePath());
System.out.println(f1.getPath());
System.out.println(f1.toString());
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
File f2 = this.getExternalFilesDir(null);
System.out.println("this.getExternalFilesDir(null)");
System.out.println(f2.getAbsolutePath());
System.out.println(f2.getPath());
System.out.println(f2.toString());
// I/System.out: /data
// I/System.out: /data
// I/System.out: /data
File f3 = Environment.getDataDirectory();
System.out.println("Environment.getDataDirectory()");
System.out.println(f3.getAbsolutePath());
System.out.println(f3.getPath());
System.out.println(f3.toString());
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
File f4 = Environment.getExternalStorageDirectory();
System.out.println("Environment.getExternalStorageDirectory()");
System.out.println(f4.getAbsolutePath());
System.out.println(f4.getPath());
System.out.println(f4.toString());
}
https://developer.android.com/guide/topics/data/data-storage.html
protected void saveto() {
// I/System.out: this.getDatabasePath("test")
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
File f1 = this.getDatabasePath("test");
System.out.println("this.getDatabasePath(\"test\")");
System.out.println(f1.getAbsolutePath());
System.out.println(f1.getPath());
System.out.println(f1.toString());
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
File f2 = this.getExternalFilesDir(null);
System.out.println("this.getExternalFilesDir(null)");
System.out.println(f2.getAbsolutePath());
System.out.println(f2.getPath());
System.out.println(f2.toString());
// I/System.out: /data
// I/System.out: /data
// I/System.out: /data
File f3 = Environment.getDataDirectory();
System.out.println("Environment.getDataDirectory()");
System.out.println(f3.getAbsolutePath());
System.out.println(f3.getPath());
System.out.println(f3.toString());
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
File f4 = Environment.getExternalStorageDirectory();
System.out.println("Environment.getExternalStorageDirectory()");
System.out.println(f4.getAbsolutePath());
System.out.println(f4.getPath());
System.out.println(f4.toString());
}
2016年12月24日土曜日
Android IntentService 类
Android IntentService 类
https://developer.android.com/guide/components/services.html
Develop > API Guides > 应用组件
//////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.e560.m1217a">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyServer"></service>
</application>
</manifest>
//////////////////////////////////////////////////////////////////////
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
Button bt = new Button(this);
bt.setText("SaveFiletoAndroidFile");
linearLayout.addView(bt);
setContentView(linearLayout);
i = 0;
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
SavetoServer(i);
}
});
}
protected void SavetoServer(int i) {
String[] imgURLs = new String[]{
"https://farm4.staticflickr.com/3239/2897452239_d2cf730467.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3050\\/2897460805_781ed40c84.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3553\\/3619665782_e9766aefe5.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
};
Intent intent = new Intent(this, MyServer.class);
intent.putExtra("URL", imgURLs[i].toString());
startService(intent);
}
}
https://developer.android.com/guide/components/services.html
Develop > API Guides > 应用组件
//////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.e560.m1217a">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyServer"></service>
</application>
</manifest>
//////////////////////////////////////////////////////////////////////
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
Button bt = new Button(this);
bt.setText("SaveFiletoAndroidFile");
linearLayout.addView(bt);
setContentView(linearLayout);
i = 0;
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
SavetoServer(i);
}
});
}
protected void SavetoServer(int i) {
String[] imgURLs = new String[]{
"https://farm4.staticflickr.com/3239/2897452239_d2cf730467.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3050\\/2897460805_781ed40c84.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3553\\/3619665782_e9766aefe5.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
};
Intent intent = new Intent(this, MyServer.class);
intent.putExtra("URL", imgURLs[i].toString());
startService(intent);
}
}
//////////////////////////////////////////////////////////////////////
import android.app.IntentService;
import android.content.Intent;
public class MyServer extends IntentService {
public MyServer() {
super("test");
}
@Override
protected void onHandleIntent(Intent intent) {
HTTPClient httpClient = new HTTPClient(getApplicationContext(), intent.getStringExtra("URL"));
}
}
//////////////////////////////////////////////////////////////////////
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HTTPClient {
private String urlString;
private String FileName;
private String savePath;
private Context context;
public HTTPClient(Context context, String urlString) {
this.context = context;
this.urlString = urlString.replace("\\", "");
this.savePath = String.valueOf(this.context.getFilesDir());
FileName = getFname(urlString);
System.out.println("Thread.name Httpclient" + Thread.currentThread().getName());
SaveFile();
}
public void SaveFile() {
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5 * 1000);
httpURLConnection.setReadTimeout(5 * 1000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
if (httpURLConnection.getResponseCode() == 200) {
File SaveF = new File(this.savePath + "/" + this.FileName);
InputStream inputStream = httpURLConnection.getInputStream();
FileOutputStream fos = new FileOutputStream(SaveF);
byte[] buff = new byte[4096];
int len = 0;
while ((len = inputStream.read(buff)) != -1) {
fos.write(buff, 0, len);
fos.flush();
}
fos.close();
inputStream.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected String getFname(String url) {
String[] temp = url.split("/");
return temp[temp.length - 1];
}
}
2016年12月5日月曜日
Android FTP 文件上传
Android FTP 文件上传
package com.example.e560.m1126a.ToolsClass;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by E560 on 2016/12/04.
*/
public class sun_FTP {
private String ftp_url, ftp_user, ftp_password;
private boolean ftp_open;
private String TAG = "sun_FTP";
public sun_FTP(String ftp_url, String ftp_user, String ftp_password) {
this.ftp_url = ftp_url;
this.ftp_user = ftp_user;
this.ftp_password = ftp_password;
this.ftp_open = true;
}
public void Ftp_connect(String file_mode, File file) throws IOException {
InetAddress inetAddress = InetAddress.getByName(ftp_url);
Socket socket21 = new Socket(inetAddress.getHostAddress(), 21);
BufferedReader ftpcmd_input = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
BufferedWriter ftpcmd_output = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
sendFTPcommand(ftpcmd_output, "USER " + ftp_user);
sendFTPcommand(ftpcmd_output, "PASS " + ftp_password);
sendFTPcommand(ftpcmd_output, "PASV ");
switch (file_mode) {
case "upFile":
while (ftp_open) {
String temp = ftpcmd_input.readLine();
Log.i(TAG, temp);
String code = temp.substring(0, 3);
//进入被动模式(IP 地址、ID 端口)
if (code.equals("227")) {
String[] temp2 = get227(temp);
sendFTPcommand(ftpcmd_output, "TYPE " + "I");
sendFTPcommand(ftpcmd_output, "STOR " + file.getName());
upFile(temp2, file);
sendFTPcommand(ftpcmd_output, "QUIT");
ftpcmd_output.
}
}
break;
case "downFile":
break;
case "Del_file":
break;
}
}
private void upFile(String[] urltemp, File file) throws IOException {
Socket dataSocket = new Socket(urltemp[0], Integer.parseInt(urltemp[1]));
OutputStream outputStream = dataSocket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buff = new byte[20480];
int len = 0;
while ((len = fileInputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
dataSocket.close();
ftp_open = false;
}
protected void sendFTPcommand(BufferedWriter ftpcmd_output, String command) throws IOException {
ftpcmd_output.write(command + "\r\n");
ftpcmd_output.flush();
if (command.equals("QUIT")) {
ftpcmd_output.close();
}
}
protected Socket ftpSocket() throws IOException {
Socket socket = new Socket(ftp_url, 21);
return null;
}
protected String[] get227(String string) {
//227 Entering Passive Mode (208,71,106,43,237,147).
int start = string.indexOf("(") + 1;
int end = string.indexOf(")");
String substring = string.substring(start, end);
Log.i(TAG, substring);
String[] temp = substring.split(",");
String ip = temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3];
int port = Integer.parseInt(temp[4]) * 256 + Integer.parseInt(temp[5]);
String sport = String.valueOf(port);
Log.i(TAG, "POST " + port);
String[] res = {ip, sport};
return res;
}
}
package com.example.e560.m1126a.ToolsClass;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by E560 on 2016/12/04.
*/
public class sun_FTP {
private String ftp_url, ftp_user, ftp_password;
private boolean ftp_open;
private String TAG = "sun_FTP";
public sun_FTP(String ftp_url, String ftp_user, String ftp_password) {
this.ftp_url = ftp_url;
this.ftp_user = ftp_user;
this.ftp_password = ftp_password;
this.ftp_open = true;
}
public void Ftp_connect(String file_mode, File file) throws IOException {
InetAddress inetAddress = InetAddress.getByName(ftp_url);
Socket socket21 = new Socket(inetAddress.getHostAddress(), 21);
BufferedReader ftpcmd_input = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
BufferedWriter ftpcmd_output = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
sendFTPcommand(ftpcmd_output, "USER " + ftp_user);
sendFTPcommand(ftpcmd_output, "PASS " + ftp_password);
sendFTPcommand(ftpcmd_output, "PASV ");
switch (file_mode) {
case "upFile":
while (ftp_open) {
String temp = ftpcmd_input.readLine();
Log.i(TAG, temp);
String code = temp.substring(0, 3);
//进入被动模式(IP 地址、ID 端口)
if (code.equals("227")) {
String[] temp2 = get227(temp);
sendFTPcommand(ftpcmd_output, "TYPE " + "I");
sendFTPcommand(ftpcmd_output, "STOR " + file.getName());
upFile(temp2, file);
sendFTPcommand(ftpcmd_output, "QUIT");
ftpcmd_output.
}
}
break;
case "downFile":
break;
case "Del_file":
break;
}
}
private void upFile(String[] urltemp, File file) throws IOException {
Socket dataSocket = new Socket(urltemp[0], Integer.parseInt(urltemp[1]));
OutputStream outputStream = dataSocket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buff = new byte[20480];
int len = 0;
while ((len = fileInputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
dataSocket.close();
ftp_open = false;
}
protected void sendFTPcommand(BufferedWriter ftpcmd_output, String command) throws IOException {
ftpcmd_output.write(command + "\r\n");
ftpcmd_output.flush();
if (command.equals("QUIT")) {
ftpcmd_output.close();
}
}
protected Socket ftpSocket() throws IOException {
Socket socket = new Socket(ftp_url, 21);
return null;
}
protected String[] get227(String string) {
//227 Entering Passive Mode (208,71,106,43,237,147).
int start = string.indexOf("(") + 1;
int end = string.indexOf(")");
String substring = string.substring(start, end);
Log.i(TAG, substring);
String[] temp = substring.split(",");
String ip = temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3];
int port = Integer.parseInt(temp[4]) * 256 + Integer.parseInt(temp[5]);
String sport = String.valueOf(port);
Log.i(TAG, "POST " + port);
String[] res = {ip, sport};
return res;
}
}
2016年12月2日金曜日
Android 网络信息和IP地址
Android 网络信息和IP地址
package com.example.java.m1202a;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(this.getClass().getCanonicalName());
test_network();
test_ipadd();
}
/**
* <uses-permission android:name="android.permission.INTERNET"/>
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
*/
protected void test_network() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
System.out.println("toString " + networkInfo.toString());
System.out.println("getType " + networkInfo.getType());
System.out.println("getTypeName " + networkInfo.getTypeName());
System.out.println("getState " + networkInfo.getState());
System.out.println("getDetailedState " + networkInfo.getDetailedState());
System.out.println("getReason " + networkInfo.getReason());
System.out.println("getSubtypeName " + networkInfo.getSubtypeName());
System.out.println("getExtraInfo " + networkInfo.getExtraInfo());
System.out.println("describeContents " + networkInfo.describeContents());
System.out.println(networkInfo.getClass().getCanonicalName());
}
protected void test_ipadd() {
System.out.println("test_ipadd 7777");
try {
Enumeration<NetworkInterface> networkInterfaces = null;
networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface2 = networkInterfaces.nextElement();
Enumeration<InetAddress> ipadd = networkInterface2.getInetAddresses();
while (ipadd.hasMoreElements()) {
System.out.println(ipadd.nextElement().toString());
}
}
System.out.println(networkInterfaces.getClass().getCanonicalName());
} catch (SocketException e) {
e.printStackTrace();
}
}
}
package com.example.java.m1202a;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(this.getClass().getCanonicalName());
test_network();
test_ipadd();
}
/**
* <uses-permission android:name="android.permission.INTERNET"/>
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
*/
protected void test_network() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
System.out.println("toString " + networkInfo.toString());
System.out.println("getType " + networkInfo.getType());
System.out.println("getTypeName " + networkInfo.getTypeName());
System.out.println("getState " + networkInfo.getState());
System.out.println("getDetailedState " + networkInfo.getDetailedState());
System.out.println("getReason " + networkInfo.getReason());
System.out.println("getSubtypeName " + networkInfo.getSubtypeName());
System.out.println("getExtraInfo " + networkInfo.getExtraInfo());
System.out.println("describeContents " + networkInfo.describeContents());
System.out.println(networkInfo.getClass().getCanonicalName());
}
protected void test_ipadd() {
System.out.println("test_ipadd 7777");
try {
Enumeration<NetworkInterface> networkInterfaces = null;
networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface2 = networkInterfaces.nextElement();
Enumeration<InetAddress> ipadd = networkInterface2.getInetAddresses();
while (ipadd.hasMoreElements()) {
System.out.println(ipadd.nextElement().toString());
}
}
System.out.println(networkInterfaces.getClass().getCanonicalName());
} catch (SocketException e) {
e.printStackTrace();
}
}
}
2016年12月1日木曜日
Android 保存 GridView 的位置
保存 GridView 的位置
gridView.getFirstVisiblePosition();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex("name"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
Toast.makeText(ListPage.this, img_url, Toast.LENGTH_SHORT).show();
grp = gridView.getFirstVisiblePosition();
Intent intent = new Intent(getApplicationContext(), Idolpiclist.class);
intent.putExtra("name", name);
startActivity(intent);
}
});
private class Myhand extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
cursor = (Cursor) msg.obj;
System.out.println(cursor.getCount());
GridView gridView = (GridView) findViewById(R.id.List_page_gridview);
gridView.setSelection(grp+1);
gridView.setAdapter(new Myadapter());
}
}
gridView.getFirstVisiblePosition();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex("name"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
Toast.makeText(ListPage.this, img_url, Toast.LENGTH_SHORT).show();
grp = gridView.getFirstVisiblePosition();
Intent intent = new Intent(getApplicationContext(), Idolpiclist.class);
intent.putExtra("name", name);
startActivity(intent);
}
});
private class Myhand extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
cursor = (Cursor) msg.obj;
System.out.println(cursor.getCount());
GridView gridView = (GridView) findViewById(R.id.List_page_gridview);
gridView.setSelection(grp+1);
gridView.setAdapter(new Myadapter());
}
}
android.os.Process.setThreadPriority(-8);
android.os.Process.setThreadPriority(-8);
private class MyThread extends Thread {
@Override
public void run() {
android.os.Process.setThreadPriority(-8);
super.run();
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
Message message = myhand.obtainMessage();
message.obj = flickrSQL.SelectallIdol();
myhand.sendMessage(message);
}
}
private class MyThread extends Thread {
@Override
public void run() {
android.os.Process.setThreadPriority(-8);
super.run();
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
Message message = myhand.obtainMessage();
message.obj = flickrSQL.SelectallIdol();
myhand.sendMessage(message);
}
}
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月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日月曜日
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日水曜日
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();
}
}
}
登録:
投稿 (Atom)