Пользовательский просмотр списка с кнопкой и JSON
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Patient> patientItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Patient> movieItems) {
this.activity = activity;
this.patientItems = movieItems;
}
@Override
public int getCount() {
return patientItems.size();
}
@Override
public Object getItem(int location) {
return patientItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
Button viewBtn = (Button)convertView.findViewById(R.id.view_btn);
// getting data for the row
Patient m = patientItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
viewBtn.setTag(position);
viewBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int tag = (Integer) v.getTag();
switch (tag) {
case 0:
TextView c = (TextView) v.findViewById(R.id.title);
String item = c.getText().toString();
Log.d("id", item);
//Toast.makeText(PatientList.this, "row " + item + " was pressed", Toast.LENGTH_LONG).show();
break;
case 1:
break;
}
}
});
return convertView;
}
}
PatientList.java
public class PatientList extends FragmentActivity implements SwipeRefreshLayout.OnRefreshListener {
// Log tag
private static final String TAG = PatientList.class.getSimpleName();
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
// Movies json url
private static final String url = "http://192.168.0.102/test/apps.php";
private ProgressDialog pDialog;
private List<Patient> patientList = new ArrayList<Patient>();
private ListView listView;
private CustomListAdapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patientlist_listview);
listView = (ListView) findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
adapter = new CustomListAdapter(this, patientList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#00BBD3")));
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchPatients();
}
}
);
listView.setAdapter(adapter);
// Click event for single list row
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(PatientList.this, "row " + position + " was pressed", Toast.LENGTH_LONG).show();
switch (position) {
case 0:
TextView c = (TextView) view.findViewById(R.id.title);
String item = c.getText().toString();
Log.d("id", item);
break;
case 1:
break;
}
}
});
}
/**
* This method is called when swipe refresh is pulled down
*/
@Override
public void onRefresh() {
fetchPatients();
}
/**
* Fetching movies json by making http call
*/
private void fetchPatients() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
Log.d("id", "hi") ;
// Parsing json
// reset the list
patientList.clear();
adapter.notifyDataSetChanged();
for (int i = 0; i < response.length();i++) {
try {
Log.d("id","hi1") ;
Log.d("i","i:"+i);
Patient patient = new Patient();
Log.d("length", "length:" + response.length());
JSONObject objid= response.getJSONObject(i);
//get id
patient.setTitle(objid.getString("id"));
JSONObject objimage= response.getJSONObject(++i);
patient.setThumbnailUrl(objimage.getString("image"));
// adding movie to movies array
if(i%2==1)
patientList.add(patient);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Patient.java
public class Patient {
private String title;
public Patient() {
}
public Patient(String name) {
this.title = name;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
}
Сообщения об ошибках
01-11 03:16:30.607 25561-25561/? I/art: Late-enabling -Xcheck:jni
01-11 03:16:30.636 25561-25569/? I/art: Debugger is no longer active
01-11 03:16:30.793 25561-25582/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-11 03:16:30.814 25561-25561/? D/Atlas: Validating map...
01-11 03:16:30.907 25561-25582/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
01-11 03:16:30.910 25561-25582/? D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
01-11 03:16:30.934 25561-25582/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
01-11 03:16:30.985 25561-25582/? I/OpenGLRenderer: Initialized EGL, version 1.4
01-11 03:16:31.037 25561-25582/? D/OpenGLRenderer: Enabling debug mode 0
01-11 03:16:31.069 25561-25582/? W/EGL_emulation: eglSurfaceAttrib not implemented
01-11 03:16:31.069 25561-25582/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3fcf2e0, error=EGL_SUCCESS
01-11 03:16:31.193 25561-25582/? W/EGL_emulation: eglSurfaceAttrib not implemented
01-11 03:16:31.193 25561-25582/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3fcf320, error=EGL_SUCCESS
01-11 03:16:32.099 25561-25561/info.androidhive.customlistviewvolley D/PatientList: [{"id":"g"},{"image":"http:\/\/192.168.56.1\/test\/1.png"},{"id":"xd"},{"image":"http:\/\/192.168.56.1\/test\/2.png"},{"id":"hallo"},{"image":"http:\/\/192.168.56.1\/test\/2.png"}]
01-11 03:16:32.134 25561-25561/info.androidhive.customlistviewvolley D/id: hi
01-11 03:16:32.134 25561-25561/info.androidhive.customlistviewvolley D/id: hi1
01-11 03:16:32.135 25561-25561/info.androidhive.customlistviewvolley D/i: i:0
01-11 03:16:32.135 25561-25561/info.androidhive.customlistviewvolley D/length: length:6
01-11 03:16:32.136 25561-25561/info.androidhive.customlistviewvolley D/id: hi1
01-11 03:16:32.136 25561-25561/info.androidhive.customlistviewvolley D/i: i:2
01-11 03:16:32.136 25561-25561/info.androidhive.customlistviewvolley D/length: length:6
01-11 03:16:32.136 25561-25561/info.androidhive.customlistviewvolley D/id: hi1
01-11 03:16:32.136 25561-25561/info.androidhive.customlistviewvolley D/i: i:4
01-11 03:16:32.136 25561-25561/info.androidhive.customlistviewvolley D/length: length:6
01-11 03:16:32.347 25561-25569/info.androidhive.customlistviewvolley W/art: Suspending all threads took: 5.607ms
01-11 03:16:32.556 25561-25574/info.androidhive.customlistviewvolley I/art: Background partial concurrent mark sweep GC freed 707(71KB) AllocSpace objects, 1(81KB) LOS objects, 39% free, 2MB/3MB, paused 1.361ms total 130.175ms
01-11 03:16:38.118 25561-25561/info.androidhive.customlistviewvolley D/AndroidRuntime: Shutting down VM
01-11 03:16:38.118 25561-25561/info.androidhive.customlistviewvolley E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.customlistviewvolley, PID: 25561
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at info.androidhive.customlistviewvolley.adater.CustomListAdapter$1.onClick(CustomListAdapter.java:83)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
01-11 03:17:02.358 25561-25561/? I/Process: Sending signal. PID: 25561 SIG: 9
Из сообщений об ошибках я знал, что он получил данные, которые я хочу, но я не могу получить данные из заголовка.
Я также проверил тег. Нажатие на кнопку первого ряда возвращает число ноль.
switch (tag) {
case 0:
TextView c = (TextView) v.findViewById(R.id.title);
String item = c.getText().toString();
Log.d("id", item);
//Toast.makeText(PatientList.this, "row " + item + " was pressed", Toast.LENGTH_LONG).show();
break;
Строка с кодом ошибки
String item = c.getText().toString();
Но я не могу получить строковый элемент с помощью c.getText(). ToString();. Как я могу изменить код, чтобы получить строку textview. Пожалуйста, дайте мне помощь. Спасибо.
1 ответ
Решение
Пожалуйста, попробуйте это, я думаю, что это работает, во-первых, вы заменяете прослушиватель кликов viewBtn на viewBtn.setOnClickListener(new OnItemClickListener(position)); затем поместите код в свой класс адаптера
private class OnItemClickListener implements View.OnClickListener {
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
@Override
public void onClick(View arg0) {
Patient p=patientItems.get(mPosition);
String Title=p.getTitle();
Log.d("Title at row"+mPosition,Title);
}
}