2016-07-14 7 views
0

リストビューの項目を次のコードを使用してリストビューでクリックすると、オートコンプリートテキストビューに表示されます。リストビューからオートコンプリートテキストビューに選択したアイテムをどのように取るか

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, AdapterView.OnItemClickListener { 

    LocationRequest mLocationRequest; 
    GoogleApiClient mGoogleApiClient; 


GoogleMap mMap; 
SupportMapFragment mFragment; 
Marker CurrentMarker,FindMarker; 
Location mLastLocation; 


CustomAutoCompleteTextView atvPlaces = null; 
DownloadTask placesDownloadTask; 
DownloadTask placeDetailsDownloadTask; 
ParserTask placesParserTask; 
ParserTask placeDetailsParserTask; 

final int PLACES=0; 
final int PLACES_DETAILS=1; 
LatLng latLng; 
ListView lv; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     checkLocationPermission(); 
    } 

    mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
    mFragment.getMapAsync(this); 


// Getting a reference to the AutoCompleteTextView 
    atvPlaces = (CustomAutoCompleteTextView) findViewById(R.id.atv_places); 
    atvPlaces.setThreshold(1); 

    // Adding textchange listener 
    atvPlaces.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      // Creating a DownloadTask to download Google Places matching "s" 
      placesDownloadTask = new DownloadTask(PLACES); 

      // Getting url to the Google Places Autocomplete api 
      String url = getAutoCompleteUrl(s.toString()); 

      // Start downloading Google Places 
      // This causes to execute doInBackground() of DownloadTask class 
      placesDownloadTask.execute(url); 


     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
             int after) { 
      // TODO Auto-generated method stub 
     } 

     @Override 
     public void afterTextChanged(Editable s) { 
      // TODO Auto-generated method stub 
     } 
    }); 



    lv = (ListView) findViewById(R.id.list); 

    lv.setOnItemClickListener(this); 


} 

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
public boolean checkLocationPermission() { 
    if(ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED){ 

     if(ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_FINE_LOCATION)){ 

      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     }else { 
      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     } 
     return false; 
    }else{ 
     return true; 
    } 

} 


private String getAutoCompleteUrl(String place){ 

    // Obtain browser key from https://code.google.com/apis/console 
    String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog"; 

    // place to be be searched 
    String input = "input="+place; 

    // place type to be searched 
    String types = "types=geocode"; 

    // Sensor enabled 
    String sensor = "sensor=false"; 

    // Building the parameters to the web service 
    String parameters = input+"&"+types+"&"+sensor+"&"+key; 

    // Output format 
    String output = "json"; 

    // Building the url to the web service 
    String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters; 

    return url; 
} 

private String getPlaceDetailsUrl(String ref){ 

    // Obtain browser key from https://code.google.com/apis/console 
    String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog"; 

    // reference of place 
    String reference = "reference="+ref; 

    // Sensor enabled 
    String sensor = "sensor=false"; 

    // Building the parameters to the web service 
    String parameters = reference+"&"+sensor+"&"+key; 

    // Output format 
    String output = "json"; 

    // Building the url to the web service 
    String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters; 

    return url; 
} 

/** A method to download json data from url */ 
private String downloadUrl(String strUrl) throws IOException{ 
    String data = ""; 
    InputStream iStream = null; 
    HttpURLConnection urlConnection = null; 
    try{ 
     URL url = new URL(strUrl); 

     // Creating an http connection to communicate with url 
     urlConnection = (HttpURLConnection) url.openConnection(); 

     // Connecting to url 
     urlConnection.connect(); 

     // Reading data from url 
     iStream = urlConnection.getInputStream(); 

     BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 

     StringBuffer sb = new StringBuffer(); 

     String line = ""; 
     while((line = br.readLine()) != null){ 
      sb.append(line); 
     } 

     data = sb.toString(); 

     br.close(); 

    }catch(Exception e){ 
     //Log.d("Exception while downloading url", e.toString()); 
    }finally{ 
     iStream.close(); 
     urlConnection.disconnect(); 
    } 
    return data; 
} 


@Override 
public void onConnected(Bundle bundle) { 

    mLocationRequest = new LocationRequest(); 
    // mLocationRequest.setInterval(1000); 
    // mLocationRequest.setFastestInterval(1000); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 

    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){ 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this); 
    } 

} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onLocationChanged(Location location) { 
    mLastLocation = location; 
    if(CurrentMarker != null){ 
     CurrentMarker.remove(); 
    } 

    LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude()); 
    MarkerOptions markerOption = new MarkerOptions(); 
    markerOption.position(latLng); 
    markerOption.title("Current Position"); 
    markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
    CurrentMarker = mMap.addMarker(markerOption); 

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(13)); 



    if(mGoogleApiClient != null){ 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this); 
    } 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 


    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       ==PackageManager.PERMISSION_GRANTED){ 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 

     } 
    } 
    else { 
     buildGoogleApiClient(); 
     mMap.setMyLocationEnabled(true); 
    } 

} 

protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResult){ 
    switch (requestCode){ 
     case MY_PERMISSIONS_REQUEST_LOCATION: { 

      if(grantResult.length > 0 
        && grantResult[0] == PackageManager.PERMISSION_GRANTED){ 
       if(ContextCompat.checkSelfPermission(this, 
         Manifest.permission.ACCESS_FINE_LOCATION) 
         == PackageManager.PERMISSION_GRANTED) { 
        if(mGoogleApiClient == null){ 
         buildGoogleApiClient(); 
        } 
        mMap.setMyLocationEnabled(true); 
       } 

      }else { 
       Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show(); 
      } 
      return; 
     } 

    } 
} 

@Override 
public void onItemClick(AdapterView adapterView, View view, int position, long id) { 

    String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString(); 
    Toast.makeText(this,str, Toast.LENGTH_SHORT).show(); 

} 


private class DownloadTask extends AsyncTask<String, Void, String> { 
    private int downloadType = 0; 

    // Constructor 
    public DownloadTask(int type) { 
     this.downloadType = type; 
    } 

    @Override 
    protected String doInBackground(String... url) { 
     // For storing data from web service 
     String data = ""; 

     try { 
      // Fetching the data from web service 
      data = downloadUrl(url[0]); 
     } catch (Exception e) { 
      Log.d("Background Task", e.toString()); 
     } 
     return data; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     switch (downloadType) { 
      case PLACES: 
       // Creating ParserTask for parsing Google Places 
       placesParserTask = new ParserTask(PLACES); 

       // Start parsing google places json data 
       // This causes to execute doInBackground() of ParserTask class 
       placesParserTask.execute(result); 


       break; 

      case PLACES_DETAILS: 
       // Creating ParserTask for parsing Google Places 
       placeDetailsParserTask = new ParserTask(PLACES_DETAILS); 

       // Starting Parsing the JSON string 
       // This causes to execute doInBackground() of ParserTask class 
       placeDetailsParserTask.execute(result); 
     } 
    } 
} 

/** 
* A class to parse the Google Places in JSON format 
*/ 
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> { 

    int parserType = 0; 

    public ParserTask(int type) { 
     this.parserType = type; 
    } 

    @Override 
    protected List<HashMap<String, String>> doInBackground(String... jsonData) { 

     JSONObject jObject; 
     List<HashMap<String, String>> list = null; 

     try { 
      jObject = new JSONObject(jsonData[0]); 

      switch (parserType) { 
       case PLACES: 
        PlaceJSONParser placeJsonParser = new PlaceJSONParser(); 
        // Getting the parsed data as a List construct 
        list = placeJsonParser.parse(jObject); 
        break; 
       case PLACES_DETAILS: 
        PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser(); 
        // Getting the parsed data as a List construct 
        list = placeDetailsJsonParser.parse(jObject); 
      } 

     } catch (Exception e) { 
      Log.d("Exception", e.toString()); 
     } 
     return list; 
    } 

    @Override 
    protected void onPostExecute(List<HashMap<String, String>> result) { 

     switch (parserType) { 
      case PLACES: 


       String[] from = new String[]{"description"}; 
       int[] to = new int[]{R.id.place_name}; 

       // Creating a SimpleAdapter for the AutoCompleteTextView 
       //SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to); 

       // Setting the adapter 
       // atvPlaces.setAdapter(lv); 

       // list adapter 
       ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.list_item,from,to); 
       // Adding data into listview 
       lv.setAdapter(adapter); 


       break; 
      case PLACES_DETAILS: 
       String location = atvPlaces.getText().toString(); 
       if (location != null && !location.equals("")) { 
        new GeocoderTask().execute(location); 

       } 

       break; 
     } 
    } 


} 

private class GeocoderTask extends AsyncTask<String, Void, List<Address>> { 

    @Override 
    protected List<Address> doInBackground(String... locationName) { 
     // TODO Auto-generated method stub 

     Geocoder geocoder = new Geocoder(getBaseContext()); 
     List<Address> addresses = null; 

     try { 
      // Getting a maximum of 3 Address that matches the input text 
      addresses = geocoder.getFromLocationName(locationName[0], 3); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return addresses; 
    } 

    protected void onPostExecute(List<Address> addresses) { 
     if(addresses==null || addresses.size()==0){ 
      Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show(); 
     } 
     for(int i=0;i<addresses.size();i++){ 
      Address address = (Address)addresses.get(i); 
      latLng = new LatLng(address.getLatitude(), address.getLongitude()); 
      String addressText = String.format("%s, %s", 
        address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", 
        address.getCountryName()); 
      MarkerOptions markerOptions = new MarkerOptions(); 
      markerOptions.position(latLng); 
      markerOptions.title("Find Location"); 
      markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); 
      FindMarker = mMap.addMarker(markerOptions); 

      CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build(); 
      mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 

     } 

    } 

} 

} 

私はその項目をクリックすると、リストビューからautocompleteTextviewで選択した項目を表示したいです。私のソースコードを使って教えてください。

答えて

0
@Override 
    public void onItemClick(AdapterView adapterView, View view, int position, long id) { 

     String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString(); 
     Toast.makeText(this,str, Toast.LENGTH_SHORT).show(); 
     atvPlaces.setText(str); 
     atvPlaces.dismissDropDown(); 



    } 
+0

okですが、動作していますが、クラッシュした後で、データがautocompletetextviewに表示されます。検索が開始されない – Rishabh

+0

java.lang.NullPointerException:ヌルオブジェクトリファレンスでインタフェースメソッド 'int java.util.List.size()'を呼び出そうとしました。 android.widget.SimpleAdapter.getCount(SimpleAdapter.java:100) at android.widget.ListView.setAdapter(ListView.java:491) at com.test.MainActivity $ ParserTask.onPostExecute(MainActivity.java:521) - このエラーが発生しました – Rishabh

+0

解決方法を教えてください – Rishabh

0

Plsこのコードをチェックして、変更しました。

String mSelectedItem; 


    mListView.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int ClikedPosition, long id) { 
        //Getting clicked item from list view 
       mSelectedItem=adapter.getItem(ClikedPosition); 

//Setting to auto complete text view 
       mAutoCompleteTextView.setText(mSelectedItem); 


      } 
     }); 
+0

新しいデータを動的に送信したい場合、カスタムアダプタクラスに1つの関数(例:refreshAdapter(Arraylistリスト))を作成し、そのデータを送信してくださいその関数を呼び出してnotifyDataSetChang ed()。 – Siva

+0

私はリストからautocompletetextviewに行きたいです。 – Rishabh

+0

リストビューまたは複数のアイテムから選択した1つのアイテムのみを取得しますか? – Siva

関連する問題