这可能是一个facepalm但我已经搜索了一个多星期了。
我在ListFragment中使用了自定义ArrayAdapter。一旦我在listview上设置了adapter它会抛出一个NPE,但我无法弄清楚为什么我的适配器没有返回任何东西。
JobAttachedTasks.java
package com.calnetwork;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import library.com.calnetwork.JSONParser;
import library.com.calnetwork.TaskAttachedItemAdapter;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class JobAttachedTasks extends ListFragment {
public JobAttachedTasks() {}
// Progress Dialog
private ProgressDialog pDialog;
public String jobID, taskID;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String TAG_JOB_JOBID = "jobID";
private static final String TAG_JOB_TASKID = "taskID";
private static final String TAG_JOB_TASKID_TITLE = "taskTitle";
private static final String TAG_JOB_INSTRUMENT_NAME = "instrumentName";
private static final String TAG_JOB_TASK_TYPE = "taskType";
private static final String TAG_SUCCESS = "success";
public JSONArray tasks = null;
public ListView lv;
public Button options;
public ArrayList<HashMap<String, String>> taskList = new ArrayList<HashMap<String, String>>();
public TaskAttachedItemAdapter myAdapter = null;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// URL to get job details
private static final String display_attached_tasks_url = "http://com.tradeport.on.ca/view_tasks_attached_to_job.php";
// URL to remove selected task
private static final String remove_task_url = "http://com.tradeport.on.ca/delete_single_attached_task.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.job_attached_task, container, false);
getActivity().getActionBar().setTitle("Edit Job Details");
getActivity().getActionBar().setHomeButtonEnabled(true);
Intent i = getActivity().getIntent();
jobID = i.getStringExtra("jobID");
taskList = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
myAdapter = new TaskAttachedItemAdapter(getActivity(), R.layout.list_job_attached_item, taskList);
lv.setAdapter(myAdapter);
lv.setOnItemLongClickListener(null);
registerForContextMenu(lv);
new LoadAllTasks().execute();
return rootView;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
getActivity().onBackPressed();
return true;
}
class LoadAllTasks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading attached tasks. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* @return
* */
protected String doInBackground(String... args) {
// Building Parameters
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("USER_SESSION", 0);
String session_username = pref.getString("username", null);
String session_key = pref.getString("key", null);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", "view_attached_tasks"));
params.add(new BasicNameValuePair("username", session_username));
params.add(new BasicNameValuePair("key", session_key ));
params.add(new BasicNameValuePair("jobID", jobID));
Log.d("task query params: ", params.toString());
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(display_attached_tasks_url, "POST", params);
// Check your log cat for JSON reponse
Log.d("All tasks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of users
tasks = json.getJSONArray("tasks");
Log.d("Single Attached Tasks Details", tasks.toString());
// looping through All users
for (int i = 0; i < tasks.length(); i++) {
JSONObject c = tasks.getJSONObject(i);
// Storing each json item in variable
String taskID = c.getString(TAG_JOB_TASKID);
String instrumentName = c.getString(TAG_JOB_INSTRUMENT_NAME);
String taskType = c.getString(TAG_JOB_TASK_TYPE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_JOB_TASKID, taskID);
map.put(TAG_JOB_JOBID, jobID);
map.put(TAG_JOB_TASKID_TITLE, "Task ID : "+taskID);
map.put(TAG_JOB_INSTRUMENT_NAME, instrumentName);
map.put(TAG_JOB_TASK_TYPE, taskType);
// adding HashList to ArrayList
taskList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public void onPostExecute(String args) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
Log.d("taskList", taskList.toString());
myAdapter = new TaskAttachedItemAdapter(getActivity(), R.layout.list_job_attached_item, taskList);
lv.setAdapter(myAdapter);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, 0, 0, "Task Details");
menu.add(0, 1, 0,"Remove Task");
return;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
taskID = ((TextView) info.targetView.findViewById(R.id.taskID)).getText().toString();
int menuPosition = item.getItemId();
Object itemIndex = taskList.get(menuPosition);
if(item.getTitle().equals("Task Details")) {
Intent i = new Intent(getActivity().getApplicationContext(), Tasks.class);
i.putExtra("taskID", taskID);
startActivity(i);
} else if(item.getTitle().equals("Remove Task")) {
taskList.remove(itemIndex);
myAdapter.notifyDataSetChanged();
}
return true;
};
class DeleteAttachedTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Deleting User ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
SharedPreferences pref = getActivity().getSharedPreferences("USER_SESSION", 0);
String session_username = pref.getString("username", null);
String session_key = pref.getString("key", null);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", "delete_single_attached_task"));
params.add(new BasicNameValuePair("taskID", taskID));
params.add(new BasicNameValuePair("jobID", String.valueOf(jobID)));
params.add(new BasicNameValuePair("session_username", session_username));
params.add(new BasicNameValuePair("session_key", session_key));
Log.d("delete params", String.valueOf(params));
JSONObject json = jsonParser.makeHttpRequest(remove_task_url, "POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product uupdated
pDialog.dismiss();
Toast.makeText(getActivity(), "Task Removed Successfully",Toast.LENGTH_SHORT).show();
}
}
}
TaskAttachedAdapter.java
package library.com.calnetwork;
import java.util.ArrayList;
import java.util.HashMap;
import com.calnetwork.R;
import android.content.ClipData.Item;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TaskAttachedItemAdapter extends ArrayAdapter<String> {
public static LayoutInflater inflater = null;
public ArrayList<HashMap<String, String>> taskList;
public String jobId;
public Context context;
public int layoutResourceId;
static class ViewHolder {
TextView jid;
TextView tid;
TextView tidt;
TextView ti;
TextView tt;
}
public TaskAttachedItemAdapter(Context context, int layoutResourceId){
super(context, layoutResourceId);
this.context = context;
Log.d("taskAttachedItemAdapter 1", "check");
}
public TaskAttachedItemAdapter(Context context, int layoutResourceId, ArrayList<HashMap<String, String>> taskList){
super(context, layoutResourceId);
this.context = context;
this.taskList = taskList;
Log.d("taskAttachedItemAdapter 2", "check");
}
@Override
public int getCount() {
return taskList.size();
}
public Item getItem(Item position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("taskAttachedItemAdapter 3", "check");
ViewHolder holder = null;
View v = convertView;
if(convertView == null)
{
Log.d("taskAttachedItemAdapter 4", "check");
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_job_attached_item, null);
TextView jid = (TextView) v.findViewById(R.id.jobID);
TextView tidt = (TextView) v.findViewById(R.id.attachedTaskID);
TextView tid = (TextView) v.findViewById(R.id.taskID);
TextView ti = (TextView) v.findViewById(R.id.taskInstrument);
TextView tt = (TextView) v.findViewById(R.id.taskType);
v.setTag(holder);
}
HashMap<String, String> i = taskList.get(position);
if(i != null)
{
Log.d("taskAttachedItemAdapter 5", "check");
holder = (ViewHolder) v.getTag();
String sjid = i.get("jobID");
String stidt = i.get("taskTitle");
String stid = i.get("taskID");
String sti = i.get("instrumentName");
String stt = i.get("taskType");
holder.jid.setText(sjid);
holder.tidt.setText(stidt);
holder.tid.setText(stid);
holder.ti.setText(sti);
holder.tt.setText(stt);
}
return v;
}
}
list_job_attached_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:paddingTop="6dip"
android:paddingBottom="6dip" >
<!-- Job id and task id - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="@+id/taskID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/jobID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="@+id/whiteBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
android:layout_alignParentBottom="true"
android:background="@drawable/white_field_with_stroke" />
<TextView
android:id="@+id/greenBackground"
android:layout_width="fill_parent"
android:layout_height="25dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="50dp"
android:background="@color/list_item_title" />
<TextView
android:id="@+id/attachedTaskID"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="50dp"
android:padding="5dp"
android:textColor="#ffffff"
android:text="Task ID : 4"
android:textSize="12sp" />
<LinearLayout
android:id="@+id/labelContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/attachedTaskID"
android:layout_marginTop="5dp">
<TextView
android:id="@+id/instrumentLabel"
android:layout_width="0dp"
android:layout_weight=".50"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="instrument :"
android:textColor="#999999"
android:textSize="9sp" />
<TextView
android:id="@+id/taskTypeLabel"
android:layout_width="0dp"
android:layout_weight=".50"
android:layout_height="wrap_content"
android:textColor="#999999"
android:text="task type"
android:textSize="9sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/labelContainer"
android:layout_marginTop="5dp">
<TextView
android:id="@+id/taskInstrument"
android:layout_width="0dp"
android:layout_weight=".50"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="#000000"
android:text="GW Instek GDS 3220"
android:textSize="12sp" />
<TextView
android:id="@+id/taskType"
android:layout_width="0dp"
android:layout_weight=".50"
android:layout_height="wrap_content"
android:text="Accredited Calibration"
android:textColor="#000000"
android:textSize="12sp" />
</LinearLayout>
</RelativeLayout>
最后是logCat错误输出
02-12 19:41:49.225: E/AndroidRuntime(4456): FATAL EXCEPTION: main
02-12 19:41:49.225: E/AndroidRuntime(4456): java.lang.NullPointerException
02-12 19:41:49.225: E/AndroidRuntime(4456): at com.calnetwork.JobAttachedTasks$1.onClick(JobAttachedTasks.java:284)
02-12 19:41:49.225: E/AndroidRuntime(4456): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
02-12 19:41:49.225: E/AndroidRuntime(4456): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 19:41:49.225: E/AndroidRuntime(4456): at android.os.Looper.loop(Looper.java:137)
02-12 19:41:49.225: E/AndroidRuntime(4456): at android.app.ActivityThread.main(ActivityThread.java:5041)
02-12 19:41:49.225: E/AndroidRuntime(4456): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 19:41:49.225: E/AndroidRuntime(4456): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 19:41:49.225: E/AndroidRuntime(4456): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-12 19:41:49.225: E/AndroidRuntime(4456): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-12 19:41:49.225: E/AndroidRuntime(4456): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
别介意人们。找到了答案。我的ListView和taskList声明是Null指针异常的原因。万一有人需要知道我做了什么来清理它,这是。
对于我的taskList ArrayList,改变了这个:
public ArrayList<HashMap<String, String>> taskList = new ArrayList<HashMap<String, String>>();
对此:
public ArrayList<HashMap<String, String>> taskList;
对于我的lv ListView,更改了这个:
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
对此:
lv = (ListView) rootView.findViewById(android.R.id.list);
我还对arrayAdapter进行了更新。
public class TaskAttachedItemAdapter extends ArrayAdapter<String> {
public static LayoutInflater inflater = null;
public ArrayList<HashMap<String, String>> taskList;
public String jobId;
public Context context;
public int layoutResourceId;
public static class ViewHolder {
TextView jid;
TextView tid;
TextView tidt;
TextView ti;
TextView tt;
}
public TaskAttachedItemAdapter(Context context, int layoutResourceId){
super(context, layoutResourceId);
this.context = context;
}
public TaskAttachedItemAdapter(Context context, int layoutResourceId, ArrayList<HashMap<String, String>> taskList){
super(context, layoutResourceId);
this.context = context;
this.taskList = taskList;
}
@Override
public int getCount() {
return taskList.size();
}
public Item getItem(Item position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HashMap<String, String> i = taskList.get(position);
ViewHolder holder = null;
View v = convertView;
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_job_attached_item, null);
TextView jid = (TextView) v.findViewById(R.id.jobID);
TextView tidt = (TextView) v.findViewById(R.id.attachedTaskID);
TextView tid = (TextView) v.findViewById(R.id.taskID);
TextView ti = (TextView) v.findViewById(R.id.taskInstrument);
TextView tt = (TextView) v.findViewById(R.id.taskType);
v.setTag(holder);
}
//holder = (ViewHolder) convertView.getTag();
if(i != null)
{
TextView jid = (TextView) v.findViewById(R.id.jobID);
TextView tidt = (TextView) v.findViewById(R.id.attachedTaskID);
TextView tid = (TextView) v.findViewById(R.id.taskID);
TextView ti = (TextView) v.findViewById(R.id.taskInstrument);
TextView tt = (TextView) v.findViewById(R.id.taskType);
String sjid = i.get("jobID");
String stidt = i.get("taskTitle");
String stid = i.get("taskID");
String sti = i.get("instrumentName");
String stt = i.get("taskType");
jid.setText(sjid);
tidt.setText(stidt);
tid.setText(stid);
ti.setText(sti);
tt.setText(stt);
}
return v;
}
}