how to minus off the previous keyed value(store in

2019-08-06 16:53发布

FORMULA: total distance travel(current odometer - previous odometer)/ no. of litres petrol pump

I've done up in my code this formula, however my code was not done completely. My code is (current odometer/ no. of litres petrol). I wanted to minus away the previous odometer , but I don't know how to do so. I will be storing the information in my database, based on the date. Can someone guide me how can I do so? in order to achieve the formula of total distance travel(current odometer - previous odometer)/ no. of litres petrol pump..

this is my code: I know there is something wrong with my String lastOdm=""; , butI not sure what to solve the error.

logcat:

01-22 11:01:12.136: E/AndroidRuntime(7078): FATAL EXCEPTION: main
01-22 11:01:12.136: E/AndroidRuntime(7078): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fuellog/com.example.fuellog.MainActivity}: java.lang.NullPointerException
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.os.Looper.loop(Looper.java:137)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at java.lang.reflect.Method.invokeNative(Native Method)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at java.lang.reflect.Method.invoke(Method.java:511)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at dalvik.system.NativeStart.main(Native Method)
01-22 11:01:12.136: E/AndroidRuntime(7078): Caused by: java.lang.NullPointerException
01-22 11:01:12.136: E/AndroidRuntime(7078):     at com.example.fuellog.DBAdapter.getLastOdometer(DBAdapter.java:104)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at com.example.fuellog.MainActivity.onCreate(MainActivity.java:74)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.Activity.performCreate(Activity.java:5104)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-22 11:01:12.136: E/AndroidRuntime(7078):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-22 11:01:12.136: E/AndroidRuntime(7078):     ... 11 more

mainactivity.java

      public class MainActivity extends Activity {
   // TableLayout tablelayout_Log = null;
    Button saveButton = null;
    Button cancelButton = null;
   // Button searchButton = null;
    static EditText dateEdit; 
    EditText priceEdit;
    EditText pumpEdit;
    TextView costView;
    EditText odometerEdit;
    TextView fconView;
     TextWatcher textWatcher;
     String priceEditStr ="",pumpEditStr="";
     String  odmEditStr = "";
     String lastOdm = "";

double result;
double resultCon;
private int mYear;
private int mMonth;
private int mDay;

static final int DATE_DIALOG_ID = 0;





    public boolean isNumeric(String str)
    {
        return str.matches("-?\\d+(\\.\\d+)?"); 
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        costView = (TextView)findViewById(R.id.tcost);
        dateEdit = (EditText)findViewById(R.id.date);
        priceEdit = (EditText)findViewById(R.id.fuelprice);
        pumpEdit = (EditText)findViewById(R.id.fuelpump);
        odometerEdit = (EditText)findViewById(R.id.odometer);
        fconView = (TextView)findViewById(R.id.fcon);



        dateEdit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               // showDialog(DATE_DIALOG_ID);
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datePicker");
            }
        });


           priceEdit.addTextChangedListener(new TextWatcher() {

               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it
                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !priceEdit.getText().toString().trim().equalsIgnoreCase(null))
                        priceEditStr = priceEdit.getText().toString().trim();
                   if(!pumpEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(null))
                        pumpEditStr = pumpEdit.getText().toString().trim();

                  if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                  {
                    result = Double.parseDouble(priceEditStr) * Double.parseDouble(pumpEditStr);              
                    costView.setText(" "+result);
                  }

               }
           });

           pumpEdit.addTextChangedListener(new TextWatcher() {

               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it
                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase(""))
                        priceEditStr = priceEdit.getText().toString().trim();
                   if(!pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                        pumpEditStr = pumpEdit.getText().toString().trim();


                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                      {
                        result = Double.parseDouble(priceEditStr) * Double.parseDouble(pumpEditStr);              
                        costView.setText(" "+result);
                      }

               }
           });







           odometerEdit.addTextChangedListener(new TextWatcher() {
               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }



               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it

                   if(!odometerEdit.getText().toString().trim().equalsIgnoreCase(""))
                       odmEditStr = odometerEdit.getText().toString().trim();


                  if(!odometerEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase("") && !lastOdm.trim().equalsIgnoreCase(null) && !lastOdm.trim().equalsIgnoreCase(" "))
                     {
                      DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
                      lastOdm = dbAdaptor.getLastOdometer();
                       resultCon = Double.parseDouble(odmEditStr) - Double.parseDouble(lastOdm) / Double.parseDouble(pumpEditStr);              
                       fconView.setText(" "+resultCon);
                     }

               }
           });



           cancelButton = (Button) findViewById(R.id.cancelBTN);
           cancelButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    /// Create Intent for About  and start activity
                    Intent summaryView=new Intent(getApplicationContext(),summary.class);
                    startActivity(summaryView);
                    }
                });



   //Insert
        saveButton = (Button) findViewById(R.id.saveBTN);
        saveButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());

                try
                {
                    dbAdaptor.open();

                   // String cursor = dbAdaptor.getLastOdometer();
                    String date = dateEdit.getText().toString();
                    String price = priceEdit.getText().toString();
                    String pump = pumpEdit.getText().toString();
                    String tcost = costView.getText().toString();
                    String odometer = odometerEdit.getText().toString();
                    String fcon = fconView.getText().toString();
                    dbAdaptor.insertLog(date, price, pump, tcost, odometer, fcon);
                    Intent summaryView=new Intent(getApplicationContext(),summary.class);
                    startActivity(summaryView);

                }
                catch(Exception e){
                    Log.d("Fuel Log", e.getMessage());
                }
                finally
                {
                    if(dbAdaptor != null)
                        dbAdaptor.close();
                }
            }
        });

    }


    public static class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {

        public EditText editText;
        DatePicker dpResult;

    public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker

    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    //return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {

        dateEdit.setText(String.valueOf(day) + "/"
                + String.valueOf(month + 1) + "/" + String.valueOf(year));
        // set selected date into datepicker also


    }
    }
}

dbadapter.java

  public class DBAdapter {



    public static final String KEY_ROWID = "_id";
    public static final String KEY_DATE = "date";
    public static final String KEY_PRICE = "fuelprice";
    public static final String KEY_FUEL = "fuelpump";
    public static final String KEY_COST = "tcost";
    public static final String KEY_ODM = "odometer";
    public static final String KEY_CON = "fcon";

    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "MyDB";
    private static final String DATABASE_TABLE = "fuelLog";
    private static final int DATABASE_VERSION = 2;



    private static final String DATABASE_CREATE =
            "create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);";


        private final Context context;    

        private DatabaseHelper DBHelper;
        private SQLiteDatabase db;

        public DBAdapter(Context ctx){
            this.context = ctx;
            DBHelper = new DatabaseHelper(context);
        }

        private static class DatabaseHelper extends SQLiteOpenHelper 
        {
            DatabaseHelper(Context context){
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            public void onCreate(SQLiteDatabase db) 
            {
                try{
                    db.execSQL(DATABASE_CREATE);    
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }//onCreate

            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
            {
                Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
                db.execSQL("DROP TABLE IF EXISTS contacts");
                onCreate(db);
            }//onUpgrade

        }//DatabaseHelper


        public DBAdapter open() throws SQLException 
        {
            db = DBHelper.getWritableDatabase();
            return this;
        }//open


        //---closes the database---    
        public void close() 
        {
            DBHelper.close();
        }//close


        //---insert a log into the database---
        public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon ) 
        {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_DATE, date);
            initialValues.put(KEY_PRICE, fuelprice);
            initialValues.put(KEY_FUEL, fuelpump);
            initialValues.put(KEY_COST, tcost);
            initialValues.put(KEY_ODM, odometer);
            initialValues.put(KEY_CON, fcon);


            return db.insert(DATABASE_TABLE, null, initialValues);
        }//insertLog



        public String getLastOdometer() {
            Cursor cursor = db.query(DATABASE_TABLE, new String[] {KEY_ODM}, "KEY_ROWID=(SELECT MAX(KEY_ROWID) FROM " + DATABASE_TABLE + ")", null, null, null, null);
            try {
                if(cursor.moveToNext()) {
                    return cursor.getString(0);
                } else {
                    return null;
                }
            } finally {
                cursor.close();
            }
        }





}

标签: java android
2条回答
We Are One
2楼-- · 2019-08-06 17:25

The simplest way would be to just get the last inserted value, by adding the following function to DBAdapter:

public String getLastOdometer() {
    Cursor cursor = db.query(DATABASE_TABLE, new String[] {KEY_ODM}, "rowId=(SELECT MAX(rowId) FROM " + DATABASE_TABLE + ")", null, null, null, null);
    try {
        if(cursor.moveToNext()) {
            return cursor.getString(0);
        } else {
            return null;
        }
    } finally {
        cursor.close();
    }
}

Note that it returns null if the table is empty.

But if you want to rely on the dates inserted and not the order in which the data was inserted, you need to make sure that dates can be textually sorted, e.g. by formatting year first, then month and then day (2014-01-20). Then you can use a query based on getting the latest date: KEY_DATE + "=(SELECT MAX(" + KEY_DATE + ") FROM " + DATABASE_TABLE + ")".

After this function is ready, you can call it where you calculate the fuel utilization (just don't forget to open() and close() the database).

查看更多
叼着烟拽天下
3楼-- · 2019-08-06 17:26

Final Edited Answer

See the solved

    import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



public class EditResult1 extends Activity {

    // TableLayout tablelayout_Log = null;
    Button saveButton = null;
    Button cancelButton = null;
   // Button searchButton = null;
    static EditText dateEdit; 
    EditText priceEdit;
    EditText pumpEdit;
    TextView costView;
    EditText odometerEdit;
    TextView fconView;
    TextWatcher textWatcher;
    String priceEditStr ="",pumpEditStr="";
    String  odmEditStr = "";
    String lastOdm = "";

    double result;
    double resultCon;
    private int mYear;
    private int mMonth;
    private int mDay;

    SharedPreferences sp;

    static final int DATE_DIALOG_ID = 0;

    public boolean isNumeric(String str)
    {
        return str.matches("-?\\d+(\\.\\d+)?"); 
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.edit_sample);
        costView = (TextView)findViewById(R.id.tcost);
        dateEdit = (EditText)findViewById(R.id.date);
        priceEdit = (EditText)findViewById(R.id.fuelprice);
        pumpEdit = (EditText)findViewById(R.id.fuelpump);
        odometerEdit = (EditText)findViewById(R.id.odometer);
        fconView = (TextView)findViewById(R.id.fcon);

        /**
         * Shared preference 
         **/
        sp=this.getSharedPreferences("result_store", MODE_WORLD_READABLE);
        lastOdm=sp.getString("ODO", lastOdm);

        if(lastOdm.trim().equalsIgnoreCase("NA"))
            Toast.makeText(getApplicationContext(), " "+lastOdm.trim(), Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getApplicationContext(), " "+lastOdm.trim(), Toast.LENGTH_LONG).show();

        dateEdit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               // showDialog(DATE_DIALOG_ID);
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datePicker");
            }
        });


           priceEdit.addTextChangedListener(new TextWatcher() {

               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it
                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !priceEdit.getText().toString().trim().equalsIgnoreCase(null))
                        priceEditStr = priceEdit.getText().toString().trim();
                   if(!pumpEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(null))
                        pumpEditStr = pumpEdit.getText().toString().trim();

                  if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                  {
                    result = Double.parseDouble(priceEditStr) * Double.parseDouble(pumpEditStr);              
                    costView.setText(" "+result);
                  }

               }
           });

           pumpEdit.addTextChangedListener(new TextWatcher() {

               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it
                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase(""))
                        priceEditStr = priceEdit.getText().toString().trim();
                   if(!pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                        pumpEditStr = pumpEdit.getText().toString().trim();


                   if(!priceEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase(""))
                      {
                        result = Double.parseDouble(priceEditStr) * Double.parseDouble(pumpEditStr);              
                        costView.setText(" "+result);
                      }

               }
           });


           odometerEdit.addTextChangedListener(new TextWatcher() {
               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               }



               @Override
               public void afterTextChanged(Editable editable) {
                  //here, after we introduced something in the EditText we get the string from it

                   if(!odometerEdit.getText().toString().trim().equalsIgnoreCase(""))
                       odmEditStr = odometerEdit.getText().toString().trim();


                  if(!odometerEdit.getText().toString().trim().equalsIgnoreCase("") && !pumpEdit.getText().toString().trim().equalsIgnoreCase("") && !lastOdm.trim().equalsIgnoreCase("") && !lastOdm.trim().equalsIgnoreCase("NA"))
                     {

                       resultCon = Double.parseDouble(odmEditStr) - Double.parseDouble(lastOdm) / Double.parseDouble(pumpEditStr);              
                       fconView.setText(" "+resultCon);
                     }

               }
           });



           cancelButton = (Button) findViewById(R.id.cancelBTN);
           cancelButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    /// Create Intent for About  and start activity
                    Intent summaryView=new Intent(getApplicationContext(),ActivityA.class);
                    startActivity(summaryView);
                    }
                });



   //Insert
        saveButton = (Button) findViewById(R.id.saveBTN);
        saveButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());

                try
                {
                    dbAdaptor.open();
                   // String cursor = dbAdaptor.getLastOdometer();
                    String date = dateEdit.getText().toString();
                    String price = priceEdit.getText().toString();
                    String pump = pumpEdit.getText().toString();
                    String tcost = costView.getText().toString();
                    String odometer = odometerEdit.getText().toString();
                    String fcon = fconView.getText().toString();

                    if(!odometer.trim().equalsIgnoreCase(""))
                    {
                        SharedPreferences.Editor editor=sp.edit();
                        editor.putString("ODO", odometer.trim());
                        editor.commit();
                    }
                    else
                    {
                        SharedPreferences.Editor editor=sp.edit();
                        editor.putString("ODO", "NA");
                        editor.commit();
                    }

                    dbAdaptor.insertLog(date, price, pump, tcost, odometer, fcon);
                    Intent summaryView=new Intent(getApplicationContext(),ActivityA.class);
                    startActivity(summaryView);

                }
                catch(Exception e){
                    Log.d("Fuel Log", e.getMessage());
                }
                finally
                {
                    if(dbAdaptor != null)
                        dbAdaptor.close();
                }
            }
        });

    }


    public static class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {

        public EditText editText;
        DatePicker dpResult;

    public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker

    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    //return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {

        dateEdit.setText(String.valueOf(day) + "/"
                + String.valueOf(month + 1) + "/" + String.valueOf(year));
        // set selected date into datepicker also


    }
    }
}

Replace EditResult1 to your class name and also same for XML .

查看更多
登录 后发表回答