【Android】JSONObjectにおけるnull判定の方法
JSONの値がnullかどうか判定する方法です。
以下のJSONデータのnullを判定する例を書いていきます。
{ data1 : "データ1" data2 : "データ2", data3 : null }
JSONObjectの作成
JSONObject json = new JSONObject(JSONデータ);
isNull()
値がnullまたはキー自体が存在しない場合はtrueを返却してくれます。
上記のJSONデータのnullを判定した結果です。
json.isNull("data3") -> true json.isNull("data4") -> true
has()
キーが存在する場合はtrueを返却してくれます。
上記のJSONデータのnullを判定した結果です。
json.has("data1") -> true json.has("data4") -> false
参考サイト:
org.json.JSONObjectにおけるnullの取扱い | infoScoop開発者ブログ
2.07. 直列化とコレクション、永続化 · mixi-inc/AndroidTraining Wiki · GitHub
【Android】ArrayListに格納したHashMapをgetし表示する方法
ArrayList
のなかからHashMap
を取り出して、Log
に表示するまでを書いていきます。
表示方法
ArrayListの作成
ArrayList<HashMap> list = new ArrayList<HashMap>();
ArrayListにHashMapを格納
for (int i = 0; i < 10; i++) { HashMap<String, String> map = new HashMap<String, String>(); map.put("name", "Tom"); map.put("age", "16"); map.put("mail", "tom@mail.com"); //リストへ追加 list.add(map); }
ログでHashMapの中身を表示
型変換する必要があります。
Log.v("name", ((HashMap<String, String>) list.get(0)).get("name"));
【Android】地図でのピンと吹き出しのクリックイベント
地図に表示されるピンとそのピンに表示される吹き出しをクリックしたときに、何かしらの処理を実行したい場合の方法です。
クリックリスナーについて書いていきます。
ピンのクリックリスナー
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { Toast.makeText(getActivity(), "ピンクリック", Toast.LENGTH_LONG).show(); return false; } });
吹き出しのクリックリスナー
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { Toast.makeText(getActivity(), "吹き出しクリック", Toast.LENGTH_LONG).show(); } });
参考サイト:
【Android】Fragmentに地図とピンを表示する方法
Fragmentに地図を表示し、その上にピンを表示する方法にハマったので、その解決方法を書きます。
Google APIキーを取得し設定ていることを前提としています。
レイアウトの作成
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/fragment_map" tools:context="com.example.macuser.takiken.MapsFragment" android:name="com.google.android.gms.maps.SupportMapFragment" />
フラグメントの作成
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsFragment extends Fragment { private GoogleMap mMap; // Might be null if Google Play services APK is not available. public static MapsFragment newInstance() { MapsFragment fragment = new MapsFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } public MapsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view =inflater.inflate(R.layout.fragment_maps, container, false); return view; } @Override public void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { mMap.getUiSettings().setZoomControlsEnabled(true);//拡大縮小ボタン表示 LatLng morioka = new LatLng(39.703531, 141.152667);//盛岡 LatLng takizawa = new LatLng(39.734694, 141.077056);//滝沢 CameraPosition.Builder camerapos = new CameraPosition.Builder();//表示位置の作成 camerapos.target(morioka);//カメラの表示位置の指定 camerapos.zoom(13.0f);//ズームレベル camerapos.bearing(0);//カメラの向きの指定(北向きなので0) camerapos.tilt(25.0f);//カメラの傾き設定 mMap.moveCamera(CameraUpdateFactory.newCameraPosition(camerapos.build()));//マップの表示位置変更 MarkerOptions options = new MarkerOptions();//ピンの設定 options.position(morioka);//ピンの場所を指定 options.title("盛岡");//マーカーの吹き出しの設定 mMap.addMarker(options);//ピンの設置 options.position(takizawa); options.title("滝沢"); mMap.addMarker(options); } }
参考サイト:
【Android】配列(ArrayList)の中身をランダムに並び替える方法
配列の中身をランダムに並べ替える方法です。
並び替え方法
ArrayList<String> list = new ArrayList<String>(); list.add("test1"); list.add("test2"); list.add("test3"); Collections.shuffle(list);// 配列の中身をシャッフル Log.v("配列の先頭", choices.get(0));// 配列の先頭をログで表示
参考サイト:
【Android】Fragmentへの画面遷移の方法
Fragmentへ画面遷移する方法は、Activityへの画面遷移と異なります。
今回は、Fragmentへ画面遷移する方法を書きます。
Activity -> Fragment
FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.container, フラグメント名.newInstance(引数があったらここに入力)).commit();
Fragment -> Fragment
FragmentからFragmentへ画面遷移する場合はgetActivity()
が必要になります。
FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.container, フラグメント名.newInstance(引数があったらここに入力)).commit();
【Android】ラジオボタンの使い方
ラジオボタンはRadioGroup
クラスとRadioButton
クラスを利用します。
RadioGroup
クラスには2つ以上のRadioButton
クラスを持たせるようにします。
レイアウトの作成
<RadioGroup android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/RadioGroup"> <RadioButton android:text="1" android:id="@+id/RadioButton1" android:layout_height="wrap_content" android:layout_width="wrap_content" /> <RadioButton android:text="2" android:id="@+id/RadioButtoni2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioButton android:text="3" android:id="@+id/RadioButton3" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RadioGroup>
値の取得方法1
ラジオボタンが選択された項目が変わったことを知るにはRadioGroup
クラスのsetOnCheckedChangeListener
メソッドでOnCheckedChangeListener
インタフェースを登録します。
何が選択されているかはRadioGroup
クラスのgetCheckedRadioButtonId
メソッドの戻り値でIDを知ることができます。何も選択されていない時は-1が返ってきます。
radioGroup = (RadioGroup) findViewById(R.id.RadioGroup); radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId != -1) { // 選択されているラジオボタンの取得 RadioButton radioButton = (RadioButton) findViewById(checkedId); // ラジオボタンのテキストを取得 String text = radioButton.getText().toString(); Log.v("checked", text); } else { // 何も選択されていない場合の処理 } } });
値の取得方法2
決定ボタンをクリックしたときに値を取得したいなどの場合です。
その場合は、RadioGroup
クラスのgetCheckedRadioButtonId
メソッドを利用します。戻り値でそのRadioGroup
のなかで選択されているRadioButton
を取得することができます。onCheckedChanged
メソッドと同様に何も選択されていない場合には-1が返ってきます。
int checkedId = radioGroup.getCheckedRadioButtonId(); if (checkedId != -1) { // 選択されているラジオボタンの取得 RadioButton radioButton = (RadioButton) findViewById(checkedId);// (Fragmentの場合は「getActivity().findViewById」にする) // ラジオボタンのテキストを取得 String text = radioButton.getText().toString(); Log.v("checked", text); } else { // 何も選択されていない場合の処理 }
参考サイト:
ラジオボタンで複数の選択肢から1つを選択させる / Getting Started « Tech Booster