2

スピナーの使用方法についてこのチュートリアルを見てきましたが、行き詰まっています。

現在、スピナーからアイテムを選択するとトーストが表示され、選択した国に緯度と経度を設定するメソッドを代わりに実行したいと考えています。

「場所を日本に設定」ボタンは、「SetLocationJapan」メソッドを呼び出すことで完全に機能します。このプロセスをスピナーに入れて、選択が行われるたびに緯度と経度が更新されるようにしたいだけです。

例: スピナーで日本が選択されているprotected void setLocationJapan() 場合 フランスが選択されているprotected void setLocationFrance() 場合に呼び出したい インドが選択されている場合に呼び出したいprotected void setLocationIndia()

要求されたコード:

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class SunriseSunset extends Activity implements OnClickListener {

    public Button getLocation;
    public Button setLocationJapan;
    public TextView LongCoord;
    public TextView LatCoord;
    public double longitude;
    public double latitude;
    public LocationManager lm;
    private Spinner spinner1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sunrisesunset);

        addListenerOnSpinnerItemSelection();

        findViewById(R.id.my_button).setOnClickListener(this);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
                new MyLocationListener());

        setLocationJapan = (Button) findViewById(R.id.SetLocationJapan);
        getLocation = (Button) findViewById(R.id.GetLocation);
        LongCoord = (TextView) findViewById(R.id.LongCoord);
        LatCoord = (TextView) findViewById(R.id.LatCoord);

        getLocation.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // When GetLocation button is clicked the showCurrentLocation
                // function is ran
                showCurrentLocation();
            }

        });

        setLocationJapan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // When SetLocation button is clicked the setCurrentLocation
                // function is ran
                setLocationJapan();
            }

        });
    }

    public void addListenerOnSpinnerItemSelection() {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
    }

    protected void setLocationJapan() {
        // TODO Auto-generated method stub
        LatCoord.setText("35.4112");
        LongCoord.setText("135.8337");
    }

    protected void setLocationFrance() {
        // TODO Auto-generated method stub
        LatCoord.setText("65.4112");
        LongCoord.setText("85.8337");
    }

    protected void setLocationIndia() {
        // TODO Auto-generated method stub
        LatCoord.setText("21.4112");
        LongCoord.setText("105.8337");
    }

    protected void showCurrentLocation() {
        // TODO Auto-generated method stub
        // This is called to find current location based on GPS data and sends
        // this to LongCoord and LatCoord TextViewsw
        Location location = lm
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }

    @Override
    public void onClick(View arg0) {
        Button b = (Button) findViewById(R.id.my_button);
        b.setClickable(false);
        new LongRunningGetIO().execute();
    }

    private class LongRunningGetIO extends AsyncTask<Void, Void, String> {

        protected String getASCIIContentFromEntity(HttpEntity entity)
                throws IllegalStateException, IOException {
            InputStream in = entity.getContent();
            StringBuffer out = new StringBuffer();
            int n = 1;
            while (n > 0) {
                byte[] b = new byte[4096];
                n = in.read(b);
                if (n > 0)
                    out.append(new String(b, 0, n));
            }
            return out.toString();
        }

        @Override
        protected String doInBackground(Void... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            // Finds todays date and adds that into the URL
            Calendar c = Calendar.getInstance();
            System.out.println("Current time => " + c.getTime());
            SimpleDateFormat df = new SimpleDateFormat("dd/MM");
            String formattedDate = df.format(c.getTime());

            String finalURL = "http://www.earthtools.org/sun/"
                    + LatCoord.getText().toString().trim() + "/"
                    + LongCoord.getText().toString().trim() + "/"
                    + formattedDate + "/99/0";
            HttpGet httpGet = new HttpGet(finalURL);
            String text = null;

            try {
                HttpResponse response = httpClient.execute(httpGet,
                        localContext);
                HttpEntity entity = response.getEntity();
                text = getASCIIContentFromEntity(entity);
            } catch (Exception e) {
                return e.getLocalizedMessage();
            }
            return text;
        }

        protected void onPostExecute(String results) {
            if (results != null) {
                try {

                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                            .newInstance();
                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                    InputSource s = new InputSource(new StringReader(results));
                    Document doc = dBuilder.parse(s);
                    doc.getDocumentElement().normalize();
                    TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
                    TextView tvSunset = (TextView) findViewById(R.id.Sunset);
                    tvSunrise.setText(doc.getElementsByTagName("sunrise")
                            .item(0).getTextContent());
                    tvSunset.setText(doc.getElementsByTagName("sunset").item(0)
                            .getTextContent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Button b = (Button) findViewById(R.id.my_button);
            b.setClickable(true);
        }
    }

    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }   
}

CustomOnItemSelectedListener.java

package richgrundy.learnphotography;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(), 
        "You have changed to : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
  }

}

レイアウト:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SunriseSunset" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:entries="@array/country_arrays"
        android:padding="10dp" />

    <LinearLayout
        android:id="@+id/LinearLayout02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Date:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/Date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Current Date"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/LinearLayout02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Location:"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

    <Button
        android:id="@+id/GetLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Find Current Location" />

    <Button
        android:id="@+id/SetLocationJapan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Set Location to Japan" />

    <LinearLayout
        android:id="@+id/LinearLayout02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/LatCoord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp" />

        <TextView
            android:id="@+id/LongCoord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp" />
    </LinearLayout>

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Calculate Sunrise/Sunset Time" />

    <TextView
        android:id="@+id/Sunrise"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00:00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/Sunset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00:00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

どんな助けでも大歓迎です、ありがとう!

setLocationJapan()クラス内で移動する必要があると確信してCustomOnItemSelectedListenerいますが、そこから先に進む方法がわかりません。

疑似コードの回答を好むので、可能であれば自分でこれを解決できます:)

4

1 に答える 1