我正在使用两项活动。一个用于用户输入,另一个用于显示。 我想在第一个活动中过滤JSONArray作为用户输入,我使用Intent进行此操作。 这是我的第一个活动。
public class PlaceFinder extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.place_finder);
}
public void onClickplaceFinder(View view) {
EditText UserPlace = (EditText)findViewById(R.id.editText);
String UserPlaceText = UserPlace.getText().toString();
Intent intent = new Intent(PlaceFinder.this , MainActivity.);
intent.putExtra("place", UserPlaceText);
intent.putExtra(MainActivity.EXTRA_MESSAGE,UserPlaceText);
startActivity(intent);
}
**这里是我的第二个活动JSON解析**
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "place";
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://api.myjson.com/bins/1an69r";
ArrayList<HashMap<String, String>> placeList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
Intent intent = getIntent();
String UserPlaceText = intent.getStringExtra(EXTRA_MESSAGE);
TextView UserPlace = (TextView)findViewById(R.id.editText);
setContentView(R.layout.activity_main);
placeList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetPlace().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetPlace extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Hope This To Work");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray places = jsonObj.getJSONArray("places");
// looping through All Contacts
for (int i = 0; i < places.length(); i++) {
JSONObject c = places.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String city = c.getString("city");
String needle = c.getString("needle");
String lat = c.getString("lat");
String lng = c.getString("lng");
String rating = c.getString("rating");
// Phone node is JSON Object
// tmp hash map for single contact
HashMap<String, String> place = new HashMap<>();
// adding each child node to HashMap key => value
place.put("id", id);
place.put("name", name);
place.put("city", city);
place.put("needle", needle );
place.put("lat",lat);
place.put("lng",lng);
place.put("rating",rating);
// adding contact to place list
placeList.add(place);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, placeList,
R.layout.list_item, new String[]{"name", "city",
"lat","lng","needle","rating"}, new int[]{R.id.name,
R.id.city, R.id.lat,R.id.lng,R.id.needle,R.id.rating});
lv.setAdapter(adapter);
}
}
登录CAT
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8600', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1425)
W/System: ClassLoader referenced unknown path: /data/app/tester.battleship-2/lib/arm
I/InstantRun: Instant Run Runtime started. Android package is tester.battleship, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/tester.battleship-2/lib/arm
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: endAllStagingAnimators on 0xa1f06980 (RippleDrawable) with handle 0xa0ebf400
E/MainActivity: Response from url: {"mumbai":[{"id":1,"name":"place1","city":null,"needle":null,"lat":null,"lng":null,"rating":null,"created_at":"2017-06-26T02:57:43.617Z","updated_at":"2017-06-26T02:57:43.617Z"},{"id":2,"name":null,"city":"ranchi","needle":null,"lat":null,"lng":null,"rating":null,"created_at":"2017-06-26T02:57:43.763Z","updated_at":"2017-06-26T02:57:43.763Z"},{"id":3,"name":null,"city":null,"needle":"07301230AP","lat":null,"lng":null,"rating":null,"created_at":"2017-06-26T02:57:43.850Z","updated_at":"2017-06-26T02:57:43.850Z"},{"id":4,"name":null,"city":null,"needle":null,"lat":23.14,"lng":null,"rating":null,"created_at":"2017-06-26T02:57:43.953Z","updated_at":"2017-06-26T02:57:43.953Z"},{"id":5,"name":null,"city":null,"needle":null,"lat":null,"lng":85.3,"rating":null,"created_at":"2017-06-26T02:57:44.037Z","updated_at":"2017-06-26T02:57:44.037Z"},{"id":6,"name":null,"city":null,"needle":null,"lat":null,"lng":null,"rating":4,"created_at":"2017-06-26T02:57:44.129Z","updated_at":"2017-06-26T02:57:44.129Z"},{"id":7,"name":"place1","city":"ranchi","needle":"07301230AP","lat":23.14,"lng":85.3,"rating":4,"created_at":"2017-06-26T03:00:11.502Z","updated_at":"2017-06-26T03:00:11.502Z"},{"id":8,"name":"place1","city":"ranchi","needle":"07301230AP","lat":23.14,"lng":85.3,"rating":4,"created_at":"2017-06-26T03:01:44.261Z","updated_at":"2017-06-26T03:01:44.261Z"},{"id":9,"name":"place1","city":"ranchi","needle":"07301230AP","lat":23.14,"lng":85.3,"rating":4,"created_at":"2017-06-26T03:03:19.061Z","updated_at":"2017-06-26T03:03:19.061Z"},{"id":10,"name":"place2","city":"ranchi","needle":"07301430AP","lat":23.34,"lng":85.9,"rating":4,"created_at":"2017-06-26T03:03:19.183Z","updated_at":"2017-06-26T03:03:19.183Z"}],"places":[{"id":11,"name":"place3","city":"ranchi","needle":"09000130AP","lat":23.44,"lng":82.4,"rating":4,"created_at":"2017-06-26T03:03:19.283Z","updated_at":"2017-06-26T03:03:19.283Z"},{"id":12,"name":"place4","city":"ranchi","needle":"11301830AP","lat":23.54,"lng":87.3,"rating":4,"created_at":"2017-06-26T03:03:19.371Z","updated_at":"2017-06-26T03:03:19.371Z"},{"id":13,"name":"place5","city":"mumbai","needle":"10301930AP","lat":123.64,"lng":185.8,"rating":4,"created_at":"2017-06-26T03:03:19.459Z","updated_at":"2017-06-26T03:03:19.459Z"},{"id":14,"name":"place6","city":"patna","needle":"07301260AP","lat":173.34,"lng":485.3,"rating":4,"created_at":"2017-06-26T03:03:19.550Z","updated_at":"2017-06-26T03:03:19.550Z"},{"id":15,"name":"place7","city":"delhi","needle":"07301240AP","lat":383.34,"lng":485.3,"rating":4,"created_at":"2017-06-26T03:03:19.638Z","updated_at":"2017-06-26T03:03:19.638Z"}]}
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tester.battleship, PID: 7622
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at tester.battleship.MainActivity$GetPlace.onPostExecute(MainActivity.java:161)
at tester.battleship.MainActivity$GetPlace.onPostExecute(MainActivity.java:59)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 7622 SIG: 9
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
有什么办法吗? 谢谢。
答案 0 :(得分:0)
首先,我强烈建议您不要使用asyncTasks
进行网络通话。尝试使用像Retrofit这样的库。
使用此方法,您可以在将其传递给适配器之前在onPostExecute中查找列表,并根据您作为Intent传递的字符串对其进行过滤。将字符串存储为字段,以便您可以在类中访问它。然后创建一个名为filterList()
的方法,返回ArrayList<Places>
。
该方法应该迭代列表并比较places对象的字段(我不知道你要比较哪些字段,因为你没有说出来)。然后只需删除不相关的项目并返回修改后的列表。然后执行您已经执行的操作:关闭对话框并将已过滤的列表传递给适配器。