概要
vistaでandroid studio 1.0.1やってみた。
練習問題やってみた。
練習問題
qiitaのohisamaの記事をリストして、タップでブラウザで表示せよ。
方針
- 暗黙のインテント使う。
- listview使う。
- httpsurlconnect使う。
- AsyncTask使う。
- jsonarray使う。
写真
サンプルコード
public void run() {
new AsyncTask<Void, Void, String>() {
ListView list = (ListView) findViewById(R.id.list);
final ArrayList<String> data = new ArrayList<>();
final ArrayList<String> data0 = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_single_choice, data);
@Override
protected String doInBackground(Void... voids) {
String dis = "";
String urlStr = "https://qiita.com/api/v2/users/ohisama@github/items";
String result = null;
HttpsURLConnection con;
URL url = null;
BufferedReader reader = null;
try
{
Log.e("ohi", "ok0");
url = new URL(urlStr);
con = (HttpsURLConnection) url.openConnection();
Log.e("ohi", "ok1");
con.setRequestMethod("GET");
Log.e("ohi", "ok2");
final int status = con.getResponseCode();
Log.e("ohi", "ok3");
if (status == HttpsURLConnection.HTTP_OK)
{
Log.e("ohi", "ok4");
StringBuilder stringBuilder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = reader.readLine()) != null)
{
stringBuilder.append(inputLine);
}
dis = stringBuilder.toString();
}
else
{
result = String.valueOf(status);
Log.e("ohi", "err1");
}
}
catch (Exception e)
{
Log.e("ohi", e.toString());
dis = e.toString();
}
return dis;
}
@Override
protected void onPostExecute(String result) {
try
{
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
data.add(jsonObject.getString("title"));
data0.add(jsonObject.getString("url"));
}
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String url = data0.get(i);
//Toast.makeText(MainActivity.this, String.format("選択したのは%s", url), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}.execute();
}
以上。