【问题标题】:AsyncTask isn't working with BaseAdapterAsyncTask 不适用于 BaseAdapter
【发布时间】:2012-08-21 15:08:16
【问题描述】:

我正在构建歌曲列表应用程序。我想在加载数据时显示启动画面。为此,我设置了一个AsyncTask 与 ViewSwitcher 结合使用,以在初始屏幕(只是徽标和圆形进度条)和主屏幕之间切换 xml 布局。问题是在将数据放入 ListView 时,我使用的是单独类中的 BaseAdapter,它会引发错误"The Constructor LazyAdapter(Home.LoadViewTask, ArrayList<HashMap<String,String>>) is undefined"

这是具有 AsyncTask 的 Home 类的来源:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main);

    mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
    mBtnNaslovnica.setSelected(true);

    new LoadViewTask().execute();
}

//To use the AsyncTask, it must be subclassed
public class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
    //A TextView object and a ProgressBar object
    private TextView tv_progress;
    private ProgressBar pb_progressBar;

    //Before running code in the separate thread
    @Override
    protected void onPreExecute() 
    {
        //Initialize the ViewSwitcher object
        viewSwitcher = new ViewSwitcher(Home.this);
        /* Initialize the loading screen with data from the 'loadingscreen.xml' layout xml file. 
         * Add the initialized View to the viewSwitcher.*/
        viewSwitcher.addView(ViewSwitcher.inflate(Home.this, R.layout.init, null));

        //Set ViewSwitcher instance as the current View.
        setContentView(viewSwitcher);
    }

    //The code to be executed in a background thread.
    @Override
    protected Void doInBackground(Void... params) 
    {
        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_SONG);
        // looping through all song nodes <song>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

            // adding HashList to ArrayList
            songsList.add(map);
        }

        list=(ListView)findViewById(R.id.list);

        // Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);        
        list.setAdapter(adapter);
        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {    

            }
        });

        return null;
    }

    //After executing the code in the thread
    @Override
    protected void onPostExecute(Void result) 
    {
        /* Initialize the application's main interface from the 'main.xml' layout xml file. 
         * Add the initialized View to the viewSwitcher.*/
        viewSwitcher.addView(ViewSwitcher.inflate(Home.this, R.layout.main, null));
        //Switch the Views
        viewSwitcher.showNext();
    }
}

//Override the default back key behavior
@Override
public void onBackPressed() 
{
    //Emulate the progressDialog.setCancelable(false) behavior
    //If the first view is being shown
    if(viewSwitcher.getDisplayedChild() == 0)
    {
        //Do nothing
        return;
    }
    else
    {
        //Finishes the current Activity
        super.onBackPressed();
    }
}

这是LazyAdapter类的来源:

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader; 

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_row, null);

    TextView title = (TextView)vi.findViewById(R.id.title); // title
    TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
    TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);

    // Setting all values in listview
    title.setText(song.get(Home.KEY_TITLE));
    artist.setText(song.get(Home.KEY_ARTIST));
    duration.setText(song.get(Home.KEY_DURATION));
    imageLoader.DisplayImage(song.get(Home.KEY_THUMB_URL), thumb_image);
    return vi;
}

`

【问题讨论】:

    标签: android listview android-asynctask baseadapter


    【解决方案1】:

    你不能做任何 UI 修改.. 例如设置标签文本,修改 AsyncTask.doInBackground 中的列表.. 因为它是一个单独的线程...

      list=(ListView)findViewById(R.id.list);
    
    
        // Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);        
        list.setAdapter(adapter);
        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
    
    
            }
        });
    

    您应该在调用之前放置这部分代码

    新的 LoadViewTask().execute();

    在 doInBackground()... 作为最后一行.. 把这条线.. 适配器.notifyDataSetChanged();

    【讨论】:

    • 你能得到一个包含所有歌曲的列表视图吗.. 没有加载栏???那部分对你有用吗?一个简单的活动,里面只有 listview.. 只需使用 asyncTask 加载数据.. 看看它是否显示.. 当它关闭时.. 可能 viewSwitcher 很容易在之后做......
    • 我这样做了,但我不工作,它只有在我删除完整的 AsyncTask 时才工作,但那毫无意义
    • 你的 R.layout.main 长什么样子??
    • 我知道如何以其他方式做到这一点 :) 但是 thnx ;)
    【解决方案2】:

    第一个参数中的构造函数获取 Activity 并传递 LoadViewTask 的实例(这指的是 LoadViewTask 的当前实例), 而不是这种用法:

    adapter=new LazyAdapter(Home.this, songList);

    Home应该是您的活动名称

    【讨论】:

    • 它不工作,它消除了错误,但是当我启动应用程序时..在启动屏幕后它崩溃
    【解决方案3】:

    问题在于,无论出于何种原因,您都需要 Activity 作为构造函数的第一个参数。通过将this 传递给适配器的构造函数,您将传递AsyncTask 类型的对象,该对象不是活动且没有上下文。因此,您应该将Activity 作为LoadViewTask 的重写构造函数中的参数传递,然后将其用作构造函数的正确参数。 尽管如此,在将上下文绑定到AsyncTask 时要小心,因为它可能会导致意外行为(Activity 可能在AsyncTask 尝试更新它时不再存在)。 AsyncTask 是一个非常危险的类,因为它有许多与同步相关的缺陷。

    【讨论】:

      【解决方案4】:

      我希望这可能会有所帮助,

      onPostExecute include (Inside AsyncTask)
      
      ExampleAdapter sectionedAdapter = new  EfficientAdapter(ClassInfoThread.this,getBaseContext());
      listView.setAdapter(sectionedAdapter);  
      

      在你的适配器类中添加这个构造函数

      public ExampleAdapter(ExampleThread exampleThread,Context context) {
              // TODO Auto-generated constructor stub`enter code here`
              mInflater = LayoutInflater.from(context);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-16
        • 2018-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-28
        • 2015-11-16
        相关资源
        最近更新 更多