Android Studio 将自定义适配器添加到 AsyncTask

Posted

技术标签:

【中文标题】Android Studio 将自定义适配器添加到 AsyncTask【英文标题】:Android studio adding custom adapter to AsyncTask 【发布时间】:2017-07-16 16:23:50 【问题描述】:

所以我有一个 AsyncTask,它从 mysql 数据库中提取数据并显示它,目前这工作正常,但我需要将简单适配器更改为自定义适配器,以便我可以对显示的内容进行更多操作。但我不确定我需要更改什么才能让我的自定义适配器与我的 AsyncTask 一起使用。

public class SearchFor extends AppCompatActivity implements View.OnClickListener 

DBManager db;
ListView lv;

myAdapter myAdapter;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> attractionList;
ArrayList<HashMap<String, String>> transportList;

// url to get all attraction list
private static String url_all_attractions = "http://10.0.2.2/TravelApp/get_all_attractions.php";
private static String url_all_transport = "http://10.0.2.2/TravelApp/get_all_transport.php";

// JSON Node names for attraction
private static final String TAG_SUCCESS = "success";
private static final String TAG_ATTRACTION = "attraction";
private static final String TAG_ATTRACTIONID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_TYPE = "Type";
private static final String TAG_LOCATION = "Location";
private static final String TAG_OPENING = "OpeningTime";
private static final String TAG_CLOSING = "ClosingTime";
private static final String TAG_NEARBYSTOP = "NearbyStop";
private static final String TAG_LATITUDE = "Latitude";
private static final String TAG_LONGITUDE = "Longitude";

//JSON Node names for transport
private static final String TAG_TRANSPORT = "transport";
private static final String TAG_TRANSPORTID = "Id";
private static final String TAG_TIME = "Time";
private static final String TAG_NEXTSTOP = "NextStop";
private static final String TAG_PHONENUMBER = "PhoneNumber";

// attraction JSONArray
JSONArray attraction = null;
JSONArray transport = null;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_for);

    db = new DBManager(this);

    // Hashmap for ListView
    attractionList = new ArrayList<HashMap<String, String>>();
    transportList = new ArrayList<HashMap<String, String>>();
    lv = (ListView) findViewById(R.id.list_search);
    this.registerForContextMenu(lv);



@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenu.ContextMenuInfo menuInfo) 
    super.onCreateContextMenu(menu, v, menuInfo);
    if(v.getId()== R.id.list_search )
        this.getMenuInflater().inflate(R.menu.context_menu_more,menu);
    


@Override
public boolean onContextItemSelected(MenuItem item) 
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) 
        case R.id.menuBookmark:
            testAdd();
            break;
        case R.id.menuDirections:
            break;
        default:
            return super.onContextItemSelected(item);
    
    return false;


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home_button, menu);
    getMenuInflater().inflate(R.menu.optionsmenu,menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in androidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if(id == R.id.go_home)
        Intent i = new Intent(getApplicationContext(),QavelNav.class);
        startActivity(i);
    

    if (item.isChecked())
        item.setChecked(false);
    else
        item.setChecked(true);

    if(id == R.id.attractionSub1)
        new LoadAllAttractions().execute();
    else if(id == R.id.attractionSub2)
        Toast.makeText(getApplicationContext(),"Pubs", Toast.LENGTH_LONG).show();
    else if(id == R.id.attractionSub3)

    else if(id == R.id.attractionSub4)

    else if(id == R.id.transportSub1)
        new LoadAllTransport().execute();
    else if(id == R.id.transportSub2)

    
    return super.onOptionsItemSelected(item);


@Override
public void onClick(View view) 
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        @Override
        public void onItemClick(AdapterView<?> parent, View viewClicked,
                                int position, long id) 

            System.out.println(position);
        
    );


/**
 * Background Async Task to Load all product by making HTTP Request
 */
class LoadAllAttractions extends AsyncTask<String, String, String> 

    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() 
        super.onPreExecute();
        pDialog = new ProgressDialog(SearchFor.this);
        pDialog.setMessage("Loading attractions. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    

    /**
     * getting All attraction 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_all_attractions, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Attractions: ", json.toString());

        try 
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) 
                // attraction found
                // Getting Array of Products
                attraction = json.getJSONArray(TAG_ATTRACTION);

                // looping through All Products
                for (int i = 0; i < attraction.length(); i++) 
                    JSONObject c = attraction.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ATTRACTIONID);
                    String name = c.getString(TAG_NAME);
                    String type = c.getString(TAG_TYPE);
                    String location = c.getString(TAG_LOCATION);
                    String opening = c.getString(TAG_OPENING);
                    String closing = c.getString(TAG_CLOSING);
                    String nearbyStop1 = c.getString(TAG_NEARBYSTOP);
                    String latitude = c.getString(TAG_LATITUDE);
                    String longitude = c.getString(TAG_LONGITUDE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ATTRACTIONID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_TYPE, type);
                    map.put(TAG_LOCATION, location);
                    map.put(TAG_OPENING,opening);
                    map.put(TAG_CLOSING,closing);
                    map.put(TAG_NEARBYSTOP, nearbyStop1);
                    map.put(TAG_LATITUDE, latitude);
                    map.put(TAG_LONGITUDE, longitude);
                    // adding HashList to ArrayList
                    attractionList.add(map);
                
            
         catch (JSONException e) 
            e.printStackTrace();
        

        return null;
    

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String file_url) 
        final ArrayList<Adapter> listData = new ArrayList<Adapter>();
        listData.clear();
        // dismiss the dialog after getting all attraction
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() 
           public void run() 
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        SearchFor.this, attractionList,
                        R.layout.list_attractions, new String[]TAG_ATTRACTIONID,
                        TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_OPENING,TAG_CLOSING,TAG_NEARBYSTOP,TAG_LATITUDE,TAG_LONGITUDE,
                        new int[]R.id.Attractionid, R.id.tvAttractionName, R.id.tvAttractionType, R.id.tvAttractionLocation,R.id.tvAttractionOpening,R.id.tvAttractionClosing,R.id.tvAttractionNearbyStop1);
                // updating listview

                //myAdapter = new myAdapter(listData);
                lv.setAdapter(adapter);

            
        );

    



class LoadAllTransport extends AsyncTask<String, String, String> 

    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() 
        super.onPreExecute();
        pDialog = new ProgressDialog(SearchFor.this);
        pDialog.setMessage("Loading Transport. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    

    /**
     * getting All attraction 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_all_transport, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Transport: ", json.toString());

        try 
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) 
                // attraction found
                // Getting Array of Products
                transport = json.getJSONArray(TAG_TRANSPORT);

                // looping through All Products
                for (int i = 0; i < transport.length(); i++) 
                    JSONObject c = transport.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_TRANSPORTID);
                    String name = c.getString(TAG_NAME);
                    String type = c.getString(TAG_TYPE);
                    String location = c.getString(TAG_LOCATION);
                    String time = c.getString(TAG_TIME);
                    String nextStop = c.getString(TAG_NEXTSTOP);
                    String phoneNumber = c.getString(TAG_PHONENUMBER);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_TRANSPORTID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_TYPE, type);
                    map.put(TAG_LOCATION, location);
                    map.put(TAG_TIME,time);
                    map.put(TAG_NEXTSTOP,nextStop);
                    map.put(TAG_PHONENUMBER, phoneNumber);

                    // adding HashList to ArrayList
                    transportList.add(map);
                
            
         catch (JSONException e) 
            e.printStackTrace();
        

        return null;
    

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String file_url) 
        // dismiss the dialog after getting all attraction
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() 
            public void run() 
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        SearchFor.this, transportList,
                        R.layout.list_transport, new String[]TAG_TRANSPORTID,
                        TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_TIME,TAG_NEXTSTOP,TAG_PHONENUMBER,
                        new int[]R.id.transportid, R.id.tvTransportName, R.id.tvTransportType, R.id.tvTransportLocation,R.id.tvTransportPhone);
                // updating listview
                lv.setAdapter(adapter);
            
        );

    



public void testAdd()
    TextView TextName = (TextView)findViewById(R.id.tvAttractionName);
    System.out.println(TextName.getText().toString());


public void addAttraction(View v)

    TextView TextName = (TextView)findViewById(R.id.tvAttractionName);
    System.out.println(TextName.getText().toString());

    TextView TextType = (TextView) findViewById(R.id.tvAttractionType);
    TextView TextLocation = (TextView)findViewById(R.id.tvAttractionLocation);
    TextView TextOpening = (TextView)findViewById(R.id.tvAttractionOpening);
    TextView TextClosing = (TextView)findViewById(R.id.tvAttractionClosing);
    TextView TextNearbyStop = (TextView)findViewById(R.id.tvAttractionNearbyStop1);

    ContentValues values = new ContentValues();
    values.put(DBManager.ColName,TextName.getText().toString());
    values.put(DBManager.ColType,TextType.getText().toString());
    values.put(DBManager.ColLocation,TextLocation.getText().toString());
    values.put(DBManager.ColOpening,TextOpening.getText().toString());
    values.put(DBManager.ColClosing,TextClosing.getText().toString());
    values.put(DBManager.ColNearbyStop,TextNearbyStop.getText().toString());

    long id = db.Insert("BookmarkAttraction",values);
    if (id > 0)
        Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();



public void addTransport(View v)
    TextView TextName = (TextView)findViewById(R.id.tvTransportName);
    TextView TextType = (TextView) findViewById(R.id.tvTransportType);
    TextView TextLocation = (TextView)findViewById(R.id.tvTransportLocation);
    TextView TextPhoneNumber = (TextView)findViewById(R.id.tvTransportPhone);

    ContentValues values = new ContentValues();
    values.put(DBManager.ColName,TextName.getText().toString());
    values.put(DBManager.ColType,TextType.getText().toString());
    values.put(DBManager.ColLocation,TextLocation.getText().toString());
    values.put(DBManager.ColPhoneNumber,TextPhoneNumber.getText().toString());

    long id = db.Insert("BookmarkTransport",values);
    if (id > 0)
        Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();


class myAdapter extends BaseAdapter 

    public ArrayList<Adapter> listItem;

    public myAdapter(ArrayList<Adapter> listItem) 
        this.listItem = listItem;
    
    @Override
    public int getCount() 
        return listItem.size();
    
    @Override
    public Object getItem(int position) 
        return null;
    

    @Override
    public long getItemId(int position) 
        return position;
    

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) 
        LayoutInflater myInflator = getLayoutInflater();
        final View myView = myInflator.inflate(R.layout.list_attractions, null);

        final Adapter ac = listItem.get(position);

        TextView attractionId = (TextView) myView.findViewById(R.id.Attractionid);
        attractionId.setText(ac.ID);

        TextView Name = (TextView) myView.findViewById(R.id.tvAttractionName);
        Name.setText(ac.Name);

        TextView Type = (TextView) myView.findViewById(R.id.tvAttractionType);
        Type.setText(ac.Type);

        TextView Location = (TextView) myView.findViewById(R.id.tvAttractionLocation);
        Location.setText(ac.Location);

        TextView Opening = (TextView) myView.findViewById(R.id.tvAttractionOpening);
        Opening.setText(ac.Opening);

        TextView Closing = (TextView) myView.findViewById(R.id.tvAttractionClosing);
        Closing.setText(ac.Closing);

        TextView NearbyStop1 = (TextView) myView.findViewById(R.id.tvAttractionNearbyStop1);
        NearbyStop1.setText(ac.NearbyStop);

        return myView;
    


感兴趣的部分是位于底部的自定义适配器(myAdapter),第一个 AsyncTask 是我试图转换为自定义适配器的内容。 onPostExecute 是简单适配器所在的位置,可能我需要引用自定义适配器但需要帮助

【问题讨论】:

【参考方案1】:

您似乎正在使用一个适配器来满足您的两种需求。

您是否考虑过为您的两个 AsyncTask 创建两个自定义适配器类。

还有一些建议: 1. 如果您使用 AsyncTask 进行数据库获取,您可以使用 Loader Callbacks 和 Cursor loader。 2. preExecute 和 postExecute 已经在 UI 线程上运行。所以那里不需要 runOnUIThread 调用。 3. 在 Adapters getView 方法中使用 ViewHolder 模式以获得更好的优化。

【讨论】:

感谢您提供有关 runOnUIThread 调用的提示,我将研究 ViewHolder 模式,但是我如何使用我所拥有的实现加载器回调,即我需要替换什么。/更改为容纳他们,然后我将如何将加载的结果与我的自定义适配器链接

以上是关于Android Studio 将自定义适配器添加到 AsyncTask的主要内容,如果未能解决你的问题,请参考以下文章

Android将自定义适配器设置为viewPager

Android Gradle 插件将自定义 Gradle 插件上传到自建 Maven 仓库 ④ ( 默认生成的 pom 文件 | Maven 中的 pom 配置 | 自定义 pom 文件节点 )

Android Gradle 插件将自定义 Gradle 插件上传到自建 Maven 仓库 ⑦ ( 登录 Maven 私服 | Maven 私服初始化设置 | 创建 Maven 仓库 )

Android Gradle 插件将自定义 Gradle 插件上传到自建 Maven 仓库 ⑥ ( 配置 Sonatype Nexus 搭建的 Maven 私服 | 配置端口号 | 配置JVM )

如何将自定义按钮应用于 Android Studio 中的活动?

android以编程方式将自定义按钮添加到布局