无法将String转换为我的列表对象

时间:2016-05-12 07:10:20

标签: android listview arraylist android-arrayadapter

在我的适配器类中的这一行:ListItemsModel listItem = getItem(position);,我得到了转换错误。

非常奇怪的错误,考虑到我根本没有向我的String对象投射ListItemsModel。实际上这段代码运行得很好,然后我更新了我的启动器图标(无关),现在我收到了这个错误。有任何想法吗?感谢。

MainListActivity

package org.azurespot.nonigrocerylist;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class MainListActivity extends AppCompatActivity {
    private ArrayList<ListItemsModel> itemsList = new ArrayList<>();
    private ListViewItemAdapter itemsAdapter;
    private ListView itemsView;
    EditText newItemET;

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

        newItemET = (EditText)findViewById(R.id.etNewItem);
        // read items that were persisted in list, before adapter is created with the list
        readItems();
        itemsAdapter = new ListViewItemAdapter(MainListActivity.this, itemsList);
        itemsView = (ListView) findViewById(R.id.lvItems);

        itemsView.setAdapter(itemsAdapter);

        setUpListDetailsClickListener();
        setupDeleteItemClickListener();
    }

    // Enables a listener, to go to list details activity
    public void setUpListDetailsClickListener(){
        itemsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                if (itemsView.getItemAtPosition(position) != null) {
                    Intent intent = new Intent(MainListActivity.this, ListItemActivity.class);
                    intent.putExtra("item name", itemsView.getItemAtPosition(position).toString());
                    startActivity(intent);
                } else {
                    Toast.makeText(MainListActivity.this, "Add item to list.",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // Adds item to list
    public void addItem(View v) {
        if (!newItemET.getText().toString().equals("")) {
            ListItemsModel item = new ListItemsModel(newItemET.getText().toString(), 1);
            itemsAdapter.add(item);
            newItemET.setText("");
            writeItems();

        }
            // soft keyboard down
            InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.hideSoftInputFromWindow(newItemET.getWindowToken(), 0);
    }

    // Enables listener to delete item
    private void setupDeleteItemClickListener() {
        itemsView.setOnItemLongClickListener(
                new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> adapter,
                                                   View item, int pos, long id) {
                        // Remove the item within array at position
                        itemsList.remove(pos);
                        // Refresh the adapter
                        itemsAdapter.notifyDataSetChanged();
                        writeItems();
                        // Return true consumes the long click event (marks it handled)
                        return true;
                    }

                });
    }

    // Reads list from file (saved)
    private void readItems() {
        File filesDir = getFilesDir();
        File groceryFile = new File(filesDir, "grocery.txt");
        try {
            itemsList = new ArrayList<ListItemsModel>(FileUtils.readLines(groceryFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Writes new items to list (saves it), or refreshes after delete item
    private void writeItems() {
        File filesDir = getFilesDir();
        File groceryFile = new File(filesDir, "grocery.txt");
        try {
            FileUtils.writeLines(groceryFile, itemsList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ListViewItemAdapter

package org.azurespot.nonigrocerylist;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;

import java.util.ArrayList;

/**
 * Created by mizu on 5/11/16.
 */
public class ListViewItemAdapter extends ArrayAdapter<ListItemsModel> {


    public ListViewItemAdapter(Context context, ArrayList<ListItemsModel> items){
        super(context, 0, items);
    }

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


        ListItemsModel listItem = getItem(position);

        if(row == null) {
            row = LayoutInflater.from(getContext())
                                .inflate(R.layout.list_row, parent, false);

            holder = new ViewHolder();
            holder.checkBox = (CheckBox)row.findViewById(R.id.checkBox);
            holder.itemTitleET = (EditText)row.findViewById(R.id.listItem);
            holder.itemQtyET = (EditText)row.findViewById(R.id.itemQty);

            row.setTag(holder);
        }
        else {
            holder = (ViewHolder)row.getTag();
        }

        holder.itemTitleET.setText(listItem.getTitle());
        // setText() only accepts Strings
        holder.itemQtyET.setText(String.valueOf(listItem.getQty()));

        return row;
    }

    static class ViewHolder {
        CheckBox checkBox;
        EditText itemTitleET;
        EditText itemQtyET;
    }
}

ListItemsModel

package org.azurespot.nonigrocerylist;

/**
 * Created by mizu on 5/11/16.
 */
public class ListItemsModel {


    private String title;
    private int qty = 0;

    public ListItemsModel(String t, int q){
        this.title = t;
        this.qty = q;
    }

    public ListItemsModel(String t){
        this.title = t;
    }

    public String getTitle(){
        return title;
    }

    public void setTitle(String title){
        this.title = title;
    }

    public int getQty(){
        return qty;
    }

    public void setQty(int qty){
        this.qty = qty;
    }
}

logcat的

05-12 00:03:30.972 28958-28958/org.azurespot.nonigrocerylist E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: org.azurespot.nonigrocerylist, PID: 28958
                                                                               java.lang.ClassCastException: java.lang.String cannot be cast to org.azurespot.nonigrocerylist.ListItemsModel
                                                                                   at org.azurespot.nonigrocerylist.ListViewItemAdapter.getView(ListViewItemAdapter.java:29)
                                                                                   at android.widget.AbsListView.obtainView(AbsListView.java:2842)
                                                                                   at android.widget.ListView.measureHeightOfChildren(ListView.java:1290)
                                                                                   at android.widget.ListView.onMeasure(ListView.java:1202)
                                                                                   at android.view.View.measure(View.java:18425)
                                                                                   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
                                                                                   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
                                                                                   at android.view.View.measure(View.java:18425)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5802)
                                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                   at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                   at android.view.View.measure(View.java:18425)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5802)
                                                                                   at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
                                                                                   at android.view.View.measure(View.java:18425)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5802)
                                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                   at android.view.View.measure(View.java:18425)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5802)
                                                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1835)
                                                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:725)
                                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:616)
                                                                                   at android.view.View.measure(View.java:18425)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5802)
                                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                                   at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2881)
                                                                                   at android.view.View.measure(View.java:18425)
                                                                                   at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2241)
                                                                                   at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1295)
                                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1537)
                                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1180)
                                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6563)
                                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
                                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:590)
                                                                                   at android.view.Choreographer.doFrame(Choreographer.java:560)
                                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:145)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5835)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

2 个答案:

答案 0 :(得分:1)

试试这个,

public class ListViewItemAdapter extends ArrayAdapter<ListItemsModel> {

 ArrayList<ListItemsModel> items;
    public ListViewItemAdapter(Context context, ArrayList<ListItemsModel> items){
        super(context, 0, items);
        this.items=items;
    }

    @Override
    public ListItemsModel getItem(int position) {
        return items.get(position);
    }

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


        ListItemsModel listItem = getItem(position);

        if(row == null) {
            row = LayoutInflater.from(getContext())
                                .inflate(R.layout.list_row, parent, false);

            holder = new ViewHolder();
            holder.checkBox = (CheckBox)row.findViewById(R.id.checkBox);
            holder.itemTitleET = (EditText)row.findViewById(R.id.listItem);
            holder.itemQtyET = (EditText)row.findViewById(R.id.itemQty);

            row.setTag(holder);
        }
        else {
            holder = (ViewHolder)row.getTag();
        }

        holder.itemTitleET.setText(listItem.getTitle());
        // setText() only accepts Strings
        holder.itemQtyET.setText(String.valueOf(listItem.getQty()));

        return row;
    }

    static class ViewHolder {
        CheckBox checkBox;
        EditText itemTitleET;
        EditText itemQtyET;
    }
}

答案 1 :(得分:0)

尝试我的CustomListView示例而不使用@Override getItem()。

  

MainActivity.java

package listview.customlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

String m_txt[] = {"one" , "two" , "three" , "four", "five"};
int m_img [] = {R.drawable.ic_launcher ,
        R.drawable.ic_launcher ,
        R.drawable.ic_launcher ,
        R.drawable.ic_launcher ,
        R.drawable.ic_launcher};

ListView m_list;
List<RowItem> rowItems;

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

    m_list = (ListView)findViewById(R.id.lv_items);

    rowItems = new ArrayList<RowItem>();
    for (int i = 0; i < m_txt.length; i++) {
        RowItem item = new RowItem(m_img[i],m_txt[i]);
        rowItems.add(item);
    }

    CustomListViewAdapter adapter = new CustomListViewAdapter(this,
            R.layout.listitem, rowItems);
    m_list.setAdapter(adapter);
    m_list.setOnItemClickListener(MainActivity.this);

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
    Toast toast = Toast.makeText(getApplicationContext(),
            "Item " + (position) + ": " + rowItems.get(position).getTxt(),
            Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    toast.show();

}
}
  

CustomListViewAdapter

package listview.customlistview;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CustomListViewAdapter extends ArrayAdapter<RowItem> {

Context context;

public CustomListViewAdapter(Context context, int resourceId,
                             List<RowItem> items) {
    super(context, resourceId, items);
    this.context = context;
}

/*private view holder class*/
private class ViewHolder {
    ImageView m_pic;
    TextView m_title;
    Button m_btn;
}

public View getView(final int position, View convertView, ViewGroup parent)    {
    ViewHolder holder = null;
    RowItem rowItem = getItem(position);

    LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
    {
        convertView = mInflater.inflate(R.layout.listitem, null);
        holder = new ViewHolder();
        holder.m_title = (TextView) convertView.findViewById(R.id.m_textview);
        holder.m_btn = (Button)convertView.findViewById(R.id.m_buttonview);
        holder.m_pic = (ImageView) convertView.findViewById(R.id.m_imageview);

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

    holder.m_title.setText(rowItem.getTxt());

    holder.m_pic.setImageResource(rowItem.getImage());

   holder.m_btn.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {

           Toast.makeText(context, position + " clicked" , Toast.LENGTH_LONG).show();
       }
   });

    return convertView;
}
}
  

RowItem

package listview.customlistview;


public class RowItem {

private int image;
private String txt;

public RowItem(int imageview , String textview)
{
    this.image = imageview;
    this.txt = textview;
}


public int getImage() {
    return image;
}

public String getTxt() {
    return txt;
}

public void setImage(int image) {
    this.image = image;
}

public void setTxt(String txt) {
    this.txt = txt;
}
}

检查我的适配器类构造函数

这可能对你有所帮助。