我正在开发抵押贷款计算器应用程序。 它的工作原理如下 -
1]您可以在CalculationFragment中进行新的计算。您可以保存未来的计算。
2]在MapFragment中显示Google地图的已保存计算。
每当用户点击CalculationFragment中的保存计算时,我都会使用SQLite存储所有已保存的数据。 无论何时启动应用程序,都会创建并读取SQlite。 我希望每次用户点击保存计算时更新地图。 每当我第二次尝试访问SQLite来更新映射时,它都会抛出对象引用错误。 我无法弄清楚它为什么抛出对象引用错误。 请提供您的意见。
以下行是在DatabaseHelper.java中抛出错误:
MapFragment mapFragment = new MapFragment();
mapFragment.updateMap();
以下是文件:
MapFragment.java:
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
TextView propertyType, address;
LatLng latLng;
String PropertyType, Address;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("PAVAN", "Inside map create");
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_map, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter(){
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View v = inflater.inflate(R.layout.custom_window_adapter, null);
Log.d("PAVAN", "inside getInfoWindow");
propertyType = (TextView) v.findViewById(R.id.PropertyType);
address = (TextView) v.findViewById(R.id.Address);
TextView loanAmount = (TextView) v.findViewById(R.id.loanAmount);
TextView APR = (TextView) v.findViewById(R.id.APR);
TextView monthlyPayment = (TextView) v.findViewById(R.id.monthlyPayment);
String separateTitle = marker.getTitle();
Log.d("VANSH", "Separate Title"+separateTitle);
String[] titleParts;
titleParts = separateTitle.split("-");
propertyType.setText(titleParts[0]);
address.setText(titleParts[1]);
loanAmount.setText(titleParts[2]);
APR.setText(titleParts[3]);
monthlyPayment.setText(titleParts[4]);
latLng = marker.getPosition();
return v;
}
});
updateMap();
return v;
}
public void updateMap()
{
Log.d("PAVAN", "Calling database helper from Map fragment to read data");
DatabaseHelper databaseHelper = new DatabaseHelper(getContext(), null, null, 0);
ArrayList<PropertyDetails> arrayList = databaseHelper.readData();
if(arrayList.size() != 0)
{
for(int i = 0 ; i < arrayList.size() ; i++)
{
PropertyType = arrayList.get(i).PropertyType;
Address = arrayList.get(i).Address;
String City = arrayList.get(i).City;
Double LoanAmount = arrayList.get(i).LoanAmount;
Double APR = arrayList.get(i).APR;
Double MonthlyPayment = arrayList.get(i).MonthlyPayment;
Double Latitude = arrayList.get(i).getLatitude();
Double Longitude = arrayList.get(i).getLongitude();
LatLng latlang = new LatLng(Latitude, Longitude);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(latlang)
.title(PropertyType+"-"+Address+"-"+LoanAmount+"-"+APR+"-"+MonthlyPayment)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
Log.d("PAVAN", "calling show info window");
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return true;
}
});
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
else {
// latitude and longitude
double Latitude = 17.385044;
double Longitude = 78.486671;
LatLng latlang = new LatLng(Latitude, Longitude);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(latlang)
.title("Default-Default-0-0-0")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
Log.d("PAVAN", "calling show info window");
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return true;
}
});
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
DatabaseHelper.java:
public class DatabaseHelper extends SQLiteOpenHelper
{
SQLiteDatabase sqLiteDatabase;
private static final String databaseName = "MortgageCalculatorDatabase.db";
private static final int databaseVersion = 11;
private static final String tableName = "PropertyTable";
DatabaseHelper databaseHelper;
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
{
super(context, databaseName, factory, databaseVersion);
databaseHelper = this;
}
public DatabaseHelper getObject()
{
return databaseHelper;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
Log.d("PAVAN", "Inside create table");
String query = "CREATE TABLE IF NOT EXISTS " + tableName + "(PropertyType TEXT, Address TEXT, City TEXT, LoanAmount DOUBLE, APR DOUBLE, MonthlyPayment DOUBLE, Latitude DOUBLE, Longitude DOUBLE)";
sqLiteDatabase.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
{
Log.d("PAVAN", "Inside upgrade");
String query = "DROP TABLE IF EXISTS " + tableName;
sqLiteDatabase.execSQL(query);
onCreate(sqLiteDatabase);
}
public boolean addPropertyInfo(String PropertyType, String Address, String City, Double LoanAmount, Double APR, Double MonthlyPayment, Double Latitude, Double Longitude)
{
sqLiteDatabase = databaseHelper.getWritableDatabase();
Log.d("PAVAN", "inside Add property info");
try
{
ContentValues contentValues = new ContentValues();
contentValues.put("PropertyType", PropertyType);
contentValues.put("Address", Address);
contentValues.put("City", City);
contentValues.put("LoanAmount", LoanAmount);
contentValues.put("APR", APR);
contentValues.put("MonthlyPayment", MonthlyPayment);
contentValues.put("Latitude", Latitude);
contentValues.put("Longitude", Longitude);
sqLiteDatabase.insert(tableName, null, contentValues);
MapFragment mapFragment = new MapFragment();
mapFragment.updateMap();
return true;
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}
public ArrayList<PropertyDetails> readData()
{
Log.d("PAVAN", "Inside read data");
Log.d("PAVAN", "Current object"+this.getClass().getName());
sqLiteDatabase = databaseHelper.getReadableDatabase();
String query = "SELECT * FROM " + tableName;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
ArrayList<PropertyDetails> adapter = new ArrayList<>();
Log.d("PAVAN", "Cursor count "+cursor.getCount());
if (cursor != null && cursor.getCount() !=0)
{
cursor.moveToFirst();
do
{
String PropertyType = cursor.getString(cursor.getColumnIndex("PropertyType"));
String Address = cursor.getString(cursor.getColumnIndex("Address"));
String City = cursor.getString(cursor.getColumnIndex("City"));
Double LoanAmount = cursor.getDouble(cursor.getColumnIndex("LoanAmount"));
Double APR = cursor.getDouble(cursor.getColumnIndex("APR"));
Double MonthlyPayment = cursor.getDouble(cursor.getColumnIndex("MonthlyPayment"));
Double Latitude = cursor.getDouble(cursor.getColumnIndex("Latitude"));
Double Longitude = cursor.getDouble(cursor.getColumnIndex("Longitude"));
PropertyDetails propertyDetails = new PropertyDetails();
propertyDetails.setPropertyType(PropertyType);
propertyDetails.setAddress(Address);
propertyDetails.setCity(City);
propertyDetails.setLoanAmount(LoanAmount);
propertyDetails.setAPR(APR);
propertyDetails.setMonthlyPayment(MonthlyPayment);
propertyDetails.setLatitude(Latitude);
propertyDetails.setLongitude(Longitude);
adapter.add(propertyDetails);
}while (cursor.moveToNext());
cursor.close();
return adapter;
}
return adapter;
}
}
CalculationFragment.java:
public class CalculationFragment extends Fragment
{
String globalAddress;
double lat, lng;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_calculation, container, false);
final PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
//final String globalAdd = new String();
final EditText price = (EditText)rootView.findViewById(R.id.editTextPropertyPrice);
final EditText downPayment = (EditText)rootView.findViewById(R.id.editTextDownPayment);
final EditText apr = (EditText)rootView.findViewById(R.id.editTextAPR);
final Spinner years = (Spinner)rootView.findViewById(R.id.spinnerYears);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i("Vansh", "Place: " + place.getName());
Log.i("Vansh", "Place: " + place.getAddress().toString());
//CharSequence addressCS = place.getAddress();
Geocoder geocoder = new Geocoder(getContext());
//String[] address = place.getAddress().toString().split(",");
try{
List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude,place.getLatLng().longitude, 1);
//List<Integer> addresses = place.getPlaceTypes();
String city = addresses.get(0).getLocality();
String country = addresses.get(0).getCountryName();
String address = addresses.get(0).getAddressLine(0);
globalAddress = address;
Double latitude = addresses.get(0).getLatitude();
Double longitude = addresses.get(0).getLongitude();
lat = latitude;
lng = longitude;
String zip = addresses.get(0).getPostalCode();
String state = addresses.get(0).getAdminArea();
Log.i("Vansh", "City: " + city);
Log.i("Vansh", "State: " + state);
Log.i("Vansh", "Country: " + country);
Log.i("Vansh", "Address: " + address);
Log.i("Vansh", "Lat: " + latitude);
Log.i("Vansh", "Long: " + longitude);
Log.i("Vansh", "Zip: " + zip);
//Log.i("Vansh", "Place: " + address[2]);
Spinner stateSpinner = (Spinner) rootView.findViewById(R.id.spinnerStates);
for(int i=0;i<stateSpinner.getCount();i++)
{
if(stateSpinner.getItemAtPosition(i).toString().equals(state))
{
stateSpinner.setSelection(i);
//return;
}
}
EditText cityEditText = (EditText)rootView.findViewById(R.id.editTextCity);
cityEditText.setText(city);
EditText zipEditText = (EditText)rootView.findViewById(R.id.editTextZipcode);
zipEditText.setText(zip);
//Log.i("Vansh", "thay che ahiya sudhi execute" + zipEditText.getText());
}catch (Exception e)
{
Log.i("Vansh", "Exception: " + e.getMessage());
}
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
}
});
Button calculate = (Button) rootView.findViewById(R.id.buttonCalculate);
final Button newCalculation = (Button) rootView.findViewById(R.id.newCalculation);
Button saveCalculation = (Button) rootView.findViewById(R.id.saveCalculation);
calculate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//Log.i("Vansh", "Thayooooooooooooo" + price.toString());
Double priceDbl = Double.parseDouble(price.getText().toString());
//Log.i("Vansh", "Thayooooooooooooo1"+years.getSelectedItem().toString());
Double downPaymentDbl = Double.parseDouble(downPayment.getText().toString());
//Log.i("Vansh", "Thayooooooooooooo2");
Double aprDbl = Double.parseDouble(apr.getText().toString());
//Log.i("Vansh", "Thayooooooooooooo3");
//Log.i("Vansh", "price " + priceDbl);
///Log.i("Vansh", "downpayment " + downPaymentDbl);
///Log.i("Vansh", "apr " + aprDbl);
Double rate = Math.pow(1+((Double.parseDouble(apr.getText().toString()))/(100*12)),12*Double.parseDouble(years.getSelectedItem().toString()));
//Log.i("Vansh", "rate: " + rate);
Double result = (priceDbl-downPaymentDbl)*((rate*(aprDbl/(100*12)))/(rate-1));
int output = (int)Math.round(result);
TextView resultText = (TextView)rootView.findViewById(R.id.textViewResult);
resultText.setText(Integer.toString(output));
}
});
newCalculation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((EditText) rootView.findViewById(R.id.editTextAPR)).getText().clear();
((EditText) rootView.findViewById(R.id.editTextCity)).getText().clear();
((EditText) rootView.findViewById(R.id.editTextZipcode)).getText().clear();
((EditText) rootView.findViewById(R.id.editTextPropertyPrice)).getText().clear();
((EditText) rootView.findViewById(R.id.editTextDownPayment)).getText().clear();
((Spinner) rootView.findViewById(R.id.spinnerStates)).setSelection(0);
((Spinner) rootView.findViewById(R.id.spinnerYears)).setSelection(0);
//int radio = ((RadioGroup)rootView.findViewById(R.id.radioGroupPropertyType)).getCheckedRadioButtonId();
autocompleteFragment.setText("");
}});
saveCalculation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Vansh", "savecalc 1");
DatabaseHelper db = new DatabaseHelper(getContext(), null, null,0);
Log.i("Vansh", "savecalc 2");
//String PropertyType, String Address, String City, Double LoanAmount, Double APR, Double MonthlyPayment, Double Latitude, Double Longitude
RadioGroup rg = (RadioGroup)rootView.findViewById(R.id.radioGroupPropertyType);
Log.i("Vansh", "savecalc 3");
String propertyType = ((RadioButton)rootView.findViewById(rg.getCheckedRadioButtonId())).getText().toString();
Log.i("Vansh", "savecalc 4");
//String address = autocompleteFragment.getText(0).toString();
String add = autocompleteFragment.toString();
Log.i("Vansh", "savecalc 5");
String city = ((EditText) rootView.findViewById(R.id.editTextCity)).getText().toString();
Double priceDbl = Double.parseDouble(price.getText().toString());
Log.i("Vansh", "savecalc 6");
Double downPaymentDbl = Double.parseDouble(downPayment.getText().toString());
Log.i("Vansh", "savecalc 7");
double loanAmount = priceDbl-downPaymentDbl;
Log.i("Vansh", "savecalc 8");
double apr = Double.parseDouble(((EditText) rootView.findViewById(R.id.editTextAPR)).getText().toString());
Log.i("Vansh", "savecalc 9");
double result = Double.parseDouble(((TextView)rootView.findViewById(R.id.textViewResult)).getText().toString());
Log.i("Vansh", "savecalc 10");
Log.d("PAVAN", "Save calculation");
db.addPropertyInfo(propertyType, globalAddress, city, loanAmount, apr, result, lat, lng);
}
});
return rootView;
}
}
这是堆栈跟踪中的错误消息:
java.lang.NullPointerException:尝试调用虚方法'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String,int,android.database.sqlite.SQLiteDatabase $ CursorFactory,android。 data.DatabaseErrorHandler)'对空对象引用