自定义列表视图适配器语法图像

时间:2015-07-23 19:33:40

标签: java android json listview android-adapter

我是Android开发的新手,我正在创建我的第一个应用程序。该应用程序拍照,预览该图片,从数据库中随机选择一张图片上传到服务器并在列表视图中显示JSON文本信息。

我正在尝试使用自定义列表视图适配器来允许JSON信息的相应图片位于LISTVIEW和NOT imageview中。

我已经彻底研究了listview适配器,以了解语法以及放置代码的位置,以便正确地使用图片实现listview。但是,我收到四条错误消息,阻止代码编译。我意识到在这个网站上还有其他关于类似主题的帖子,但我已经挖掘过它们并尝试实施状态解决方案但没有成功。

以下是我的代码:

public class JSONBuilderActivity extends ListActivity {

    private ProgressDialog pDialog;

    //URL to get JSON
    private static String url = ".........";

    //JSON Node names
    private static final String TAG_CARS = "cars";      //root
    private static final String TAG_CARID = "CarID";
    private static final String TAG_CARVIN = "CarVIN";
    private static final String TAG_IMG = "CarMainImage";
    CustomListViewAdapter adapter;

    JSONArray carid = null;  //Initializes JSON array

    private CustomListViewAdapter clva = null;
    ListView lv;
    List<Item> item = new ArrayList<JSONBuilderActivity.Item>();

    static String response = null;

    //Hashmap for ListView
    ArrayList<HashMap<String, Object>> caridList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        lv = getListView();
        //ArrayList<Item> item;

        lv.setAdapter(adapter);
        lv = (ListView) findViewById(R.id.list_item);
        adapter = new CustomListViewAdapter(this,item);
        lv.setAdapter(adapter);

        //Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

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

                //Gets values from selected ListItem
                String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
                String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
                String car_vin = ((TextView) view.findViewById(R.id.car_vin)).getText().toString();
                String model_img = ((ImageView) view.findViewById(R.id.model_img)).getTag().toString();

                Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
                //Sends data to MainActivity
                in.putExtra("TAG_CARS", cars);
                in.putExtra("TAG_CARID", car_id);
                in.putExtra("TAG_CarVin", car_vin);
                in.putExtra("TAG_IMG", model_img);
                startActivity(in);
            }
        });

        //Calls async task to get json
        new GetCars().execute();
    }

    public class ServiceHandler {

        public final static int GET = 1;
        public final static int POST = 2;

        public ServiceHandler() {

        }

        /**
         * Makes service call
         *
         * @url - url to make request
         * @method - http request method
         */
        public String makeServiceCall(String url, int method) {
            return this.makeServiceCall(url, method, null);
        }

        /**
         * Makes service call
         *
         * @url - url to make request
         * @method - http request method
         * @params - http request params
         */
        public String makeServiceCall(String url, int method, ArrayList<NameValuePair> params) {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpEntity httpEntity = null;
                HttpResponse httpResponse = null;

                //Checks http request method type
                if (method == POST) {
                    HttpPost httpPost = new HttpPost(url);

                    //Adds post params
                    if (params != null) {
                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                    }

                    httpResponse = httpClient.execute(httpPost);

                } else if (method == GET) {

                    //Appends params to url
                    if (params != null) {
                        String paramString = URLEncodedUtils.format(params, "utf-8");
                        url += "?" + paramString;
                    }
                    HttpGet httpGet = new HttpGet(url);

                    httpResponse = httpClient.execute(httpGet);
                }

                httpEntity = httpResponse.getEntity();
                response = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return response;

        }
    }

    public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "CarMainImage", null);
        return Uri.parse(path);
    }

    public void saveBmpToFile(File filename, Bitmap bmp) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filename);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public boolean renameFileExtension(String source, String newExtension) {
        String target;
        String currentExtension = getFileExtension(source);

        if (currentExtension.equals("")) {
            target = source + "." + newExtension;
        } else {
            target = source.replaceFirst(Pattern.quote("." +
                    currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));

        }
        return new File(source).renameTo(new File(target));
    }

    public String getFileExtension(String f) {
        String ext = "";
        int i = f.lastIndexOf('.');
        if (i > 0 && i < f.length() - 1) {
            ext = f.substring(i + 1);
        }
        return ext;
    }

    /*
     * Async task class to get json by making HTTP call
     */
    private class GetCars extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            caridList = new ArrayList<HashMap<String, Object>>();

            //Shows progress dialog
            pDialog = new ProgressDialog(JSONBuilderActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            //Creates service handler class instance
            ServiceHandler sh = new ServiceHandler();

            //Makes a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            //Prints the json response in the log
            Log.d("GetCars response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {

                    Log.d("try", "in the try");

                    JSONObject jsonObj = new JSONObject(jsonStr);
                    Log.d("jsonObject", "new json Object");

                    //Gets JSON Array node
                    carid = jsonObj.getJSONArray(TAG_CARS);
                    Log.d("json array", "user point array");

                    int len = carid.length();
                    Log.d("len", "get array length");

                    for (int i = 0; i < carid.length(); i++) {
                        JSONObject c = carid.getJSONObject(i);
                        String car_id = c.getString(TAG_CARID);
                        Log.d("car_id", car_id);

                        String car_vin = c.getString(TAG_CARVIN);
                        Log.d("car_vin", car_vin);

                        String model_img = c.getString(TAG_IMG);
                        Log.d("model_img", model_img);


                        //CustomListViewAdapter adapter = new CustomListViewAdapter(this, R.layout.list_item, item);

                        // String model_img = c.getString(TAG_IMG);
                        //Log.d("model_img", model_img);

                        //Hashmap for single match
                        HashMap<String, Object> matchGetCars = new HashMap<String, Object>();

                        //Adds each child node to HashMap key => value
                        matchGetCars.put(TAG_CARID, car_id);
                        matchGetCars.put(TAG_CARVIN, car_vin);
                        matchGetCars.put(TAG_IMG, model_img);
                        caridList.add(matchGetCars);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }


        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            //Dismisses the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            /**
             * Updates parsed JSON data into ListView
             * */
            //ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
            //      new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
            // setListAdapter(adapter);
            ListView lv = (ListView)findViewById(R.id.list_item);
            clva = new CustomListViewAdapter();
            lv.setAdapter(clva);
        }

    }

    public class CustomListViewAdapter extends ArrayAdapter<Item> {
        private ArrayList<Item> objitem;
        Activity context;

        public CustomListViewAdapter(ArrayList<Item> item, int ResourceId, Activity context){
            super(context, ResourceId, item);
            this.context = context;
            this.objitem = item;
        }


        private class ViewHolder {
            ImageView model_img;
            TextView car_id;
            TextView car_vin;
        }


        public View getView ( int position, View convertView, ViewGroup parent){
            ViewHolder holder = null;
            final Item item = getItem(position);
            LayoutInflater mInflater = (LayoutInflater) context
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item, null);
                holder.car_id = (TextView) convertView.findViewById(R.id.car_id);
                holder.car_vin = (TextView) convertView.findViewById(R.id.car_vin);
                holder.model_img = (ImageView) convertView.findViewById(R.id.model_img);

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

            holder.car_id.setText(item.getVin());
            holder.car_vin.setText(item.getId());
            holder.model_img.setImageResource(item.getmodelimg());

            return convertView;
        }

    }
    public class Item {
        private int model_img;
        private String car_id;
        private String car_vin;

        public Item(int model_img, String car_id, String car_vin) {
            this.model_img = model_img;
            this.car_id = car_id;
            this.car_vin = car_vin;
        }

        /* Getters
         */
        public int getmodelimg() {
            return model_img;
        }

        public String getVin() {
            return car_vin;
        }

        public String getId() {
            return car_id;
        }

            /* Setters
             */

        public void setmodelimg(int model_img) {
            this.model_img = model_img;
        }

        public void setVin(String car_vin) {
            this.car_vin = car_vin;
        }

        public void setId(String car_id) {
            this.car_id = car_id;
        }

    }
}

错误:

CustomListViewAdapter()无法应用于CustomListViewAdapter:  adapter = new CustomListViewAdapter(this,item);在onCreate

更新:  adapter = new CustomListViewAdapter(this,R.id.list_view,item);在onCreate。' 我仍然收到相同的(上面)错误。

进口:

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

我无法理解我所做的事情是如此不正确。我很感激任何意见。谢谢。

1 个答案:

答案 0 :(得分:1)

您正在尝试实例化具有此构造函数的适配器

public CustomListViewAdapter(ArrayList<Item> item, int ResourceId, Activity context)

虽然你这样称呼它

adapter = new CustomListViewAdapter(this,item);

问题:论点不匹配

应该是

adapter = new CustomListViewAdapter(item, R.layout.list_row, this);

请注意,list_row是我编写的,应该是应用程序或android sdk中的实际布局文件