【发布时间】:2014-08-15 20:36:21
【问题描述】:
我有一个用于列表视图的自定义 ArrayAdapter。当我设置列表适配器时,不会调用 getView。我已经返回了计数,并且计数应该是(不是 0)。我还记录了不同的项目位置,以确保适配器有数据要显示,但仍然没有调用 getview。我在异步任务的 postExecute() 中设置了列表适配器。似乎除了 getView 之外的所有东西都被调用了。这是代码
private class StableArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private List<String> viewString;
private ImageView image;
private TextView addToCalendarButton;
private TextView eventTitle;
private ImageView eventImage;
private TextView likesTV;
private TextView planToAttendTV;
public StableArrayAdapter(Context context, List<String> strings) {
super(context, R.layout.post_layout, strings);
this.context = context;
this.viewString = strings;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View postLayout = inflater.inflate(R.layout.post_layout, parent, false);
TextView unameTV = (TextView)postLayout.findViewById(R.id.postUnameTv);
unameTV.setText(viewString.get(0));
image = (ImageView)postLayout.findViewById(R.id.postProfPic);
DisplayImageOptions options = initiateDisplayImageOptions();
ImageLoader imageloader = ImageLoader.getInstance();
initImageLoader(getActivity());
imageloader.displayImage(viewString.get(1), image, options);
addToCalendarButton = (TextView)postLayout.findViewById(R.id.addToCalendarButton);
addToCalendarButton.setText(viewString.get(2));
eventTitle = (TextView)postLayout.findViewById(R.id.postTitleTV);
eventTitle.setText(viewString.get(3));
eventImage = (ImageView)postLayout.findViewById(R.id.eventImage);
imageloader.displayImage(viewString.get(4), eventImage, options);
likesTV = (TextView)postLayout.findViewById(R.id.likesTV);
likesTV.setText(""+viewContent.get(5));
planToAttendTV = (TextView)postLayout.findViewById(R.id.planToAttendTV);
planToAttendTV.setText(viewString.get(6));
Log.d("Adapter", ""+viewString.get(6));
return postLayout;
}
@Override
public int getCount()
{
return viewString.size();
}
@Override
public String getItem(int position) {
return viewString.get(position);
}
}
}`
我不确定这是否是一个原因,但这是我在 postExecute 中设置列表适配器的方式
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
StableArrayAdapter adapter = new StableArrayAdapter(getActivity(), viewContent);
// updating listview
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
编辑 这是我用来获取数据的异步任务
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_get_events, "GET", params);
// Check your log cat for JSON reponse
Log.d("Loading Events: ", "Loading Events...");
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt("id");
String name = c.getString("name");
String radius = c.getString("radius");
String centerlat = c.getString("centerlat");
String centerlng = c.getString("centerlng");
String topleftcornerlat = c.getString("topleftcornerlat");
String topleftcornerlng = c.getString("topleftcornerlng");
String bottomleftcornerlat = c.getString("bottomleftcornerlat");
String bottomleftcornerlng = c.getString("bottomleftcornerlng");
String bottomrightcornerlat = c.getString("bottomrightcornerlat");
String bottomrightcornerlng = c.getString("bottomrightcornerlng");
String startmonth = c.getString("startmonth");
String endmonth = c.getString("endmonth");
String startday= c.getString("startday");
String endday = c.getString("endday");
String startyear = c.getString("startyear");
String endyear = c.getString("endyear");
String starthour = c.getString("starthour");
String endhour= c.getString("endhour");
String startmins = c.getString("startmins");
String endmins= c.getString("endmins");
String attending_future = c.getString("attending_future");
String attending_now = c.getString("attending_now");
String likes = c.getString("likes");
String image = c.getString("image");
String profile = c.getString("profile");
String userprofilepic = c.getString("userprofpic");
String username = c.getString("username");
viewContent.add(username);
viewContent.add(userprofilepic);
String date = getMonth(Integer.parseInt(startmonth)) + " " + startday + ", " + startyear;
viewContent.add(date);
viewContent.add(name);
viewContent.add(image);
viewContent.add(""+likes);
viewContent.add(attending_future + " people plan to attend.");
}
} else {
// no products found
// Launch Add New product Activity
/*
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
*/
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.d("Loading Events: ", "Events Loaded");
// dismiss the dialog after getting all products
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
StableArrayAdapter adapter = new StableArrayAdapter(getActivity(), viewContent);
// updating listview
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
}
编辑
这是完整的代码
public class MainFeed extends Fragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static List<String> viewContent = new ArrayList<>();
static Bundle bundle;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_get_events = "http://127.0.0.1/get_events.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
private ListView lv;
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
bundle = savedInstanceState;
inflater = getLayoutInflater(savedInstanceState);
View view=inflater.inflate(R.layout.main_feed_layout, null);
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
lv = (ListView) view.findViewById(R.id.listView);
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
/*
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
*/
}
});
ImageLoadingListener progressListener = new ImageLoadingListener() {
@Override
public void onLoadingStarted(String s, View view) {
Log.i("Start", "Start");
}
@Override
public void onLoadingFailed(String s, View view, FailReason failReason) {
Log.i("Start", "Failed");
}
@Override
public void onLoadingComplete(String s, View view, Bitmap bitmap) {
}
@Override
public void onLoadingCancelled(String s, View view) {
Log.i("Start", "Cancelled");
}
};
if (container == null) {
return null;
}
return (RelativeLayout) inflater.inflate(R.layout.main_feed_layout, container, false);
}
// Response from Edit Product Activity
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = data;
//finish();
startActivity(intent);
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_get_events, "GET", params);
// Check your log cat for JSON reponse
Log.d("Loading Events: ", "Loading Events...");
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt("id");
String name = c.getString("name");
String radius = c.getString("radius");
String centerlat = c.getString("centerlat");
String centerlng = c.getString("centerlng");
String topleftcornerlat = c.getString("topleftcornerlat");
String topleftcornerlng = c.getString("topleftcornerlng");
String bottomleftcornerlat = c.getString("bottomleftcornerlat");
String bottomleftcornerlng = c.getString("bottomleftcornerlng");
String bottomrightcornerlat = c.getString("bottomrightcornerlat");
String bottomrightcornerlng = c.getString("bottomrightcornerlng");
String startmonth = c.getString("startmonth");
String endmonth = c.getString("endmonth");
String startday= c.getString("startday");
String endday = c.getString("endday");
String startyear = c.getString("startyear");
String endyear = c.getString("endyear");
String starthour = c.getString("starthour");
String endhour= c.getString("endhour");
String startmins = c.getString("startmins");
String endmins= c.getString("endmins");
String attending_future = c.getString("attending_future");
String attending_now = c.getString("attending_now");
String likes = c.getString("likes");
String image = c.getString("image");
String profile = c.getString("profile");
String userprofilepic = c.getString("userprofpic");
String username = c.getString("username");
viewContent.add(username);
viewContent.add(userprofilepic);
String date = getMonth(Integer.parseInt(startmonth)) + " " + startday + ", " + startyear;
viewContent.add(date);
viewContent.add(name);
viewContent.add(image);
viewContent.add(""+likes);
viewContent.add(attending_future + " people plan to attend.");
}
} else {
// no products found
// Launch Add New product Activity
/*
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
*/
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.d("Loading Events: ", "Events Loaded");
// dismiss the dialog after getting all products
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
StableArrayAdapter adapter = new StableArrayAdapter(getActivity(), viewContent);
// updating listview
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private class StableArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private List<String> viewString;
private ImageView image;
private TextView addToCalendarButton;
private TextView eventTitle;
private ImageView eventImage;
private TextView likesTV;
private TextView planToAttendTV;
public StableArrayAdapter(Context context, List<String> strings) {
super(context, R.layout.post_layout, strings);
this.context = context;
this.viewString = strings;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View postLayout = inflater.inflate(R.layout.post_layout, parent, false);
TextView unameTV = (TextView)postLayout.findViewById(R.id.postUnameTv);
unameTV.setText(viewString.get(0));
image = (ImageView)postLayout.findViewById(R.id.postProfPic);
DisplayImageOptions options = initiateDisplayImageOptions();
ImageLoader imageloader = ImageLoader.getInstance();
initImageLoader(getActivity());
imageloader.displayImage(viewString.get(1), image, options);
addToCalendarButton = (TextView)postLayout.findViewById(R.id.addToCalendarButton);
addToCalendarButton.setText(viewString.get(2));
eventTitle = (TextView)postLayout.findViewById(R.id.postTitleTV);
eventTitle.setText(viewString.get(3));
eventImage = (ImageView)postLayout.findViewById(R.id.eventImage);
imageloader.displayImage(viewString.get(4), eventImage, options);
likesTV = (TextView)postLayout.findViewById(R.id.likesTV);
likesTV.setText(""+viewContent.get(5));
planToAttendTV = (TextView)postLayout.findViewById(R.id.planToAttendTV);
planToAttendTV.setText(viewString.get(6));
Log.d("Adapter", ""+viewString.get(6));
return postLayout;
}
@Override
public int getCount()
{
Log.d("Adapter", ""+viewString.size());
return viewString.size();
}
@Override
public String getItem(int position) {
return viewString.get(position);
}
}
}
public DisplayImageOptions initiateDisplayImageOptions()
{
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
return options;
}
protected void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.diskCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
public String getMonth(int mon)
{
String month;
if(mon == 1)
{
month = "January";
}
else if (mon == 2)
{
month = "February";
}
else if (mon == 3)
{
month = "March";
}
else if (mon == 4)
{
month = "April";
}
else if (mon == 5)
{
month = "May";
}
else if (mon == 6)
{
month = "June";
}
else if (mon == 7)
{
month = "July";
}
else if (mon == 8)
{
month = "August";
}
else if (mon == 9)
{
month = "September";
}
else if (mon == 10)
{
month = "October";
}
else if (mon == 11)
{
month = "November";
}
else
{
month = "December";
}
return month;
}
}
【问题讨论】:
-
数据是否显示??如果不发布整个代码
-
@Rod_Algonquin 你是什么意思?我从 json 数组中获取数据。如果您的意思是实际使用的数据,是的。
-
你能发布你的异步任务吗
-
@Rod_Algonquin 但是不显示数据。膨胀的布局没有被膨胀到列表视图中。
-
向
getCount()添加一条日志语句,以确保它被调用并返回一个 > 0 的值。
标签: android