繁体   English   中英

无法在自定义适配器中将EditText转换为TextView

[英]Cannot cast EditText into TextView in a custom adapter

我们目前正在开发一个项目,无法解决这个怪异的NullPointerException。 我们必须将特定的EditText转换为TextView才能使GridView正常工作。 现在的问题是,所有教程似乎都在使用Activity,而我们在使用Fragment。 我们的“ MainActivity”就在这里初始化一些启动器(启动画面,简介滑块等)。 所有其他内容都发生在我们的“ HomeFragment”中。 目的是捕获图片,写标题和一些内容,然后将其保存到SQLite数据库中,该数据库以后可用于在GridView中显示它。

我们使用了这个家伙(github)模板来创建我们自己的数据库(并重写了一些东西,因为我们正在使用Fragments)。

阅读代码时请耐心等待,它尚未最终确定。 大量垃圾代码仍在其中。

FragmentHome.class

public class FragmentHome extends Fragment {

private ImageButton mUnicornButton;
private ImageButton mBaseballbatButton;
private ImageButton mExplosionButton;
private ImageButton mCowButton;
private ImageButton mShitButton;
private ImageButton mPenguinButton;

private final int REQUEST_GALLERY_CODE = 999;

EditText edtTitle, edtContent;
Button btnAdd, btnChoose;

private ImageView mImageView;
protected View mView;

private static final int CAMERA_REQUEST = 1888;

public FragmentHome() {
    // Required empty public constructor
}

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


public static SQLiteHelper sqLiteHelper;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_home, container, false);
    this.mView = v;

    initUI(v);
    sqLiteHelper = new SQLiteHelper(getActivity().getApplicationContext(), "ListDB.sqlite",null,1);
    sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS DBLIST(Id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, content VARCHAR, image BLOB)");

    btnChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_GALLERY_CODE);
        }
    });
    Button photoButton = v.findViewById(R.id.add_foto);
    photoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try{
                sqLiteHelper.insertData(
                        edtTitle.getText().toString().trim(),
                        edtContent.getText().toString().trim(),
                        imageViewToByte(mImageView)
                        );
                Toast.makeText(getActivity().getApplicationContext(),"Added",Toast.LENGTH_SHORT).show();
                edtTitle.setText("");
                edtContent.setText("");
                mImageView.setImageResource(R.mipmap.ic_launcher_round);

            } catch(Exception e){
                e.printStackTrace();
            }
        }
    });



    return v;
}

private byte[] imageViewToByte(ImageView image) {
    Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG,0,stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
    if(requestCode == REQUEST_GALLERY_CODE){
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_GALLERY_CODE);
        }
        else {
            Toast.makeText(getActivity().getApplicationContext(),"No Permissions",Toast.LENGTH_SHORT).show();
        }
        return;
    }
    super.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == CAMERA_REQUEST){
        if(resultCode == Activity.RESULT_OK){
            Bitmap bmp = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);

            mImageView.setImageBitmap(bitmap);
        }
    }
}

private void initUI(View v) {

  [...] //initializes everything using findViewById()
}

}

DBListAdapter.class(我们的自定义适配器)

public class DBListAdapter extends BaseAdapter{

private Context context;
private int layout;
private ArrayList<DBList> dblistsList;

public DBListAdapter(Context context, int layout, ArrayList<DBList> dblistsList) {
    this.context = context;
    this.layout = layout;
    this.dblistsList = dblistsList;
}

@Override
public int getCount() {
    return dblistsList.size();
}

@Override
public Object getItem(int position) {
    return dblistsList.get(position);
}

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


private class ViewHolder{
    ImageView imageView;
    TextView txtTitle, txtContent;
}


@Override
public View getView(int position, View view, ViewGroup viewGroup) {

    View row = view;
    ViewHolder holder = new ViewHolder();
    if(row==null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(layout, null);

        holder.txtTitle = row.findViewById(R.id.input_title);
        holder.txtContent = row.findViewById(R.id.input_content);
        holder.imageView = row.findViewById(R.id.fotoView);
        row.setTag(holder);
    }
    else{
        holder = (ViewHolder) row.getTag();

    }

    DBList dbList = dblistsList.get(position);

    holder.txtTitle.setText(dbList.getTitle());
    holder.txtContent.setText(dbList.getContent());

    byte[] dblistImage = dbList.getImage();
    Bitmap bitmap = BitmapFactory.decodeByteArray(dblistImage, 0, dblistImage.length);

    holder.imageView.setImageBitmap(bitmap);
    return row;
}
}

问题出在此适配器中。

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at s***.d***.u***.th***ive.DBListAdapter.getView(DBListAdapter.java:78)

我们无法弄清楚如何将EditText从fragment_home.xml强制转换为TextView,这是ViewHolder所需的。

fragment_home.xml

[...]
<ImageView
    android:id="@+id/fotoView"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="@color/Gainsboro"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<EditText
    android:id="@+id/input_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Title"
    android:inputType="text"
    android:maxLines="1"
    android:textAlignment="center"
    android:layout_above="@+id/input_content"
    android:layout_alignParentStart="true" />

<EditText
    android:id="@+id/input_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_what"
    android:inputType="textMultiLine"
    android:textAlignment="center"
    android:layout_above="@+id/linearLayout"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="33dp" /> [...]

任何帮助将不胜感激,我的头脑现在正在燃烧,我当然不知道如何解决这个问题。 如果您需要更多,请问我。 Kinda现在很累,因此可能会重播。

okey ..首先,您需要创建一个新的xml文件并根据需要命名它。...假设它的名称是list_reycle_view,然后将这些视图传输到该文件。

<ImageView
    android:id="@+id/fotoView"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="@color/Gainsboro"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<EditText
    android:id="@+id/input_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Title"
    android:inputType="text"
    android:maxLines="1"
    android:textAlignment="center"
    android:layout_above="@+id/input_content"
    android:layout_alignParentStart="true" />

<EditText
    android:id="@+id/input_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_what"
    android:inputType="textMultiLine"
    android:textAlignment="center"
    android:layout_above="@+id/linearLayout"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="33dp" />

然后..替换这些行

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    row = inflater.inflate(layout, null);

用这条线

row= LayoutInflater.from(context).inflate(R.layout.list_recycle_view,viewGroup,false);

并运行您的程序

ViewHolder holder = null;
if (row == null) {
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    row = inflater.inflate(layout, null);
    holder = new ViewHolder();
    holder.txtTitle = row.findViewById(R.id.input_title);
    holder.txtContent = row.findViewById(R.id.input_content);
    holder.imageView = row.findViewById(R.id.fotoView);
    row.setTag(holder);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM