Split()

时间:2017-10-18 03:42:28

标签: java android string split

嘿伙计们我正在为一项任务编写一个简单的待办事项列表应用程序。在我的应用程序中,单击listView项时发生错误。它应该打开一个对话框,我可以在其中编辑项目。但是,应用程序崩溃并显示此错误消息:

10-18 09:01:24.463 12767-12767/com.example.ayush.todolistapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.ayush.todolistapp, PID: 12767
                                                                           java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] java.lang.String.split(java.lang.String)' on a null object reference
                                                                               at com.example.ayush.todolistapp.MainActivity.fillReplaceDialog(MainActivity.java:140)
                                                                               at com.example.ayush.todolistapp.MainActivity$2.onItemClick(MainActivity.java:56)
                                                                               at android.widget.AdapterView.performItemClick(AdapterView.java:310)
                                                                               at android.widget.AbsListView.performItemClick(AbsListView.java:1147)
                                                                               at android.widget.AbsListView$PerformClick.run(AbsListView.java:3068)
                                                                               at android.widget.AbsListView$3.run(AbsListView.java:3916)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:152)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5497)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我无法找到问题的根源,所以如果有人可以帮助我,那将会非常有帮助。这是mainActivity文件:

    public class MainActivity extends AppCompatActivity {

    Dialog dialog;
    myDatabase database = new myDatabase(this);
    ArrayList<Data> list = new ArrayList<>();
    int numberOfItems = 0;
    ListView listView;
    EditText et1;
    EditText et2;
    DatePicker dp1;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        listView = (ListView) findViewById(R.id.mylist);
        list = database.returnProduct();
        CustomAdapter adapter = new CustomAdapter(MainActivity.this,list);
        listView.setAdapter(adapter);

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                database.setAsComplete(position);
                Toast.makeText(MainActivity.this, "Item saved as completed", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                fillReplaceDialog(position);
                String title = list.get(position).getTitle();
                String desc = list.get(position).getDescription();
                String final_date = list.get(position).getDueDate();
                String[] date = final_date.split("/");//here is where the error is occurring
                int day = Integer.parseInt(date[0]);
                int month = Integer.parseInt(date[1]);
                int year = Integer.parseInt(date[2]);
                et1.setText(title);
                et2.setText(desc);
                dp1.updateDate(year,month,day);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.completed_tasks){
            Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            startActivity(intent);
        }
        else if (id == R.id.add_items){
            fillDialog();
        }

        return super.onOptionsItemSelected(item);
    }

    public void fillDialog(){

        dialog = new Dialog(this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(R.layout.dialog_layout);
        dialog.show();
        Button bt_save= (Button) dialog.findViewById(R.id.button);
        listView = (ListView) findViewById(R.id.mylist);
        et1 = (EditText) dialog.findViewById(R.id.et_title);
        et2 = (EditText) dialog.findViewById(R.id.et_description);
        dp1= (DatePicker) dialog.findViewById(R.id.datePicker);
        bt_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = et1.getText().toString();
                String description = et2.getText().toString();
                int day = dp1.getDayOfMonth();
                int month = dp1.getMonth();
                int year = dp1.getYear();
                String final_date = day+"/"+month+"/"+year;
                database.insert_Data(title,description,final_date);
                numberOfItems+=1;
                dialog.dismiss();
                list = database.returnProduct();
                CustomAdapter adapter = new CustomAdapter(MainActivity.this,list);
                listView.setAdapter(adapter);
            }
        });
        Button bt_cancel = (Button) dialog.findViewById(R.id.button2);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //automatically dismisses the dialog on pressing the cancel button
                dialog.dismiss();
            }
        });
    }

    public void fillReplaceDialog(final int position){
        dialog = new Dialog(this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(R.layout.dialog_layout);
        dialog.show();
        Button bt_save= (Button) dialog.findViewById(R.id.button);
        listView = (ListView) findViewById(R.id.mylist);
        et1 = (EditText) dialog.findViewById(R.id.et_title);
        et2 = (EditText) dialog.findViewById(R.id.et_description);
        dp1= (DatePicker) dialog.findViewById(R.id.datePicker);
        bt_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = et1.getText().toString();
                String description = et2.getText().toString();
                int day = dp1.getDayOfMonth();
                int month = dp1.getMonth();
                int year = dp1.getYear();
                String final_date = day+"/"+month+"/"+year;
                database.replaceObject(title,description,final_date, position);
                dialog.dismiss();
                list = database.returnProduct();
                CustomAdapter adapter = new CustomAdapter(MainActivity.this,list);
                listView.setAdapter(adapter);
            }
        });
        Button bt_cancel = (Button) dialog.findViewById(R.id.button2);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //automatically dismisses the dialog on pressing the cancel button
                dialog.dismiss();
            }
        });
    }
}

数据类:

 public class Data {

    String title;
    String description;
    String dueDate;
    int status;

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getDueDate() {
        return dueDate;
    }

    public int getStatus() {
        return status;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setDueDate(String dueDate) {
        this.dueDate = dueDate;
    }

    public void setStatus(int status) {
        this.status = status;
    }
}

CustomAdapter类:

 public class CustomAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<Data> mData;
    LayoutInflater mInflator;

    public CustomAdapter(Context context, ArrayList<Data> list){
        mContext = context;
        mData = list;
        mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }


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

    @Override
    public Object getItem(int position) {

        return mData.get(position);
    }

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

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

        convertView = mInflator.inflate(R.layout.row_layout, parent, false);
        //inflates the layout
        TextView tv1 = (TextView) convertView.findViewById(R.id.textView);
        TextView tv2 = (TextView) convertView.findViewById(R.id.textView2);
        TextView tv3 = (TextView) convertView.findViewById(R.id.textView3);
        TextView header = (TextView) convertView.findViewById(R.id.header_title);
        ImageView iv1 = (ImageView) convertView.findViewById(R.id.imageView);
        tv1.setText(mData.get(position).getTitle());
        tv2.setText(mData.get(position).getDescription());
        tv3.setText(mData.get(position).getDueDate());
        iv1.setImageResource(R.drawable.incomplete);
        header.setText(mData.get(position).getDueDate());
        return convertView;
        //returns the view
    }
}

我只是一个初学者,并且最近才开始学习android编程,所以请原谅任何愚蠢的错误。提前致谢

3 个答案:

答案 0 :(得分:1)

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] java.lang.String.split(java.lang.String)' on a null object reference
  

当应用程序尝试使用时抛出NullPointerException   具有空值的对象引用。

问题来自

String final_date = list.get(position).getDueDate(); // At first value getting null
String[] date = final_date.split("/"); // Didn't find "/" in STRING that's why CRASHING .

FYI ,以 DEBUG 模式运行您的APP。你可以找到答案。

final_date null。您应该检查 STRING null 是否支持。

if (final_date != null && !final_date.isEmpty())
{
 String[] date = final_date.split("/");
  ........// Your code //............
}
else
{
  // Your String null ;
}

答案 1 :(得分:0)

尝试在控制台中打印值 final_date 。我认为getDueDate()返回null,即Item可能没有截止日期。

答案 2 :(得分:-2)

检查DateFormat是否为(&#34; dd / mm / yyyy&#34;)正确与否。 如果/在DateFormat中找不到,则final_date.split(&#34; /&#34;)不起作用。

你也可以得到这样的日,月,年。

  DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
  Date date = formatter.parse("10/18/2017");  
  int month = date.getMonth();
  int day= date.getDay();
  int year = date.getYear();