简体   繁体   中英

Cannot cast EditText into TextView in a custom adapter

we're currently working on a project and can't get through this weird NullPointerException. We have to cast a specific EditText into a TextView to get our GridView to work. Problem right now is that all tutorials seem to use an Activity, while we're using a Fragment. Our "MainActivity" is just here to initilize some starter things (Splash Screen, Intro Slider etc.). All the other stuff happens in our "HomeFragment". The goal is to capture a picture, write a title and some content, and then save it into a SQLite Database, which can be used to show it in a GridView later on.

We used this guys(github) template to create our own db (and rewrote some stuff because we're using Fragments, of course).

Bear with us while reading the code, it is not finalized yet. Tons of junk code still inside.

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 (our custom adapter)

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;
}
}

The problem is in this Adapter.

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)

We can't figure out how to cast the EditText from the fragment_home.xml into a TextView, which is needed for the 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" /> [...]

Any help would be appreciated, my mind is burning right now, I certaintly have no clue how to solve this. If you need more, just ask me. Kinda tired right now, so probably gonna replay late.

okey .. Firstly you need to create new xml file and name it as you want ... let assume that it's name is list_reycle_view then transfer those views to it

<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" />

then .. replace these lines

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

with this line

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

and run your program

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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