package com.capital.anew; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Handler handler; private final String RSS_URL = "http://m-shige1979.hatenablog.com/rss"; private TextView text1; private String RssText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(); setContentView(R.layout.activity_main); text1 = (TextView)findViewById(R.id.textview1); } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuItem item1 = menu.add("UPDATE"); item1.setIcon(android.R.drawable.ic_menu_upload); item1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener(){ @Override public boolean onMenuItemClick(MenuItem item){ Thread thread1 = new Thread(){ @Override public void run(){ try { RssText = RssParse.getRss(MainActivity.this, RSS_URL); handler.post(new Runnable(){ @Override public void run(){ text1.setText(RssText); Toast.makeText(MainActivity.this, "読み込み終了", Toast.LENGTH_SHORT).show(); } }); } catch (Exception e){ Log.d("sample", e.getMessage()); } } }; thread1.start(); return false; } }); item1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ int id = item.getItemId(); if(id == R.id.action_settings){ return true; } return super.onOptionsItemSelected(item); } }
package com.capital.anew;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class parse {
public static String getRss(Context context, String url)
throws IOException {
StringBuilder sb = new StringBuilder();
AndroidHttpClient client = AndroidHttpClient.newInstance(“TEST”);
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while((line = br.readLine()) != null){
sb.append(line);
}
} finally {
client.close();
}
return sb.toString();
}
}
[/code]