无法在自定义适配器

时间:2017-08-31 01:07:23

标签: java android sqlite android-fragments casting

我们目前正在开发一个项目,无法通过这个奇怪的NullPointerException。我们必须将特定的EditText转换为TextView以使我们的GridView工作。现在的问题是所有教程似乎都使用了Activity,而我们正在使用Fragment。我们的“MainActivity”就是为了启动一些初学者(Splash Screen,Intro Slider等)。所有其他的东西都发生在我们的“HomeFragment”中。目标是捕获图片,编写标题和一些内容,然后将其保存到SQLite数据库中,以后可以在GridView中显示它。

我们使用this guys(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转换为ViewHolder所需的TextView。

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" /> [...]

任何帮助都会受到赞赏,我的脑子现在正在燃烧,我肯定不知道如何解决这个问题。如果您需要更多,请问我。有点现在累了,所以可能会重播很晚。

2 个答案:

答案 0 :(得分:0)

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

并运行您的程序

答案 1 :(得分:0)

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