仅在onCreate值上进行分配

时间:2013-04-08 04:56:24

标签: java android

在我的代码中,我为两个数据选择器和lisner设置了列表,用于提交。当我运行应用程序时,我第一次可以使用数据选择器分配值但是当我第二次尝试时,不会发生值分配。我的代码出了什么问题?

public class MainActivity extends Activity {

    private GraphicalView mChart;
    // private DatePicker dpResult;
    private Button submit;
    private Button btnChangeDate;
    private Button btnChangeDatetwo;
    static final int DATE_DIALOG_ID = 100;
    static final int DATE_DIALOG_ID_TWO = 101;
    private int year;
    private int month;
    private int day;
    private int year_end;
    private int month_end;
    private int day_end;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);
        // openChart();
        // openCharttwo();
        //openChartthree();

        addListenerOnButton();// listeners for calender events
        addListenerOnButtontwo();
        addListnerOnSubmitButton();


    }



    private void openChartthree(Date startdateValue,Date enddateValue) {
        String val;
        // Date[] val2 = null;//this holds dates
        String val3;
        String val32;
        String val33;
        String val34;

        // Date[] date;
        // Date[] datearray = null;

        /*
         * GregorianCalendar startdate = new GregorianCalendar(2011,11,28,
         * 0,00); GregorianCalendar enddate = new GregorianCalendar(2012,3,4,
         * 0,00);
         */



        val = this.getString(R.string.dateCollection);
        val3 = this.getString(R.string.values);
        val32 = this.getString(R.string.values2);// second graph
        val33 = this.getString(R.string.values3);// third graph
        val34 = this.getString(R.string.values4);// fourth chart

        String[] newdate = val.split(",");

        String[] values = val3.split(",");
        String[] values2 = val32.split(",");// spliting second values
        String[] values3 = val33.split(",");// spliting third values
        String[] values4 = val34.split(",");// spliting fourth values

        Double[] results = new Double[values.length];
        Double[] results2 = new Double[values.length];// saving second values
                                                        // array in int array
        Double[] results3 = new Double[values.length];// saving third values
                                                        // array in int array
        Double[] results4 = new Double[values.length];// saving third values
                                                        // array in int array
        // converting string to integers
        // int[] results2 = results;

        for (int i = 0; i < values.length; i++) {
            try {
                // String temp = values[0];
                // int itest = Integer.parseInt(temp);
                results[i] = Double.parseDouble(values[i]);
                results2[i] = Double.parseDouble(values2[i]);
                results3[i] = Double.parseDouble(values3[i]);
                results4[i] = Double.parseDouble(values4[i]);

            } catch (NumberFormatException nfe) {
            }
            ;
        }

        // Creating TimeSeries for Visits
        TimeSeries visitsSeries = new TimeSeries("Upper band");

        // Creating TimeSeries for Views
        TimeSeries viewsSeries = new TimeSeries("Price");

        // Creating TimeSeries for Views2
        TimeSeries viewsSeries2 = new TimeSeries("Lower band");

        // Creating TimeSeries for products
        TimeSeries products = new TimeSeries("Moving Average");

        // Adding data to Visits and Views Series

        for (int i = 0; i < newdate.length; i++) {
            try {
                // String dt = newdate[i];

                // Date datePointer = new SimpleDateFormat("yyyy/MM/dd",
                // Locale.ENGLISH).parse(dt);
                SimpleDateFormat formatter = new SimpleDateFormat(
                        "MM/dd/yyyy k:mm");
                Date datePointer = formatter.parse(newdate[i]);

                if (startdateValue.before(datePointer)
                        && enddateValue.after(datePointer)) {
                    visitsSeries.add(datePointer, results[i]);
                    viewsSeries.add(datePointer, results2[i]);
                    viewsSeries2.add(datePointer, results3[i]);
                    products.add(datePointer, results4[i]);
                }
            } catch (Exception e) {

            }

        }

        // Creating a dataset to hold each series
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

        // Adding Visits Series to the dataset
        dataset.addSeries(visitsSeries);

        // Adding Visits Series to dataset
        dataset.addSeries(viewsSeries);

        // Adding Visits Series to dataset
        dataset.addSeries(viewsSeries2);

        // Adding products Series to dataset
        dataset.addSeries(products);

        // Creating XYSeriesRenderer to customize productsSeries
        XYSeriesRenderer productsRenderer = new XYSeriesRenderer();
        productsRenderer.setColor(Color.GREEN);
        productsRenderer.setPointStyle(PointStyle.POINT);
        productsRenderer.setFillPoints(true);
        productsRenderer.setLineWidth(1);
        productsRenderer.setDisplayChartValues(true);

        // Creating XYSeriesRenderer to customize visitsSeries
        XYSeriesRenderer visitsRenderer = new XYSeriesRenderer();
        visitsRenderer.setColor(Color.RED);
        // visitsRenderer.setPointStyle(PointStyle.);
        visitsRenderer.setFillPoints(true);
        visitsRenderer.setLineWidth(1);
        visitsRenderer.setDisplayChartValues(true);

        // Creating XYSeriesRenderer to customize viewsSeries
        XYSeriesRenderer viewsRenderer = new XYSeriesRenderer();
        viewsRenderer.setColor(Color.WHITE);
        // viewsRenderer.setPointStyle(PointStyle.CIRCLE);
        viewsRenderer.setFillPoints(true);
        viewsRenderer.setLineWidth(1);
        viewsRenderer.setDisplayChartValues(true);

        // Creating XYSeriesRenderer to customize viewsSeries
        XYSeriesRenderer viewsRenderer2 = new XYSeriesRenderer();
        viewsRenderer2.setColor(Color.BLUE);
        // viewsRenderer2.setPointStyle(PointStyle.CIRCLE);
        viewsRenderer2.setFillPoints(true);
        viewsRenderer2.setLineWidth(1);
        viewsRenderer2.setDisplayChartValues(true);

        // Creating a XYMultipleSeriesRenderer to customize the whole chart
        XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();

        // multiRenderer.setChartTitle("Visits vs Views Chart");
        multiRenderer.setXTitle("Days");
        multiRenderer.setYTitle("Count");
        multiRenderer.setZoomButtonsVisible(true);

        // Adding visitsRenderer and viewsRenderer to multipleRenderer
        // Note: The order of adding dataseries to dataset and renderers to
        // multipleRenderer
        // should be same
        multiRenderer.addSeriesRenderer(visitsRenderer);
        multiRenderer.addSeriesRenderer(viewsRenderer);
        multiRenderer.addSeriesRenderer(viewsRenderer2);
        multiRenderer.addSeriesRenderer(productsRenderer);
        // Getting a reference to LinearLayout of the MainActivity Layout
        LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);

        // Creating a Time Chart
        mChart = (GraphicalView) ChartFactory.getTimeChartView(
                getBaseContext(), dataset, multiRenderer, "dd-MMM-yyyy");

        multiRenderer.setClickEnabled(true);
        multiRenderer.setSelectableBuffer(10);

        // Setting a click event listener for the graph
        mChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Format formatter = new SimpleDateFormat("dd-MMM-yyyy");

                SeriesSelection seriesSelection = mChart
                        .getCurrentSeriesAndPoint();

                if (seriesSelection != null) {
                    int seriesIndex = seriesSelection.getSeriesIndex();
                    String selectedSeries = "Visits";

                    if (seriesIndex == 0)
                        selectedSeries = "Lower bound ";
                    else if (seriesIndex == 1)
                        selectedSeries = "Upperbound";
                    else
                        selectedSeries = "Price";
                    // Getting the clicked Date ( x value )

                    long clickedDateSeconds = (long) seriesSelection
                            .getXValue();
                    Date clickedDate = new Date(clickedDateSeconds);
                    String strDate = formatter.format(clickedDate);

                    // Getting the y value
                    int amount = (int) seriesSelection.getValue();

                    // Displaying Toast Message
                    Toast.makeText(getBaseContext(),
                            selectedSeries + " on " + strDate + " : " + amount,
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Adding the Line Chart to the LinearLayout
        chartContainer.addView(mChart);

        // Toast.makeText(getApplicationContext(), "msg"+newdate,
        // Toast.LENGTH_LONG).show();

    }

    // //////////////////////////////////////////////////////////opencart two
    // ////////////////////////////////

    // ////////////////////////////////////////date selecting code starts from
    // here/////////////////////////////////////////////////////////////////////
    // user can select start and end date via dialog box calender view

    public void addListenerOnButtontwo() {
        final Calendar c = Calendar.getInstance();
        year_end = c.get(Calendar.YEAR);
        month_end = c.get(Calendar.MONTH);
        day_end = c.get(Calendar.DAY_OF_MONTH);

        btnChangeDatetwo = (Button) findViewById(R.id.endate);

        btnChangeDatetwo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(DATE_DIALOG_ID_TWO);
            }
        });

    }

    public void addListenerOnButton() {

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        btnChangeDate = (Button) findViewById(R.id.startdate);

        btnChangeDate.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showDialog(DATE_DIALOG_ID);
            }
        });

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:

            // set date picker as current date
            return new DatePickerDialog(this, datePickerListener, year, month,day);
        case DATE_DIALOG_ID_TWO:

            return new DatePickerDialog(this, datePickerListener_end, year_end, month_end, day_end);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth +1;
            day = selectedDay;

            // set selected date into textview
            // tvDisplayDate.setText(new StringBuilder().append(month + 1)
            // .append("-").append(day).append("-").append(year)
            // .append(" "));

            Toast.makeText(getApplicationContext(),
                    "msg  " + year + "-" + month + "-" + day,
                    Toast.LENGTH_SHORT).show();

        }
    };
    private DatePickerDialog.OnDateSetListener datePickerListener_end = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year_end = selectedYear;
            month_end = selectedMonth+1;
            day_end = selectedDay;

            // set selected date into textview
            // tvDisplayDate.setText(new StringBuilder().append(month + 1)
            // .append("-").append(day).append("-").append(year)
            // .append(" "));

            // set selected date into datepicker also
            // dpResult.init(year, month, day, null);
            Toast.makeText(getApplicationContext(),
                    "msg" + year_end + "-" + month_end + "-" + day_end,
                    Toast.LENGTH_SHORT).show();
        }
    };

    public void addListnerOnSubmitButton() {
        addListenerOnButton();// listeners for calender events
        addListenerOnButtontwo();

        submit = (Button) findViewById(R.id.button1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                StringBuilder sb = new StringBuilder();
                sb.append(year);
                sb.append("/");
                sb.append(month);
                sb.append("/");
                sb.append(day);
                String start=sb.toString();

                StringBuilder sb2 = new StringBuilder();
                sb.append(year_end);
                sb.append("/");
                sb.append(month_end);
                sb.append("/");
                sb.append(day_end);

                String end=sb2.toString();

                Date startdateValue = new Date();
                Date enddateValue = new Date();
                try {

//                  if(year == 0 || year_end == 0){
//                      start="11/2/2011";
//                      end="1/7/2013";
//                  }

                    startdateValue = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
                            .parse(start);
                    enddateValue = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
                            .parse(end);
                } catch (Exception e) {
                }

                openChartthree(startdateValue, enddateValue);//calling charting method to render, passing start and end dates

            }
        });

    }

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

}

请帮助我纠正代码。

month_end = selectedMonth+1;

我必须在month_end变量中添加1,因为它总是在month_end变量中显示(month-1)。

2 个答案:

答案 0 :(得分:1)

尝试更改为 -

public void addButtonListenerOnBothButtons(){
    btnChangeDatetwo = (Button) findViewById(R.id.endate);
    btnChangeDate = (Button) findViewById(R.id.startdate);
    submit = (Button) findViewById(R.id.button1);

    btnChangeDatetwo.setOnClickListener(this);      
    btnChangeDate.setOnClickListener(this);
    submit.setOnClickListener(this);
}   

@Override
public void onClick(View arg0) {
switch(arg0.getId()){
    case R.id.endate:       
        final Calendar c = Calendar.getInstance();
        year_end = c.get(Calendar.YEAR);
        month_end = c.get(Calendar.MONTH);
        day_end = c.get(Calendar.DAY_OF_MONTH);

        showDialog(DATE_DIALOG_ID_TWO);

    break;

    case R.id.startdate:
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        showDialog(DATE_DIALOG_ID);
    break;        

    case R.id.button1:
            // do something when submit button pressed
    break;
  }
}

只需从addButtonListenerOnBothButtons调用onCreate方法,并将事件处理程序附加到所有三个按钮一次,而不是使用单独的函数和匿名类。

答案 1 :(得分:0)

LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);
chartContainer.removeAllViews();

我找到了解决方案。问题是我每次运行提交代码时都必须删除或重置图表。这可以使用removeAllViews()方法完成。