如何在不使用数据库的情况下将项目添加到Listview?

时间:2019-07-04 03:26:15

标签: android listview

我已经竭尽全力了,但是似乎找不到答案。因此,我们的讲师告诉我们不要使用数据库。因此,该应用程序就像填写表格一样,要求您提供图片,姓氏,名字和课程,然后将其显示在列表视图中,这是另一项活动。

如何在不使用数据库的情况下执行此操作?谢谢!请在下面查看我的代码:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ArrayList<Student> studentArrayList = new ArrayList<Student>();
    StudentAdapter studentAdapter;
    ListView listView;


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

        listView = (ListView) findViewById(R.id.listview);

        studentAdapter = new StudentAdapter(this, studentArrayList);
        listView.setAdapter(studentAdapter);
    }


    //back button
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if(id == android.R.id.home){
            onBackPressed();
            return true;
        }else if(id == R.id.action_add){
            Intent add = new Intent(MainActivity.this, AddStudentActivity.class);
            startActivity(add);
        }
        return super.onOptionsItemSelected(item);
    }

    //show add menu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_menu, menu);
        return true;
    }

StudentAdapter.java

    Context context;
    ArrayList<Student> studentArrayList;
    LayoutInflater inflater;

    //contructor


    public StudentAdapter(Context context, ArrayList<Student> studentArrayList) {
        this.context = context;
        this.studentArrayList = studentArrayList;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if(convertView == null){
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.custom_layout, parent, false);
            holder.image = (ImageView) convertView.findViewById(R.id.imageView);
            holder.lname = (TextView) convertView.findViewById(R.id.textLName);
            holder.fname = (TextView) convertView.findViewById(R.id.textFName);
            holder.course = (TextView) convertView.findViewById(R.id.textCourse);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }
        //
        holder.image.setImageResource(studentArrayList.get(position).getImage());
        holder.lname.setText(studentArrayList.get(position).getLname());
        holder.fname.setText(studentArrayList.get(position).getFname());
        holder.course.setText(studentArrayList.get(position).getCourse());

        return convertView;
    }

    private static class ViewHolder{
        ImageView image;
        TextView lname, fname, course;
    }

AddStudentActivity.java

    ImageView studentImage;
    EditText studLname, studFname;
    Button btnSave, btnCancel;
    Spinner cboCourse;
    String selectedCourse;
    Uri imageUri;
    private static final int PICK_IMAGE = 100;
    ArrayList<Student> studentArrayList = new ArrayList<Student>();
    StudentAdapter studentAdapter;

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

        //
        studentImage = (ImageView) findViewById(R.id.imageView2);
        studLname = (EditText) findViewById(R.id.editText1);
        studFname = (EditText) findViewById(R.id.editText2);
        cboCourse = (Spinner) findViewById(R.id.spinner);
        btnSave = (Button) findViewById(R.id.btnsave);
        btnCancel = (Button) findViewById(R.id.btncancel);

        cboCourse.setOnItemSelectedListener(this);
        studentImage.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

    }


    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Unsaved Changes");
        builder.setMessage("Are you sure you want to leave?");
        builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if(id == android.R.id.home){
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id){
            case R.id.imageView2:
                Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery, PICK_IMAGE);
                break;
            case R.id.btnsave:
                if(studLname.equals("") || studFname.equals("") || cboCourse.getSelectedItem().equals(0)){
                    Toast.makeText(getApplicationContext(), "Fields can not be empty!", Toast.LENGTH_SHORT).show();
                }else{
                    //add a statement to add an item here
                studentArrayList.add(studentImage.getResources().toString(), studLname.getText().toString(), studFname.getText().toString(), cboCourse.getSelectedItem());

//                    studentArrayList.add(studentImage.getBaseline(), studLname.getText().toString(), studFname.getText().toString(), cboCourse.getSelectedItem().toString());
                    Toast.makeText(getApplicationContext(), "Item successfully added!", Toast.LENGTH_SHORT).show();
                    Intent home = new Intent(AddStudentActivity.this, MainActivity.class);
                    startActivity(home);
                    studentAdapter.notifyDataSetChanged();
                }
                break;
            case R.id.btncancel:
                studLname.setText("");
                studFname.setText("");
                break;
        }
    }

    //handles opening the camera

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
            imageUri = data.getData();
            studentImage.setImageURI(imageUri);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //for the spinner
        int sid = parent.getId();

        switch (sid){
            case R.id.spinner:
                selectedCourse = this.cboCourse.getItemAtPosition(position).toString();
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

Student.java

package com.example.studentinfoapplication;

import java.io.Serializable;

public class Student implements Serializable {

    private int image;
    private String lname, fname, course;

    public int getImage() {
        return image;
    }

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

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }
}

2 个答案:

答案 0 :(得分:1)

学生班

我向您的学生班级添加了一个全局数组列表。

any

MainActivity

public class Student implements Serializable {

public static ArrayList<Student> studentArrayList = new ArrayList<>();

   private Uri image;
   private String lname, fname, course;

   public Student(){      //Add your constructor.

   }

}

AddStudentActivity

public class MainActivity extends AppCompatActivity {

StudentAdapter studentAdapter;
ListView listView;


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

    listView = (ListView) findViewById(R.id.listview);

    Log.d("test", "students" + Student.studentArrayList);

    if (Student.studentArrayList != null) {
        studentAdapter = new StudentAdapter(this, Student.studentArrayList);
        listView.setAdapter(studentAdapter);
    }
}

在顶部删除此行,因为我们指的是Student类中的全局数组列表。

 ArrayList<Student> studentArrayList = new ArrayList<Student>();

StudentAdapter

@Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id){
            case R.id.imageView2:
                Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery, PICK_IMAGE);
                break;
            case R.id.btnsave:
                if(!studLname.equals("") || !studFname.equals("") || !cboCourse.getSelectedItem().equals(0)){

                    String lname = studLname.getText().toString();
                    String fname = studFname.getText().toString();
                    String course = cboCourse.getSelectedItem().toString();

                    student.setLname(lname);
                    student.setFname(fname);
                    student.setCourse(course);

                    Student.studentArrayList.add(student); //Global arraylist

                    Log.d("test", "students:" + Student.studentArrayList);

                    Toast.makeText(getApplicationContext(), "Item successfully added!", Toast.LENGTH_SHORT).show();
                    Intent home = new Intent(AddStudentActivity.this, MainActivity.class);
                    startActivity(home);
                }else{
                    Toast.makeText(getApplicationContext(), "Fields can not be empty!", Toast.LENGTH_SHORT).show();

                }
                break;
            case R.id.btncancel:
                studLname.setText("");
                studFname.setText("");
                cboCourse.setSelection(0);
                break;
        }
    }

   @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
        if (data != null) {
            imageUri = data.getData();
        }
        student.setImage(imageUri);
        studentImage.setImageURI(imageUri);
    }
}

答案 1 :(得分:0)

您可以尝试几种方法 a)创建单例课程并维护您添加的学生列表,然后在mainactivity中使用相同的单例对象填充列表。

b)创建具有学生列表的可序列化/可分词模型,每次添加学生并将此列表发送到主要活动,反之亦然,以使用相同的模型进行两个活动。这只是解决方法。我会喜欢第一个。