I am trying to use SQLlight to favourite an object, but whenever i click the button, it gives me a null reference error.
Below is the logcat error I am getting The suggested duplicate dioesnt seem to answer my question
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.onyebuchboss.bossweatherbitcoinapp.SQLightHelper.insertWbapp(java.lang.String, java.lang.String)' on a null object reference
at com.onyebuchboss.bossweatherbitcoinapp.WeatherActivity.insert(WeatherActivity.java:299)
at com.onyebuchboss.bossweatherbitcoinapp.WeatherActivity$2.onClick(WeatherActivity.java:93)
at android.view.View.performClick(View.java:6231)
at android.view.View$PerformClick.run(View.java:23406)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6293)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1094)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
below is the class mainClass and the last method in there is the SQLLight I called. it seems i am calling the insertData() in the wrong place:
package com.onyebuchboss.bossweatherbitcoinapp;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
/**
* Created by onyeb on 22/03/2018.
*/
public class WeatherActivity extends AppCompatActivity {
final int REQUEST_CODE = 123;
//the openweather url to be used
final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
//the API key
final String APP_ID = "c9e6cb73daaf09d1bf0d1502d964bf60";
//time between location update (5000 milliseconds or 5 seconds)
final long MIN_TIME = 5000;
//Distance between location in metres
final float MIN_DISTANCE = 1000;
final String TAG = "WeatherApp";
//For the app to detect the user's location,
//we set the LOCATION_PROVIDER
String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;
//declare the variables to be linked to the layout
TextView mTemperature;
TextView mCity;
ImageView mWeatherImage;
ImageButton FavouriteButton;
//declare the LocationListener and LocationManager
LocationManager mLocationManager;
LocationListener mLocationListener;
SQLightHelper mSQLightHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_layout);
//Link the elements in the Layout here
mCity = (TextView) findViewById(R.id.locationFetching);
mTemperature = (TextView) findViewById(R.id.tempereatureView);
mWeatherImage = (ImageView) findViewById(R.id.weatherImage);
ImageButton ChangeCityButton = (ImageButton) findViewById(R.id.changeCityButton);
FavouriteButton = (ImageButton) findViewById(R.id.favouriteBtn);
//The Intent method used below is mostly used for switching between Activities
ChangeCityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent changeCityIntent = new Intent(WeatherActivity.this, ChangeCityController.class);
// finish();
startActivity(changeCityIntent);
}
});
}
//the onResume method is one of android lifecycle method
//that starts/execute after the onCreate method
@Override
protected void onResume() {
super.onResume();
//retieving the city name passed in the
//ChangecityController
//City was used in the PutExtra method in changeCity
Intent myIntent = getIntent();
String city =myIntent.getStringExtra("City");
//if the user does not enter a particular city
//retrieve user current city
if(city != null) {
getWeatherForNewLocation(city);
} else {
getWeatherForCurrentLocation();
}
FavouriteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insert();
}
});
}
//The method to retrieve any city entered by the user
private void getWeatherForNewLocation(String city) {
//the request params passes in the required parameters to retrieve data using the API
//The openWeatherMap API being used in this project, "q" and acity's name
//is to be assigned to iy
RequestParams params = new RequestParams();
params.put("q", city);
params.put("appid", APP_ID);
networkingCalls(params);
}
// get weather situation for current city -getWeatherForCurrentCityHere()
private void getWeatherForCurrentLocation() {
//create an instance of LocationManager
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//the Location listener does the checking of the location for update
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: callback received");
//get the longitude and latitude of current locaion
//stored as a string
String Longitude = String.valueOf(location.getLongitude());
String Latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "onLocation Latitude is: " + Latitude);
Log.d(TAG, "onLocationChanged: longitude " + Longitude);
RequestParams params = new RequestParams();
params.put("lat", Latitude);
params.put("lon", Longitude);
params.put("appid", APP_ID);
networkingCalls(params);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled: callback");
}
};
//REQUEST A LOCATION UPDATE PASSING THE LOCATION PROVIDER TO BE USED, MIN TIME,
// MIN DISTANCE AND mLISTENER as the receiver
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//request permissions to use the user's device GPS
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
}
//the override method below gives the result of the
// permission request to use the user's GPS
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//check to see if the request code matches the Request Code we gave
//during the request
if(requestCode == REQUEST_CODE){
if(grantResults.length> 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult(): Granted!");
getWeatherForCurrentLocation();
}else{
Log.d(TAG, "onRequestPermissionsResult: Permission Denied");
}
}
}
//create the networkingCalls method here
//this method, we implement an HttpRequest, using it to make a Get request
private void networkingCalls(RequestParams params){
AsyncHttpClient client = new AsyncHttpClient();
//the Json object handler is used to notify whether the Getrequest failed or was successful
//the json response hanler receive 2 messages - onSucess and onFailure
//both methods are declared below
client.get(WEATHER_URL, params, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response){
Log.d(TAG, "onSuccess: " + response.toString());
// call the json from the WeatherDataModel
WeatherDataModel weatherData = WeatherDataModel.fromJson(response);
updateUI(weatherData);
}
@Override
public void onFailure(int statuscode, Header[] headers, Throwable e, JSONObject response){
Log.e(TAG, "onFailure: "+ e.toString());
Log.d(TAG, "Status code: " + statuscode);
Toast.makeText(WeatherActivity.this, "Request failed", Toast.LENGTH_SHORT).show();
}
});
}
private void updateUI(WeatherDataModel weather){
mTemperature.setText(weather.getTemperature());
mCity.setText(weather.getCity());
int resourceID = getResources().getIdentifier(weather.getIconname(), "drawable", getPackageCodePath());
mWeatherImage.setImageResource(resourceID);
}
//This code below frees up memory
//when mListener is not in use and it is automatically generated
@Override
protected void onPause() {
super.onPause();
if(mLocationManager != null) mLocationManager.removeUpdates(mLocationListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.wGoToBitcoin){
Intent bitcoin = new Intent(WeatherActivity.this, BitcoinActivity.class);
startActivity(bitcoin);
}
if(item.getItemId() == R.id.wLogOut){
FirebaseAuth.getInstance().signOut();
Intent logoutIntent = new Intent(WeatherActivity.this, MainActivity.class);
startActivity(logoutIntent);
}
if(item.getItemId() == R.id.favourite){
Intent favourite = new Intent(WeatherActivity.this, ListViewActivity.class);
startActivity(favourite);
}
return true;
}
public void insert(){
String newDegree = mTemperature.toString();
String city = mCity.toString();
boolean insertData = mSQLightHelper.insertWbapp(newDegree, city);
if(insertData){
Toast.makeText(this, "Data inserted successfully", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Data insertion not successful", Toast.LENGTH_SHORT).show();
}
}
}
And below is my SQLhelper class. Please someone help look at it.
package com.onyebuchboss.bossweatherbitcoinapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SQLightHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "wbapp";
public static final String COLUMN_ID = "id";
public static final String COLUMN_A ="weather_degree";
public static final String COLUMN_B = "city_name";
private static final String DATABASE_NAME = "wbapp.db";
private static final int DATABASE_VERSION = 1;
//Creating the database
/*private static final String DATA_CREATE = "create table " + TABLE_NAME + "( " +
COLUMN_ID + "integer primary key autoincrement, " + COLUMN_A
+ COLUMN_ID + "integer primary key autoincrement, " + COLUMN_B + "text not null);";*/
public SQLightHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table wbapp " + "(id integer primary key, weather_degree text, city_name text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS wbapp");
onCreate(db);
}
public boolean insertWbapp (String weather_degree, String city_name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("weather_degree", weather_degree);
contentValues.put("city_name", city_name);
Log.d("SQLlight", "insertWbapp: " + TABLE_NAME);
db.insert("wbapp",null, contentValues);
/*if(result == -1){
return false;}
else {
return true;
}*/
return true;
}
public Cursor getData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
/*public Cursor getItemID(String wDegree, String city){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery(query, null);
return data;
}*/
//delete weatherData
public void deleteWeatherInfo (Integer id, String wDegree, String city) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = '" + id + "'" +
" AND " + COLUMN_A + " = '" + wDegree + "'" + " AND " + COLUMN_B + " = '" + city + "'";
Log.d("SQLIGHTHELPER", "deleteWeatherInfo: " + wDegree + city + "from the datbase");
db.execSQL(query);
}
}
I do not know what I am doing wrong. Someone please help
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.onyebuchboss.bossweatherbitcoinapp.SQLightHelper.insertWbapp(java.lang.String, java.lang.String)' on a null object reference
at com.onyebuchboss.bossweatherbitcoinapp.WeatherActivity.insert(WeatherActivity.java:299)
at com.onyebuchboss.bossweatherbitcoinapp.WeatherActivity$2.onClick(WeatherActivity.java:93)
at android.view.View.performClick(View.java:6231)
at android.view.View$PerformClick.run(View.java:23406)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6293)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1094)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
below is the class mainClass and the last method in there is the SQLLight I called. it seems i am calling the insertData() in the wrong place:
package com.onyebuchboss.bossweatherbitcoinapp;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
/**
* Created by onyeb on 22/03/2018.
*/
public class WeatherActivity extends AppCompatActivity {
final int REQUEST_CODE = 123;
//the openweather url to be used
final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
//the API key
final String APP_ID = "c9e6cb73daaf09d1bf0d1502d964bf60";
//time between location update (5000 milliseconds or 5 seconds)
final long MIN_TIME = 5000;
//Distance between location in metres
final float MIN_DISTANCE = 1000;
final String TAG = "WeatherApp";
//For the app to detect the user's location,
//we set the LOCATION_PROVIDER
String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;
//declare the variables to be linked to the layout
TextView mTemperature;
TextView mCity;
ImageView mWeatherImage;
ImageButton FavouriteButton;
//declare the LocationListener and LocationManager
LocationManager mLocationManager;
LocationListener mLocationListener;
SQLightHelper mSQLightHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_layout);
//Link the elements in the Layout here
mCity = (TextView) findViewById(R.id.locationFetching);
mTemperature = (TextView) findViewById(R.id.tempereatureView);
mWeatherImage = (ImageView) findViewById(R.id.weatherImage);
ImageButton ChangeCityButton = (ImageButton) findViewById(R.id.changeCityButton);
FavouriteButton = (ImageButton) findViewById(R.id.favouriteBtn);
//The Intent method used below is mostly used for switching between Activities
ChangeCityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent changeCityIntent = new Intent(WeatherActivity.this, ChangeCityController.class);
// finish();
startActivity(changeCityIntent);
}
});
}
//the onResume method is one of android lifecycle method
//that starts/execute after the onCreate method
@Override
protected void onResume() {
super.onResume();
//retieving the city name passed in the
//ChangecityController
//City was used in the PutExtra method in changeCity
Intent myIntent = getIntent();
String city =myIntent.getStringExtra("City");
//if the user does not enter a particular city
//retrieve user current city
if(city != null) {
getWeatherForNewLocation(city);
} else {
getWeatherForCurrentLocation();
}
FavouriteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insert();
}
});
}
//The method to retrieve any city entered by the user
private void getWeatherForNewLocation(String city) {
//the request params passes in the required parameters to retrieve data using the API
//The openWeatherMap API being used in this project, "q" and acity's name
//is to be assigned to iy
RequestParams params = new RequestParams();
params.put("q", city);
params.put("appid", APP_ID);
networkingCalls(params);
}
// get weather situation for current city -getWeatherForCurrentCityHere()
private void getWeatherForCurrentLocation() {
//create an instance of LocationManager
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//the Location listener does the checking of the location for update
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: callback received");
//get the longitude and latitude of current locaion
//stored as a string
String Longitude = String.valueOf(location.getLongitude());
String Latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "onLocation Latitude is: " + Latitude);
Log.d(TAG, "onLocationChanged: longitude " + Longitude);
RequestParams params = new RequestParams();
params.put("lat", Latitude);
params.put("lon", Longitude);
params.put("appid", APP_ID);
networkingCalls(params);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled: callback");
}
};
//REQUEST A LOCATION UPDATE PASSING THE LOCATION PROVIDER TO BE USED, MIN TIME,
// MIN DISTANCE AND mLISTENER as the receiver
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//request permissions to use the user's device GPS
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
}
//the override method below gives the result of the
// permission request to use the user's GPS
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//check to see if the request code matches the Request Code we gave
//during the request
if(requestCode == REQUEST_CODE){
if(grantResults.length> 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult(): Granted!");
getWeatherForCurrentLocation();
}else{
Log.d(TAG, "onRequestPermissionsResult: Permission Denied");
}
}
}
//create the networkingCalls method here
//this method, we implement an HttpRequest, using it to make a Get request
private void networkingCalls(RequestParams params){
AsyncHttpClient client = new AsyncHttpClient();
//the Json object handler is used to notify whether the Getrequest failed or was successful
//the json response hanler receive 2 messages - onSucess and onFailure
//both methods are declared below
client.get(WEATHER_URL, params, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response){
Log.d(TAG, "onSuccess: " + response.toString());
// call the json from the WeatherDataModel
WeatherDataModel weatherData = WeatherDataModel.fromJson(response);
updateUI(weatherData);
}
@Override
public void onFailure(int statuscode, Header[] headers, Throwable e, JSONObject response){
Log.e(TAG, "onFailure: "+ e.toString());
Log.d(TAG, "Status code: " + statuscode);
Toast.makeText(WeatherActivity.this, "Request failed", Toast.LENGTH_SHORT).show();
}
});
}
private void updateUI(WeatherDataModel weather){
mTemperature.setText(weather.getTemperature());
mCity.setText(weather.getCity());
int resourceID = getResources().getIdentifier(weather.getIconname(), "drawable", getPackageCodePath());
mWeatherImage.setImageResource(resourceID);
}
//This code below frees up memory
//when mListener is not in use and it is automatically generated
@Override
protected void onPause() {
super.onPause();
if(mLocationManager != null) mLocationManager.removeUpdates(mLocationListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.wGoToBitcoin){
Intent bitcoin = new Intent(WeatherActivity.this, BitcoinActivity.class);
startActivity(bitcoin);
}
if(item.getItemId() == R.id.wLogOut){
FirebaseAuth.getInstance().signOut();
Intent logoutIntent = new Intent(WeatherActivity.this, MainActivity.class);
startActivity(logoutIntent);
}
if(item.getItemId() == R.id.favourite){
Intent favourite = new Intent(WeatherActivity.this, ListViewActivity.class);
startActivity(favourite);
}
return true;
}
public void insert(){
String newDegree = mTemperature.toString();
String city = mCity.toString();
boolean insertData = mSQLightHelper.insertWbapp(newDegree, city);
if(insertData){
Toast.makeText(this, "Data inserted successfully", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Data insertion not successful", Toast.LENGTH_SHORT).show();
}
}
}
And below is my SQLhelper class. Please someone help look at it.
package com.onyebuchboss.bossweatherbitcoinapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SQLightHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "wbapp";
public static final String COLUMN_ID = "id";
public static final String COLUMN_A ="weather_degree";
public static final String COLUMN_B = "city_name";
private static final String DATABASE_NAME = "wbapp.db";
private static final int DATABASE_VERSION = 1;
//Creating the database
/*private static final String DATA_CREATE = "create table " + TABLE_NAME + "( " +
COLUMN_ID + "integer primary key autoincrement, " + COLUMN_A
+ COLUMN_ID + "integer primary key autoincrement, " + COLUMN_B + "text not null);";*/
public SQLightHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table wbapp " + "(id integer primary key, weather_degree text, city_name text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS wbapp");
onCreate(db);
}
public boolean insertWbapp (String weather_degree, String city_name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("weather_degree", weather_degree);
contentValues.put("city_name", city_name);
Log.d("SQLlight", "insertWbapp: " + TABLE_NAME);
db.insert("wbapp",null, contentValues);
/*if(result == -1){
return false;}
else {
return true;
}*/
return true;
}
public Cursor getData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
/*public Cursor getItemID(String wDegree, String city){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery(query, null);
return data;
}*/
//delete weatherData
public void deleteWeatherInfo (Integer id, String wDegree, String city) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = '" + id + "'" +
" AND " + COLUMN_A + " = '" + wDegree + "'" + " AND " + COLUMN_B + " = '" + city + "'";
Log.d("SQLIGHTHELPER", "deleteWeatherInfo: " + wDegree + city + "from the datbase");
db.execSQL(query);
}
}
I do not know what I am doing wrong. Someone please help
Комментарии
Отправить комментарий