我有一个项目,我需要从JSON
解析一些Google Places API
,但我的List
获取空值或根本没有值。因此,在我MyActivity.java
方法的onPostExecute
中,当我尝试以下操作时,它不会解析值并返回它们。它是在JSONParser
类中创建对象但是没有在我的onPostExecute方法中获取它们?
placeList = JSONParser.parseFeed(result);
这是我的代码:
public class MyActivity extends Activity {
// create some references for ui elements
EditText urlText;
TextView textView;
ProgressBar pb;
// create a reference to the list's needed for data
List<MyTask> tasks;
List<Places> placeList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// get my ui elements by id
urlText = (EditText) findViewById(R.id.myUrl);
textView = (TextView) findViewById(R.id.myText);
pb = (ProgressBar) findViewById(R.id.progressBar);
// set the progress bar to invisible
pb.setVisibility(View.INVISIBLE);
//initiate my tasks
tasks = new ArrayList<>();
// make text view scrollable
textView.setMovementMethod(new ScrollingMovementMethod());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
// the method for when the button is clicked
public void myClick(View view) {
// create a string to grab the text of the edit text
String myString = urlText.getText().toString();
// replace the spaces with + to encode into the url
String encodedString = myString.replace(" ", "+");
//check to see if online and if so continue to get the JSON data if not toast a message telling the user no connection
if (isOnline()) {
requestData("https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + encodedString + "&key=AIzaSyB9iOw6wF4FwbOdUTZYiU_MxsbfWM5iMOI");
} else Toast.makeText(this, "Network isn't available", Toast.LENGTH_SHORT).show();
}
// method to update th ui
protected void updateDisplay() {
if (placeList != null) {
for (Places place : placeList) {
textView.append(place.getName());
}
}
}
// method to check internet connectivity
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
// method to get the data from ASYNC task
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
// Async task method to do network action in
private class MyTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
if (tasks.size() == 0) {
// set the progress bar to visible while Async task is running
pb.setVisibility(View.VISIBLE);
}
// add this to the task
tasks.add(this);
}
@Override
protected String doInBackground(String... params) {
return HttpManager.getData(params[0]);
}
@Override
protected void onPostExecute(String result) {
placeList = JSONParser.parseFeed(result);
Log.v("message:", String.valueOf(placeList));
updateDisplay();
tasks.remove(this);
if (tasks.size() == 0) {
// remove progress bar visibility from ui
pb.setVisibility(View.INVISIBLE);
}
}
@Override
protected void onProgressUpdate(String... values) {
//updateDisplay(values[0]);
}
}
}
public class JSONParser {
public static List<Places> parseFeed(String content) {
JSONObject myObj;
try {
myObj = new JSONObject(content);
JSONArray result = myObj.getJSONArray("results");
List<Places> placeList = new ArrayList<>();
for (int i = 0; i <= result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
Places place = new Places();
place.setName(obj.getString("name"));
// place.setFormatted_address(obj.getString("formatted_address"));
// place.setTypes(obj.getString("types"));
//place.setPhotos(obj.getString("photos"));
placeList.add(place);
}
return placeList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
public class Places {
private String pName;
private String pTypes;
private String pFormatted_address;
private String pPhotos;
public Places(){
pName ="";
pTypes ="";
pFormatted_address = "";
pPhotos="";
}
public Places (String _name, String _types, String _formatted_address, String _photos){
pName = _name;
pTypes =_types;
pFormatted_address = _formatted_address;
pPhotos = _photos;
}
public String getName() {
return pName;
}
public void setName(String name) {
pName = name;
}
public String getTypes() {
return pTypes;
}
public void setTypes(String types) {
pTypes= types;
}
public String getFormatted_address() {
return pFormatted_address;
}
public void setFormatted_address(String formatted_address) {
pFormatted_address=formatted_address;
}
public String getPhotos() {
return pPhotos;
}
public void setPhotos(String photos) {
pPhotos= photos;
}
}
<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MyActivity">
<EditText
android:id="@+id/myUrl"
android:inputType="textUri"
android:hint="@string/hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/myBUtton"
android:text="@string/enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClick" />
<TextView
android:id="@+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/image_view"
android:contentDescription="@string/hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_gravity="center_horizontal" />
</LinearLayout>
{
"html_attributions": [],
"results": [
{
"formatted_address": "Los Angeles, CA, USA",
"geometry": {
"location": {
"lat": 34.0522342,
"lng": -118.2436849
},
"viewport": {
"northeast": {
"lat": 34.3373061,
"lng": -118.1552891
},
"southwest": {
"lat": 33.7036917,
"lng": -118.6681759
}
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id": "7f7b7d8118ae8db8ed3f541159ac928c484d12ad",
"name": "Los Angeles",
"place_id": "ChIJE9on3F3HwoAR9AhGJW_fL-I",
"reference": "CoQBfwAAADOao2DI1Kxx7JS6g1utfzjgmiioj3ZoGgn26YmDJSlpkz9sZBuRMdUkytjNTMrK8isWwhnpuJ7EyVBhL0tXiFz-yS4qizi7eeA7olH5WNZude3IYd9iCq_MrigWxqop0_WsSaR9qU57wG8VTQzn7TQHEURmsC5ZARkjGfVk-unJEhARVD57imH0qkFsJCHx7RfbGhST3GV5RcklBl_-9kjAaLZ3KuNY5A",
"types": [
"locality",
"political"
]
}
],
"status": "OK"
}
答案 0 :(得分:1)
我认为你正在解析一个比你想要的更多的对象,这将抛出异常并返回null
:
// replace <= with just <
for (int i = 0; i <= result.length(); i++) {
// (...)
}