0
0

More than 1 year has passed since last update.

vistaでandroid studio その12

Last updated at Posted at 2022-09-03

概要

vistaでandroid studio 1.0.1やってみた。
練習問題やってみた。

練習問題

qiitaのohisamaの記事をリストして、タップでブラウザで表示せよ。

方針

  • 暗黙のインテント使う。
  • listview使う。
  • httpsurlconnect使う。
  • AsyncTask使う。
  • jsonarray使う。

写真

device-2022-09-03-063009.png

サンプルコード

	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();
	}

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0