ネットワーク上のデータを取得できるようになった!
StartActivity.java
package jp.wpblog.valletta.denpo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class StartActivity extends AppCompatActivity
implements View.OnClickListener {
private final static String URL="http://valletta.exp.jp/wp/wp-content/uploads/2016/08/testcsv.csv";
String text;
Handler handler=new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Button btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(this);
}
public void onClick(View v) {
// ここに処理を記述
Thread thread=new Thread(new Runnable(){public void run(){
//HTTP通信
try{
text=new String(http2data(URL));
} catch(Exception e){
text=null;
}
//ハンドラの生成
handler.post(new Runnable(){public void run(){
if(text!=null){
TextView tv = (TextView)findViewById(R.id.textView);
tv.setText(text);
}else{
}
}});
}});
thread.start();
//Intent intent = new Intent();
//intent.setClassName("jp.wpblog.valletta.denpo", "jp.wpblog.valletta.denpo.MainActivity");
//startActivity(intent);
}
public static byte[] http2data(String path)throws Exception{
byte[] w=new byte[1024];
HttpURLConnection c=null;
InputStream in=null;
ByteArrayOutputStream out=null;
try{
//HTTP接続のオープン
URL url=new URL(path);
c=(HttpURLConnection)url.openConnection();
c.setRequestMethod("GET");
c.connect();
in=c.getInputStream();
//バイト配列の読み込み
out=new ByteArrayOutputStream();
while(true){
int size=in.read(w);
if(size<=0) break;
out.write(w,0,size);
}
out.close();
//HTTP通信のクローズ
in.close();
c.disconnect();
return out.toByteArray();
}catch(Exception e){
try {
if (c != null) c.disconnect();
if (in != null) in.close();
if (out != null) out.close();
}catch(Exception e2){
}
throw e;
}
}
}
ボタンを押すとネットワーク上にあるcsvファイルを読んで表示するプログラム
参考:布留川英一著、Androidプログラミングバイブル



ディスカッション
コメント一覧
まだ、コメントがありません