我无法将数据从远程服务器加载到列表视图。它显示上面提到的错误,一旦打开列表,应用程序就会崩溃。 我已经突出显示了log cat中发生错误的函数。我还提到我班上的功能在哪里。
public class Library extends Fragment {
private MaterialSearchView searchView;
Librarycontact currentItem;
private SimpleAdapterLibrary adpt;
List<Librarycontact> result;
ListView lView ;
;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lib, container, false);
setHasOptionsMenu(true);
searchView = (MaterialSearchView)v.findViewById(R.id.search_view);
searchView.setVoiceSearch(true); //or false
// searchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
// searchView.setCursorDrawable(R.drawable.custom_cursor);
adpt = new SimpleAdapterLibrary(new ArrayList<Librarycontact>(), getActivity());
lView = (ListView) v.findViewById(R.id.list);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
for (int i = 0; i < lView.getAdapter().getCount(); i++) {
currentItem = result.get(i);
if (query.contentEquals(currentItem.getitmCode())) {
Intent l = new Intent(getActivity(), SingleBook.class);
l.putExtra("id", currentItem.getid());
l.putExtra("itemname", currentItem.getitemname());
l.putExtra("itmCode", currentItem.getitmCode());
l.putExtra("itmRate", currentItem.getitmRate());
startActivity(l);
break;
} else
{
Toast.makeText(getActivity(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
}
@Override
public void onSearchViewClosed() {
}
});
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentItem = result.get(position);
Intent i = new Intent(getActivity() ,SingleBook.class);
i.putExtra("id", currentItem.getid());
i.putExtra("itemname", currentItem.getitemname());
i.putExtra("itmCode", currentItem.getitmCode());
i.putExtra("itmRate", currentItem.getitmRate());
startActivity(i);
}
});
searchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentItem = result.get(position);
Intent i = new Intent(getActivity(), SingleBook.class);
i.putExtra("id", currentItem.getid());
i.putExtra("itemname", currentItem.getitemname());
i.putExtra("itmCode", currentItem.getitmCode());
i.putExtra("itmRate", currentItem.getitmRate());
startActivity(i);
}
});
if (isAvailable()){ lView.setAdapter(adpt);
// Exec async load task
(new AsyncListViewLoader()).execute("http://minor.esy.es/libraryavailabilityofbooks.php");
}
else{
showAlertDialog(getActivity(), "No Internet Connection",
"Please Check Your Internet Connection And Try Again", false);
}
return v;}
public Boolean isAvailable() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
if(reachable){
System.out.println("Internet access");
return reachable;
}
else{
System.out.println("No Internet access");
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
}
HERE **private class AsyncListViewLoader extends AsyncTask<String, Void, List<Librarycontact>> {**
private final ProgressDialog dialog = new ProgressDialog(getActivity());
@Override
protected void onPostExecute(List<Librarycontact> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.getItemList();
**adpt.setItemList(result);** HERE
adpt.notifyDataSetChanged();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading information...");
dialog.show();
}
@Override
protected List<Librarycontact> doInBackground(String... params) {
result = new ArrayList<>();
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
// Read the stream
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(convertContact(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
private Librarycontact convertContact(JSONObject obj) throws JSONException {
String itemname = obj.getString("availability");
String itmCode = obj.getString("title");
String id = obj.getString("id");
String itmRate = obj.getString("authorname");
return new Librarycontact(itemname, itmCode, id,itmRate);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == getActivity().RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches != null && matches.size() > 0) {
String searchWrd = matches.get(0);
if (!TextUtils.isEmpty(searchWrd)) {
searchView.setQuery(searchWrd, false);
}
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
我的数据模型
public class Librarycontact implements Serializable {
private String itemname;
private String id;
private String itmCode;
private String itmRate;
public Librarycontact(String name, String itmCode, String id,String itmRate) {
super();
this.itemname = name;
this.itmCode = itmCode;
this.id = id;
this.itmRate = itmRate;
}
public String getitemname() {
return itemname;
}
public void setName(String itemname) {
this.itemname = itemname;
}
public String getitmCode() {
return itmCode;
}
public void setitmCode(String itmCode) {
this.itmCode = itmCode;
}
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
public String getitmRate() {
return itmRate;
}
public void setitmRate(String itmRate) {
this.itmRate = itmRate;
}
}
和我的适配器
public class SimpleAdapterLibrary extends ArrayAdapter<Librarycontact> {
private List<Librarycontact> itemList;
private Context context;
private ArrayList<Librarycontact> contactListOrigin = new ArrayList<Librarycontact>();
public SimpleAdapterLibrary(List<Librarycontact> itemListt, Context ctx) {
super(ctx, android.R.layout.simple_list_item_1, itemListt);
this.itemList = itemListt;
this.context = ctx;
this.contactListOrigin.addAll(itemListt);
}
public int getCount() {
if (itemList != null)
return itemList.size();
return 0;
}
public Librarycontact getItem(int position) {
if (itemList != null)
return itemList.get(position);
return null;
}
public long getItemId(int position) {
if (itemList != null)
return itemList.get(position).hashCode();
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.liblistitem, null);
}
Librarycontact c = itemList.get(position);
//TextView text = (TextView) v.findViewById(R.id.name);
//text.setText(c.getitemname());
TextView text1 = (TextView) v.findViewById(R.id.name);
text1.setText(c.getitmCode());
String g= c.getitmCode();
Character o = g.charAt(0);
String k = o.toString();
TextDrawable drawable = TextDrawable.builder()
.beginConfig()
.textColor(Color.BLACK)
.useFont(Typeface.DEFAULT)
.fontSize(30)
.bold()
.toUpperCase()
.endConfig()
.buildRoundRect(k, Color.RED, 10); // radius in px
ImageView img = (ImageView) v.findViewById(R.id.imageView2);
img.setImageDrawable(drawable);
/* TextView text2 = (TextView) v.findViewById(R.id.email);
text2.setText(c.getid());
TextView text3 = (TextView) v.findViewById(R.id.phone);
text3.setText(c.getitmRate());
*/
return v;
}
public List<Librarycontact> getItemList() {
if (itemList == null)
return Collections.emptyList();
else
return itemList;
}
public void setItemList(List<Librarycontact> itemListt) {
this.itemList = itemListt;
**contactListOrigin.addAll(itemListt);** HERE
}}
我的logcat
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: FATAL EXCEPTION: main
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: Process: essentials.gtbit.com.gtbitessentials, PID: 4998
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.util.ArrayList.addAll(ArrayList.java:188)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.SimpleAdapterLibrary.setItemList(SimpleAdapterLibrary.java:110)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.Library$AsyncListViewLoader.onPostExecute(Library.java:215)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.Library$AsyncListViewLoader.onPostExecute(Library.java:206)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:632)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:111)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.Looper.loop(Looper.java:194)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5576)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
答案 0 :(得分:1)
您必须在课程SimpleAdapterLibrary
中执行此操作:
public void setItemList(List<Librarycontact> itemListt) {
if(itemListt==null) {
return;
}
this.itemList = itemListt;
contactListOrigin.addAll(itemListt);
}
或在课程AsyncListViewLoader
中:
@Override
protected void onPostExecute(List<Librarycontact> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result!=null){
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
}