由于ID

时间:2018-01-22 21:03:41

标签: java android xml dynamic

我一直试图解决这个问题一段时间但似乎没有用。我在下面的代码块中的school.setClasses(classesName.getText().toString());行上获得了nullPointer异常。

实际发布到SQLite数据库的代码是什么

 public void postSchoolSetuptoSQLite() {

        school.setSchoolName(nameOfSchool.getText().toString());
        school.setSchoolLocation(schoolLocation.getText().toString());
        school.setClasses(classesName.getText().toString());
        academeaSQL.addSchool(school);

        if (demeaSQL != null) {
            StringBuilder sb = new StringBuilder();
            for (School s : demeaSQL.getAllSchools()) {
                sb.append(" SchoolName= " + s.getSchoolName() + " SchoolLocation= " + s.getSchoolLocation()
                        + " ClassName= " + s.getClasses());
                sb.append("\n");
            }
            Log.i("Database content", sb.toString());

            Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_LONG).show();

        } else {
            Log.i("Database Err", "Database Error");
        }



    }

我通过onAddField方法单击“添加新类”按钮动态创建classesName字段

public void onAddField(View v) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

         rowView = inflater.inflate(R.layout.field, null);

        rowView.setId(ViewIdGenerator.generateViewId());


        // Add the new row before the add field button.
        parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);

        Log.i("ids", String.valueOf(rowView.getId()));
    }

字段ID是通过ViewIdGenerator类动态生成的。

此代码块中动态创建的字段中获取ID时,此时出现错误classesName = rowView.findViewById(rowView.getId());

public void findByIds() {

        rowView = new View(this);

        parentLinearLayout = findViewById(R.id.parent_linear_layout);

        nameOfSchool = findViewById(R.id.nameOfSchool);

        schoolLocation = findViewById(R.id.schoolLocation);

        addSchoolAndMoveNext = findViewById(R.id.addSchoolAndMoveNext);


            classesName = rowView.findViewById(rowView.getId());

            Log.i("Classname", String.valueOf(classesName));
            Log.i("SchoolLoca", String.valueOf(schoolLocation));

    }

以下是我致电findByIds();

的地方
 @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_school_search_setup);

        findByIds();
        intitializeListeners();
        initializeObjects();





    }

对于Nullpointer例外。错误指向这些区域

school.setClasses(classesName.getText().toString());

classesName = rowView.findViewById(rowView.getId());

请问为什么我会得到nullpointer异常以及如何解决它。谢谢。我将非常感谢您的回复。

1 个答案:

答案 0 :(得分:0)

您的问题是,如果您在findByIds()内呼叫onCreate(),则rowView.getId()将返回null,因为您在按下按钮后在默认ID生成器中设置了ID。首次启动活动时会调用onCreate()

当您按下按钮时,您似乎也在尝试添加类列表。在Android中有一些内置的方法可以比你正在做的更多开销(在实现时间方面),但是对于滚动,添加新类,删除类,这将更加可靠。等

查看recyclerview以执行此操作

RecyclerView部分here中的显示光标内容将显示如何将数据从数据库添加到RecyclerView