android - 构造函数未定义 ArrayAdapter

标签 android android-arrayadapter

我收到这个错误:

The constructor AllProductsActivity.MyAdapter(AllProductsActivity, int, ArrayList<HashMap<String,String>>) is undefined

在这一行:

MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);

我最好的猜测是 productsList 是问题所在,但在尝试理解代码大约 2 天后,我还没有弄清楚。很多代码都来自本教程,老实说,我不明白 HashMap 是什么。 - http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

我知道帮助那些看起来一无所知的堆栈溢出的人很糟糕,但我真的可以在正确的方向上使用推送。 HashMap 类概述对我来说就像是胡言乱语 ( http://developer.android.com/reference/java/util/HashMap.html )

在此先感谢您的帮助。

这是我的整个 AllProductsActivity:

public class AllProductsActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://mywebsite/mycameraapp/android_connect/get_all_products.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";
private static final String TAG_DESCRIPTION = "description";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on selecting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            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);
        }
    });

}

/** CALLED WHEN THE USER CLICKS THE RECORD BUTTON */
public void sendMessage(View view) {
    Intent videoIntent = new Intent(this, PhotoIntentActivity.class);
    startActivity(videoIntent);
}

// Response from Edit Product Activity
@Override
protected 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 = getIntent();
        finish();
        startActivity(intent);
    }

}

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

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

    }

    /**
     * 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_all_products, "GET", params);

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

        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
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String description = c.getString(TAG_DESCRIPTION);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_DESCRIPTION, description);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } 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) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);

                // updating listview
                setListAdapter(adapter);

            }

        });

    }

}

}

我实际上在 AllProductsActivity 文件中有 MyAdapter,但为了便于查看,我将其单独放在此处:

public class MyAdapter extends ArrayAdapter<MyItem>{

    Context context;
    int resourceId;
    ArrayList<MyItem> items = null;
    LayoutInflater inflater;

    public MyAdapter (Context context, int resourceId, ArrayList<MyItem> items)
    {
        super(context, resourceId, items);

        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        final ViewHolder holder;
        if (convertView == null){

            convertView = inflater.inflate(R.layout.list_item, null);

            holder = new ViewHolder();
            holder.name = (TextView)convertView.findViewById(R.id.name);
            holder.video = (VideoView)convertView.findViewById(R.id.videoView);
            convertView.setTag(holder);

        } else {

            holder = (ViewHolder)convertView.getTag();
        }

        MyItem item = items.get(position);
        if (item != null)
        {
            // This is where you set up the views.
            holder.name.setText(TAG_NAME);
            Uri myUri = Uri.parse(TAG_DESCRIPTION);
            holder.video.setVideoURI(myUri);
            holder.video.seekTo(1);
            holder.video.setOnTouchListener(
                    new View.OnTouchListener()
                    {

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            holder.video.start();
                            holder.video.requestFocus();
                            return false;
                        }
                    }
                );

        }

        return convertView;
    }

    public class ViewHolder
    {
        TextView    name;
        VideoView   video;
    }
}

最佳答案

您正在将 productsList 传递给构造函数,它是 HashMapsArrayList

ArrayList<HashMap<String, String>> productsList;

同时删除 runOnUiThread,因为 onPostExecute 在 ui 线程本身上被调用。

你的构造函数必须是。

ArrayList<HashMap<String, String>>  items;
public MyAdapter (Context context, int resourceId, ArrayList<HashMap<String, String>> items)
{
    super(context, resourceId, items);
    this.items =items;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

getView()

HashMap<String,String> item = (HashMap<String,String> ) items.get(position);

设置文本

holder.name.setText(item.get(TAG_NAME));

也改为

public class MyAdapter extends ArrayAdapter<HashMap<String, String>> {

关于android - 构造函数未定义 ArrayAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23707476/

相关文章:

Android caffe Forward Prefilled() 在多线程对象中不起作用

java - 开发 Android 应用程序时的最佳实践

android - 带复选框的 ListView Holder

java - Android 应用程序在 arrayadapters 的 setadapter 函数处崩溃

android - 如何在sqlite android中检索下一个值

android - 在 android 聊天气泡可调中插入 imageview

java - 自定义ListView打开另一个自定义ListView

java - 调用 Camera.release() 后相机正在被使用

java - 如何从不同的 Activity 更改媒体播放器

java - 从 OnClickListener Android 打开 URL