2015-11-27 4 views
-1

В этом упражнении я получаю места поблизости и добавляю их в список. Я хотел также добавить телефонный номер места в список массива, как и другие данные, поэтому мне пришлось использовать запрос деталей места. Итак, я получаю все place_id для всех мест из списка arrayList и запускаю запрос, чтобы получить информацию (номер телефона). Проблема в классе «readFromGooglePlaceDetailsAPI», он идет в «», попробуйте »и гаснет, ничего не происходит, я не знаю почему !!! Я вижу только «IN TRY !!!» а затем «----» из println.Ничего не происходит в попытке

Является ли мой порядок неточным?

Где проблема и в чем заключается решение?

public class ListActivity extends Activity implements OnItemClickListener { 

public ArrayList<GetterSetter> myArrayList; 
ArrayList<GetterSetter> detailsArrayList; 
    ListView myList; 
    ProgressDialog dialog; 
    TextView nodata; 
    CustomAdapter adapter; 
    GetterSetter addValues; 
    GetterSetter addDetails; 
    private LocationManager locMan; 


@Override protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.list_view_activity); 

    if (!isNetworkAvailable()) { 
    Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!", 
    Toast.LENGTH_LONG).show(); 
    return; 
    } 

    myList = (ListView) findViewById(R.id.placesList); 

    placeSearch(); 


} 

    private boolean isNetworkAvailable() { 
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    return activeNetworkInfo != null; 
    } 

public void placeSearch() { 

//get location manager 
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
//get last location 
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
double lat = lastLoc.getLatitude(); 
double lng = lastLoc.getLongitude(); 

    dialog = ProgressDialog.show(this, "", "Please wait", true); 

//build places query string 
String placesSearchStr; 

placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" + 
     "json?location="+lat+","+lng+ 
     "&radius=1000&sensor=true" + 
     "&types="+ ServicesListActivity.types+ 
     "&key=My_KEY"; 

//execute query 
new readFromGooglePlaceAPI().execute(placesSearchStr); 

myList.setOnItemClickListener(this); 

    } 

public void detailsSearch() { 
    String detailsSearchStr; 

    //build places query string 
    for(int i=0; i < myArrayList.size(); i++){ 

    detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" + 
      "placeid=" + myArrayList.get(i).getPlace_id() + 
      "&key=My_KEY"; 

     Log.d("PlaceID:", myArrayList.get(i).getPlace_id()); 

    //execute query 
     new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr); 

    } 

} 

public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> { 

    @Override protected String doInBackground(String... param) { 
     return readJSON(param[0]); 
    } 

    protected void onPostExecute(String str) { 

     detailsArrayList = new ArrayList<GetterSetter>(); 

     String phoneNumber =" -NA-"; 
     try { 
      System.out.println("IN TRY !!!"); 

      JSONObject root = new JSONObject(str); 
      JSONArray results = root.getJSONArray("result"); 
      System.out.println("Before FOR !!!"); 

      for (int i = 0; i < results.length(); i++) { 

       System.out.println("IN FOR LOOP !!!"); 

       addDetails = new GetterSetter(); 

       JSONObject arrayItems = results.getJSONObject(i); 

       if(!arrayItems.isNull("formatted_phone_number")){ 
        phoneNumber = arrayItems.getString("formatted_phone_number"); 

        Log.d("Phone Number ", phoneNumber); 
       } 

       addDetails.setPhoneNumber(phoneNumber); 
       System.out.println("ADDED !!!"); 

       detailsArrayList.add(addDetails); 

       Log.d("Before", detailsArrayList.toString()); 

      } 
     } catch (Exception e) { 

     } 
     System.out 
       .println("------------------------------------------------------------------"); 
     Log.d("After:", detailsArrayList.toString()); 
     // nodata = (TextView) findViewById(R.id.nodata); 
     //nodata.setVisibility(View.GONE); 
     // adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList); 
     // myList.setAdapter(adapter); 
     //adapter.notifyDataSetChanged(); 
     // dialog.dismiss(); 


    } 

} 


public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> { 

    @Override protected String doInBackground(String... param) { 
    return readJSON(param[0]); 
} 

protected void onPostExecute(String str) { 
    myArrayList = new ArrayList<GetterSetter>(); 

    String rating=" -NA-"; 
    try { 

     JSONObject root = new JSONObject(str); 
     JSONArray results = root.getJSONArray("results"); 
     for (int i = 0; i < results.length(); i++) { 


      addValues = new GetterSetter(); 

      JSONObject arrayItems = results.getJSONObject(i); 
      JSONObject geometry = arrayItems.getJSONObject("geometry"); 
      JSONObject location = geometry.getJSONObject("location"); 
      //place ID for place details later 
      String placeID = arrayItems.getString("place_id").toString(); 

      if(!arrayItems.isNull("rating")){ 
       rating = arrayItems.getString("rating"); 
      } 
      addValues.setPlace_id(placeID); 
      addValues.setLat(location.getString("lat")); 
      addValues.setLon(location.getString("lng")); 
      addValues.setName(arrayItems.getString("name").toString()); 
      addValues.setRating(rating); 
      addValues.setVicinity(arrayItems.getString("vicinity").toString()); 

      myArrayList.add(addValues); 

      //Log.d("Before", myArrayList.toString()); 


     } 
    } catch (Exception e) { 

    } 
    // System.out 
    //   .println("############################################################################"); 
    // Log.d("After:", myArrayList.toString()); 
    nodata = (TextView) findViewById(R.id.nodata); 
    nodata.setVisibility(View.GONE); 
    adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList); 
    myList.setAdapter(adapter); 
    //adapter.notifyDataSetChanged(); 
    dialog.dismiss(); 

     detailsSearch(); 
} 

} 

public String readJSON(String URL) { 
    StringBuilder sb = new StringBuilder(); 
    HttpGet httpGet = new HttpGet(URL); 
    HttpClient client = new DefaultHttpClient(); 

    try { 
     HttpResponse response = client.execute(httpGet); 
     StatusLine statusLine = response.getStatusLine(); 
     if (statusLine.getStatusCode() == 200) { 
      HttpEntity entity = response.getEntity(); 
      InputStream content = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
      String line; 

      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 
     } else { 
      Log.e("JSON", "Couldn't find JSON file"); 
     } 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return sb.toString(); 
} 

@Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
    Intent details = new Intent(ListActivity.this, Details.class); 
    details.putExtra("name", myArrayList.get(arg2).getName()); 
    details.putExtra("rating", myArrayList.get(arg2).getRating()); 
    details.putExtra("vicinity", myArrayList.get(arg2).getVicinity()); 
    details.putExtra("lat", myArrayList.get(arg2).getLat()); 
    details.putExtra("lon", myArrayList.get(arg2).getLon()); 
    details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber()); 

    startActivity(details); 
} 

} 
+0

Вы проверили выходные данные журнала? Правильно ли readJSON заканчивается? – FlanschiFox

+0

Он хорошо подходит для ближайшего запроса – Lotus91

+0

Что такое журнал ошибок! плюс сделал код более читаемым и поддерживал стандарт кода. Например, имя класса начинается с капитала – Fay007

ответ

1

Обратите внимание, что функция getJSONArray() генерирует исключение, если отображение не удается. Например, я не могу найти массив JSON, который называется results.

Самое главное, что вы должны сделать в первую это:

изменение:

catch (Exception e) { 

} 

в

catch (Exception e) { 
    Log.e(YOUR_TAG, "Exception ..." , e); 
} 

Ваш попытка генерирует исключение, которое вы даже не журнал. Это может быть причиной того, что вы сбиты с толку.

+0

Эта строка вызывает проблему, результаты JSONArray = root.getJSONArray («results»); Вы правы! – Lotus91

+0

Рад это услышать. Ваш JSON просто ошибается. Наверное, мы закончили? Откройте новый вопрос, если у вас возникли дополнительные проблемы ?! – FlanschiFox

1
try{ 
    JSONObject jsonObject = new JSONObject(str); 
    if (jsonObject.has("results")) { 
     JSONArray jsonArray = jsonObject.getJSONArray("results"); 
     for (int i = 0; i < jsonArray.length(); i++) { 
     //your logic here 
     } 
    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+0

Это все равно вызовет исключение, если 'results' не относится к JSONArray. – FlanschiFox

Смежные вопросы