Related
When I run the below Java for Android code, I get a NullPointerException on the line that calls getSkuDetails in the doInBackground method in the GetItemList class. But when I step through in the debugger, all the parameters to getSkuDetails have values. pName is not an empty string and querySkus has two items in it. The exact error message I'm getting is "Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getSkuDetails(int, java.lang.String, java.lang.String, android.os.Bundle)' on a null object reference." Does anyone know why?
package com.myknitcards;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.vending.billing.IInAppBillingService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class AvailableCards extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_cards);
String packagename = this.getPackageName();
TextView priceView = (TextView)findViewById(R.id.availablePrice);
new GetItemList(packagename, priceView).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.available_cards, 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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class GetItemList extends AsyncTask<Integer, Integer, Long> {
private String pName;
private TextView pView;
GetItemList(String packagename, TextView priceView){
pName = packagename;
pView = priceView;
}
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
#Override
protected Long doInBackground(Integer... params) {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("i001");
skuList.add("i002");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, pName, "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object;
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
String mFirstIntermediate;
String mSecondIntermediate;
if (sku.equals("i001")) mFirstIntermediate = price;
else if (sku.equals("i002")) mSecondIntermediate = price;
pView.setText(sku + ": " + price);
}
}
} catch (NullPointerException ne) {
Log.d("Synch Billing", "Error Null Pointer: " + ne.getMessage());
ne.printStackTrace();
}
catch (RemoteException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error Remote: " + e.getMessage());
e.printStackTrace();
}
catch (JSONException je) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error JSON: " + je.getMessage());
je.printStackTrace();
}
return null;
}
}
Here's my log:
01-25 19:02:18.888: D/AndroidRuntime(4802): >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
01-25 19:02:18.894: D/AndroidRuntime(4802): CheckJNI is OFF
01-25 19:02:18.951: D/ICU(4802): No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
01-25 19:02:19.016: I/Radio-JNI(4802): register_android_hardware_Radio DONE
01-25 19:02:19.048: D/AndroidRuntime(4802): Calling main entry com.android.commands.pm.Pm
01-25 19:02:19.054: I/art(4802): System.exit called, status: 0
01-25 19:02:19.055: I/AndroidRuntime(4802): VM exiting with result code 0.
01-25 19:02:19.904: D/AndroidRuntime(4816): >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
01-25 19:02:19.911: D/AndroidRuntime(4816): CheckJNI is OFF
01-25 19:02:19.969: D/ICU(4816): No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
01-25 19:02:20.030: I/Radio-JNI(4816): register_android_hardware_Radio DONE
01-25 19:02:20.061: D/AndroidRuntime(4816): Calling main entry com.android.commands.am.Am
01-25 19:02:20.065: I/ActivityManager(607): Force stopping com.myknitcards appid=10087 user=-1: set debug app
01-25 19:02:20.066: I/ActivityManager(607): Killing 4727:com.myknitcards/u0a87 (adj 7): stop com.myknitcards
01-25 19:02:20.077: D/GraphicsStats(607): Buffer count: 3
01-25 19:02:20.077: I/WindowState(607): WIN DEATH: Window{9799d39 u0 com.myknitcards/com.myknitcards.MyKnitCardsMain}
01-25 19:02:20.179: I/ActivityManager(607): Force finishing activity ActivityRecord{16bdee6 u0 com.myknitcards/.MyKnitCardsMain t53}
01-25 19:02:20.182: W/ActivityManager(607): Spurious death for ProcessRecord{d0de1a6 0:com.myknitcards/u0a87}, curProc for 4727: null
01-25 19:02:20.183: I/ActivityManager(607): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.myknitcards/.MyKnitCardsMain} from uid 2000 on display 0
01-25 19:02:20.195: D/AndroidRuntime(4816): Shutting down VM
01-25 19:02:20.226: I/ActivityManager(607): Start proc 4826:com.myknitcards/u0a87 for activity com.myknitcards/.MyKnitCardsMain
01-25 19:02:20.233: I/art(4826): Late-enabling -Xcheck:jni
01-25 19:02:20.272: E/art(4826): Failed sending reply to debugger: Broken pipe
01-25 19:02:20.272: I/art(4826): Debugger is no longer active
01-25 19:02:20.292: W/ActivityThread(4826): Application com.myknitcards is waiting for the debugger on port 8100...
01-25 19:02:20.293: I/System.out(4826): Sending WAIT chunk
01-25 19:02:20.341: I/OpenGLRenderer(607): Initialized EGL, version 1.4
01-25 19:02:21.296: I/art(4826): Debugger is active
01-25 19:02:21.495: I/System.out(4826): Debugger has connected
01-25 19:02:21.495: I/System.out(4826): waiting for debugger to settle...
01-25 19:02:21.695: I/System.out(4826): waiting for debugger to settle...
01-25 19:02:21.895: I/System.out(4826): waiting for debugger to settle...
01-25 19:02:22.096: I/System.out(4826): waiting for debugger to settle...
01-25 19:02:22.297: I/System.out(4826): waiting for debugger to settle...
01-25 19:02:22.498: I/System.out(4826): waiting for debugger to settle...
01-25 19:02:22.698: I/System.out(4826): waiting for debugger to settle...
01-25 19:02:22.898: I/System.out(4826): debugger has settled (1457)
01-25 19:02:22.975: W/System(4826): ClassLoader referenced unknown path: /data/app/com.myknitcards-1/lib/arm
01-25 19:02:23.044: D/OpenGLRenderer(4826): Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-25 19:02:23.076: D/Finsky(1556): [101] InAppBillingUtils.getPreferredAccount: com.myknitcards: Account from first account - [j5w9pVwTyqMNo_FRNWfkXIUz9SE]
01-25 19:02:23.080: D/Finsky(1556): [143] InAppBillingUtils.getPreferredAccount: com.myknitcards: Account from first account - [j5w9pVwTyqMNo_FRNWfkXIUz9SE]
01-25 19:02:23.084: D/com.myknitcards(4826): In-app Billing is set up OK
01-25 19:02:23.105: I/Adreno-EGL(4826): <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
01-25 19:02:23.108: I/OpenGLRenderer(4826): Initialized EGL, version 1.4
01-25 19:02:23.133: W/AppOps(607): Finishing op nesting under-run: uid 1000 pkg android code 24 time=1451855407389 duration=1783 nesting=0
01-25 19:02:23.222: I/ActivityManager(607): Displayed com.myknitcards/.MyKnitCardsMain: +3s7ms
01-25 19:02:23.225: I/Keyboard.Facilitator(1004): onFinishInput()
01-25 19:02:23.231: D/WifiStateMachine(607): starting scan for "BooNetwork-5G"WPA_PSK with 2462,5785
01-25 19:02:24.523: D/audio_hw_primary(196): out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
01-25 19:02:24.524: I/ActivityManager(607): START u0 {cmp=com.myknitcards/.AvailableCards} from uid 10087 on display 0
01-25 19:02:24.533: D/audio_hw_primary(196): select_devices: out_snd_device(2: speaker) in_snd_device(0: none)
01-25 19:02:24.533: D/ACDB-LOADER(196): ACDB -> send_afe_cal
01-25 19:02:24.533: D/audio_hw_primary(196): enable_snd_device: snd_device(2: speaker)
01-25 19:02:24.542: D/audio_hw_primary(196): enable_audio_route: apply and update mixer path: low-latency-playback
01-25 19:02:24.666: I/ActivityManager(607): Displayed com.myknitcards/.AvailableCards: +134ms
01-25 19:02:24.667: I/Keyboard.Facilitator(1004): onFinishInput()
01-25 19:02:24.719: D/OpenGLRenderer(4826): endAllStagingAnimators on 0xb388d500 (RippleDrawable) with handle 0xb36fe690
01-25 19:02:27.777: D/audio_hw_primary(196): disable_audio_route: reset and update mixer path: low-latency-playback
01-25 19:02:27.778: D/audio_hw_primary(196): disable_snd_device: snd_device(2: speaker)
01-25 19:02:31.524: D/Synch Billing(4826): Error Null Pointer: Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getSkuDetails(int, java.lang.String, java.lang.String, android.os.Bundle)' on a null object reference
01-25 19:02:34.741: W/System.err(4826): java.lang.NullPointerException: Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getSkuDetails(int, java.lang.String, java.lang.String, android.os.Bundle)' on a null object reference
01-25 19:02:34.742: W/System.err(4826): at com.myknitcards.GetItemList.doInBackground(AvailableCards.java:87)
01-25 19:02:34.742: W/System.err(4826): at com.myknitcards.GetItemList.doInBackground(AvailableCards.java:1)
01-25 19:02:34.742: W/System.err(4826): at android.os.AsyncTask$2.call(AsyncTask.java:295)
01-25 19:02:34.743: W/System.err(4826): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-25 19:02:34.743: W/System.err(4826): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
01-25 19:02:34.743: W/System.err(4826): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
01-25 19:02:34.743: W/System.err(4826): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
01-25 19:02:34.743: W/System.err(4826): at java.lang.Thread.run(Thread.java:818)
01-25 19:02:38.949: W/art(4826): Debugger told VM to exit with status 1
01-25 19:02:39.025: D/GraphicsStats(607): Buffer count: 3
01-25 19:02:39.026: I/WindowState(607): WIN DEATH: Window{f33f18e u0 com.myknitcards/com.myknitcards.MyKnitCardsMain}
01-25 19:02:39.029: I/WindowState(607): WIN DEATH: Window{6d143a7 u0 com.myknitcards/com.myknitcards.AvailableCards}
01-25 19:02:39.047: I/Zygote(206): Process 4826 exited cleanly (1)
01-25 19:02:39.066: I/ActivityManager(607): Process com.myknitcards (pid 4826) has died
01-25 19:02:39.068: W/ActivityManager(607): Force removing ActivityRecord{d4915cb u0 com.myknitcards/.AvailableCards t54}: app died, no saved state
01-25 19:02:39.080: I/ActivityManager(607): Start proc 4874:com.myknitcards/u0a87 for activity com.myknitcards/.MyKnitCardsMain
01-25 19:02:39.100: I/art(4874): Late-enabling -Xcheck:jni
01-25 19:02:39.157: W/System(4874): ClassLoader referenced unknown path: /data/app/com.myknitcards-1/lib/arm
01-25 19:02:39.223: D/OpenGLRenderer(4874): Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-25 19:02:39.264: I/Adreno-EGL(4874): <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
01-25 19:02:39.267: I/OpenGLRenderer(4874): Initialized EGL, version 1.4
01-25 19:02:39.342: D/Finsky(1556): [100] InAppBillingUtils.getPreferredAccount: com.myknitcards: Account from first account - [j5w9pVwTyqMNo_FRNWfkXIUz9SE]
01-25 19:02:39.346: D/Finsky(1556): [101] InAppBillingUtils.getPreferredAccount: com.myknitcards: Account from first account - [j5w9pVwTyqMNo_FRNWfkXIUz9SE]
01-25 19:02:39.347: D/com.myknitcards(4874): In-app Billing is set up OK
01-25 19:02:39.404: I/ActivityManager(607): Displayed com.myknitcards/.MyKnitCardsMain: +335ms
01-25 19:02:39.404: W/InputMethodManagerService(607): Got RemoteException sending setActive(false) notification to pid 4826 uid 10087
01-25 19:02:39.412: I/Keyboard.Facilitator(1004): onFinishInput()
01-25 19:02:40.885: D/audio_hw_primary(196): out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
01-25 19:02:40.888: I/ActivityManager(607): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.launcher/com.android.launcher2.Launcher (has extras)} from uid 1000 on display 0
01-25 19:02:40.895: D/audio_hw_primary(196): select_devices: out_snd_device(2: speaker) in_snd_device(0: none)
01-25 19:02:40.895: D/ACDB-LOADER(196): ACDB -> send_afe_cal
01-25 19:02:40.895: D/audio_hw_primary(196): enable_snd_device: snd_device(2: speaker)
01-25 19:02:40.905: D/audio_hw_primary(196): enable_audio_route: apply and update mixer path: low-latency-playback
01-25 19:02:41.013: I/Keyboard.Facilitator(1004): onFinishInput()
01-25 19:02:41.014: I/art(607): Background partial concurrent mark sweep GC freed 25641(1654KB) AllocSpace objects, 19(376KB) LOS objects, 33% free, 18MB/27MB, paused 2.227ms total 106.933ms
01-25 19:02:41.560: W/OpenGLRenderer(1111): Incorrectly called buildLayer on View: ShortcutAndWidgetContainer, destroying layer...
01-25 19:02:41.560: W/OpenGLRenderer(1111): Incorrectly called buildLayer on View: ShortcutAndWidgetContainer, destroying layer...
01-25 19:02:43.233: D/WifiStateMachine(607): starting scan for "BooNetwork-5G"WPA_PSK with 2462,5785
01-25 19:02:43.616: I/PowerManagerService(607): Going to sleep due to lid switch (uid 1000)...
01-25 19:02:43.616: I/PowerManagerService(607): Sleeping (uid 1000)...
01-25 19:02:43.621: W/AudioPolicyIntefaceImpl(196): getOutputForAttr uid 10012 tried to pass itself off as 1000
01-25 19:02:43.622: W/AudioFlinger(196): uid 10012 tried to pass itself off as 1000
01-25 19:02:43.625: I/Keyboard.Facilitator(1004): onFinishInput()
01-25 19:02:43.632: D/audio_hw_primary(196): out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
01-25 19:02:43.698: I/ActivityManager(607): Config changes=480 {1.0 310mcc?mnc en_US ldltr sw600dp w960dp h528dp 320dpi lrg land finger -keyb/v/h -nav/h s.6}
01-25 19:02:43.700: I/InputReader(607): Reconfiguring input devices. changes=0x00000004
01-25 19:02:43.700: I/InputReader(607): Device reconfigured: id=6, name='elan-touchscreen', size 1200x1920, orientation 1, mode 1, display id 0
01-25 19:02:43.703: V/AudioService.RotationHelper(607): publishing device rotation =1 (x90deg)
01-25 19:02:43.707: D/audio_hw_primary(196): adev_set_parameters: enter: rotation=90
01-25 19:02:44.040: D/Launcher.Model(1111): DbDebug Modify item (Play Music) in db, id: 4 (2, 0, 0, 0) --> (2, 0, 0, 0)
01-25 19:02:44.040: D/Launcher.Model(1111): DbDebug Modify item (Play Books) in db, id: 6 (2, 0, 1, 0) --> (2, 0, 1, 0)
01-25 19:02:44.041: D/Launcher.Model(1111): DbDebug Modify item (Play Movies & TV) in db, id: 8 (2, 0, 2, 0) --> (2, 0, 2, 0)
01-25 19:02:44.041: D/Launcher.Model(1111): DbDebug Modify item (Play Games) in db, id: 10 (2, 0, 3, 0) --> (2, 0, 3, 0)
01-25 19:02:44.042: D/Launcher.Model(1111): DbDebug Modify item (Play Newsstand) in db, id: 12 (2, 0, 0, 1) --> (2, 0, 0, 1)
01-25 19:02:44.042: D/Launcher.Model(1111): DbDebug Modify item (Google+) in db, id: 14 (2, 0, 1, 1) --> (2, 0, 1, 1)
01-25 19:02:44.043: D/Launcher.Model(1111): DbDebug Modify item (Keep) in db, id: 16 (2, 0, 2, 1) --> (2, 0, 2, 1)
01-25 19:02:44.043: D/Launcher.Model(1111): DbDebug Modify item (Calendar) in db, id: 20 (2, 0, 3, 1) --> (2, 0, 3, 1)
01-25 19:02:44.043: D/Launcher.Model(1111): DbDebug Modify item (Currents) in db, id: 22 (2, 0, 0, 2) --> (2, 0, 0, 2)
01-25 19:02:44.044: D/Launcher.Model(1111): DbDebug Modify item (Photos) in db, id: 24 (2, 0, 1, 2) --> (2, 0, 1, 2)
01-25 19:02:44.044: D/Launcher.Model(1111): DbDebug Modify item (Earth) in db, id: 26 (2, 0, 2, 2) --> (2, 0, 2, 2)
01-25 19:02:44.147: I/Keyboard.Facilitator(1004): onFinishInput()
01-25 19:02:44.190: I/Launcher(1111): Deferring update until onResume
01-25 19:02:44.191: I/Launcher(1111): Deferring update until onResume
01-25 19:02:44.202: I/WindowManager(607): Screen frozen for +551ms due to Window{b92ff9b u0 com.android.launcher/com.android.launcher2.Launcher}
01-25 19:02:44.222: V/KeyguardServiceDelegate(607): onScreenTurnedOff()
01-25 19:02:44.249: I/DisplayManagerService(607): Display device changed state: "Built-in Screen", OFF
01-25 19:02:44.249: D/SurfaceFlinger(188): Set power mode=0, type=0 flinger=0xb6aa4000
01-25 19:02:44.529: D/SurfaceControl(607): Excessive delay in setPowerMode(): 280ms
01-25 19:02:44.530: E/ANDR-PERF-LOCK(204): Failed to apply optimization for resource: 4 level: 0
01-25 19:02:44.540: D/audio_hw_primary(196): adev_set_parameters: enter: screen_state=off
01-25 19:02:44.545: W/qcom_sensors_hal(607): hal_acquire_resources, no active sensors!
01-25 19:02:44.554: E/native(607): do suspend true
01-25 19:02:44.580: D/PhoneStatusBar(705): disable: < expand ICONS* alerts SYSTEM_INFO* back home recent clock search quick_settings >
01-25 19:02:44.721: D/PhoneStatusBar(705): disable: < expand ICONS alerts SYSTEM_INFO back HOME* RECENT* clock SEARCH* quick_settings >
01-25 19:02:46.209: I/art(607): Starting a blocking GC Explicit
01-25 19:02:46.280: I/art(607): Explicit concurrent mark sweep GC freed 14241(923KB) AllocSpace objects, 8(160KB) LOS objects, 33% free, 17MB/26MB, paused 1.129ms total 70.343ms
01-25 19:02:46.953: D/audio_hw_primary(196): disable_audio_route: reset and update mixer path: low-latency-playback
01-25 19:02:46.953: D/audio_hw_primary(196): disable_snd_device: snd_device(2: speaker)
01-25 19:03:03.251: D/WifiStateMachine(607): L2Connected CMD_START_SCAN source -2 41, 42 -> obsolete
01-25 19:03:03.787: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:03:14.835: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:03:29.947: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:03:41.038: E/(193): invalid crash request of size 4 (from pid=4794 uid=0)
01-25 19:03:41.165: E/Diag_Lib(4962): Diag_LSM_Init: Failed to open handle to diag driver, error = 2
01-25 19:03:41.166: E/Sensors(4962): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:03:41.166: E/Sensors(4962): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:03:41.198: W/Sensors(4962): sns_smr_la.c(446):smr_la: smr_apps_la_thread_main is starting, fd=11, sns_smr.en_rx_msg_ptr=b6f34a08
01-25 19:03:41.261: W/Sensors(4962): sns_sam_app.c(6827):sns_sam_reg_algo: Registering algo service 16, err 0
01-25 19:03:41.272: E/Sensors(4962): sns_debug_main.c(565):Debug Config File missing in EFS!
01-25 19:03:44.187: I/Keyboard.Facilitator.LanguageModelFlusher(1004): run()
01-25 19:03:44.188: I/Keyboard.Facilitator(1004): flushDynamicLanguageModels()
01-25 19:03:44.237: I/ConfigService(1203): onCreate
01-25 19:03:49.340: I/ConfigService(1203): onDestroy
01-25 19:03:54.819: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:04:09.828: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:04:57.794: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:05:12.826: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:05:13.472: E/(193): invalid crash request of size 4 (from pid=4962 uid=0)
01-25 19:05:13.615: E/Diag_Lib(4977): Diag_LSM_Init: Failed to open handle to diag driver, error = 2
01-25 19:05:13.615: E/Sensors(4977): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:05:13.616: E/Sensors(4977): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:05:13.648: W/Sensors(4977): sns_smr_la.c(446):smr_la: smr_apps_la_thread_main is starting, fd=11, sns_smr.en_rx_msg_ptr=b6fc4a08
01-25 19:05:13.713: W/Sensors(4977): sns_sam_app.c(6827):sns_sam_reg_algo: Registering algo service 16, err 0
01-25 19:05:13.726: E/Sensors(4977): sns_debug_main.c(565):Debug Config File missing in EFS!
01-25 19:06:00.771: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:06:15.788: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:06:45.928: E/(193): invalid crash request of size 4 (from pid=4977 uid=0)
01-25 19:06:46.091: E/Diag_Lib(4991): Diag_LSM_Init: Failed to open handle to diag driver, error = 2
01-25 19:06:46.091: E/Sensors(4991): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:06:46.092: E/Sensors(4991): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:06:46.119: W/Sensors(4991): sns_smr_la.c(446):smr_la: smr_apps_la_thread_main is starting, fd=11, sns_smr.en_rx_msg_ptr=b6f2ea08
01-25 19:06:46.185: W/Sensors(4991): sns_sam_app.c(6827):sns_sam_reg_algo: Registering algo service 16, err 0
01-25 19:06:46.200: E/Sensors(4991): sns_debug_main.c(565):Debug Config File missing in EFS!
01-25 19:07:00.446: I/UsageStatsService(607): User[0] Flushing usage stats to disk
01-25 19:07:06.820: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:07:21.828: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:08:09.795: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:08:18.400: E/(193): invalid crash request of size 4 (from pid=4991 uid=0)
01-25 19:08:18.715: E/Diag_Lib(5008): Diag_LSM_Init: Failed to open handle to diag driver, error = 2
01-25 19:08:18.717: E/Sensors(5008): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:08:18.718: E/Sensors(5008): sns_fsa_la.c(386):fsa: fflush failed, 9
01-25 19:08:18.748: W/Sensors(5008): sns_smr_la.c(446):smr_la: smr_apps_la_thread_main is starting, fd=11, sns_smr.en_rx_msg_ptr=b6ffca08
01-25 19:08:18.808: W/Sensors(5008): sns_sam_app.c(6827):sns_sam_reg_algo: Registering algo service 16, err 0
01-25 19:08:18.819: E/Sensors(5008): sns_debug_main.c(565):Debug Config File missing in EFS!
01-25 19:08:24.828: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
01-25 19:09:12.771: E/NetlinkEvent(192): NetlinkEvent::FindParam(): Parameter 'UID' not found
What could probably be happening is that mServiceConn instance of ServiceConnection connection class takes some time to connect, and until the connection is established, mService remains null.
To fix this, please try the following code:
public class AvailableCards extends Activity {
IInAppBillingService mService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_cards);
String packagename = this.getPackageName();
TextView priceView = (TextView)findViewById(R.id.availablePrice);
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
new GetItemList(packagename, priceView).execute();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.available_cards, 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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class GetItemList extends AsyncTask<Integer, Integer, Long> {
private String pName;
private TextView pView;
GetItemList(String packagename, TextView priceView){
pName = packagename;
pView = priceView;
}
#Override
protected Long doInBackground(Integer... params) {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("i001");
skuList.add("i002");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, pName, "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object;
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
String mFirstIntermediate;
String mSecondIntermediate;
if (sku.equals("i001")) mFirstIntermediate = price;
else if (sku.equals("i002")) mSecondIntermediate = price;
pView.setText(sku + ": " + price);
}
}
} catch (NullPointerException ne) {
Log.d("Synch Billing", "Error Null Pointer: " + ne.getMessage());
ne.printStackTrace();
}
catch (RemoteException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error Remote: " + e.getMessage());
e.printStackTrace();
}
catch (JSONException je) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error JSON: " + je.getMessage());
je.printStackTrace();
}
return null;
}
}
i try to delete the data from listview by using the context menu and i get this java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
public List<AssignmentRecord> getAllAssignment(){
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
Cursor cursor = database.query(AssigmentContract.Assigment.TABLE_NAME, allColumn , null,
null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(0));
assignmentRecord.setAssTime(cursor.getString(1));
assignmentRecord.setAssID(cursor.getString(2));
records.add(assignmentRecord);
cursor.moveToNext();
}
first line error assignmentRecord.setAssID(cursor.getString(2));
dbcon.open();
List<AssignmentRecord> records = dbcon.getAllAssignment();
dbcon.close();
second error is List records = dbcon.getAllAssignment();
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ AssigmentContract.Assigment.TABLE_NAME +
"(" + AssigmentContract.Assigment.COLUMN_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
AssigmentContract.Assigment.COLUMN_ASS + " TEXT," +
AssigmentContract.Assigment.COLUMN_ASSDATE+ " TEXT)";
public final class AssigmentContract {
public AssigmentContract(){}
public static abstract class Assigment implements BaseColumns{
public static final String TABLE_NAME ="AssignmentV2";
public static final String COLUMN_ASS ="AssignmentTitle";
public static final String COLUMN_ASSDATE ="AssignmentDate";
public static final String COLUMN_ID ="AssignmentID";
}
}
LOGCAT
my.com.chyi.schedulev2 E/CursorWindow﹕ Failed to read row 0, column 2 from a CursorWindow which has 1 rows, 2 columns.
my.com.chyi.schedulev2 D/AndroidRuntime﹕ Shutting down VM
my.com.chyi.schedulev2 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x9e4f5908)
/my.com.chyi.schedulev2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.com.chyi.schedulev2/my.com.chyi.schedulev2.assigmentActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:434)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at my.com.chyi.schedulev2.SQLController.getAllAssignment(SQLController.java:102)
at my.com.chyi.schedulev2.assigmentActivity.onCreate(assigmentActivity.java:73)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230
at android.app.ActivityThread.access$600(ActivityThread.java:141)at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234 at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method)at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Try this,
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(cursor.getColumnIndex("your_respective_column_name));
assignmentRecord.setAssTime(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
assignmentRecord.setAssID(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
records.add(assignmentRecord);
cursor.moveToNext();
I have demonstrated what Harry suggested you to do. Here replace your_respective column name with the value you given for the columns which your trying to retrieve. For Ex: when you are trying to fetch the value of AssId it will be _id or some thing. Hope this helps you.
Your getAllAssignment() should be as,
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + TABLE_NAME, null);
if(cursor.moveToFirst()){
do {
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssID(cursor.getString(0));
assignmentRecord.setAssname(cursor.getString(1));
assignmentRecord.setAssTime(cursor.getString(2));
} while(cursor.moveToNext());
}
database.close();
I am having trouble adding another column it just bugs after 5 columns..it says in logs that i have only 5 columns...
check this
Logcat
11-05 03:31:45.455: I/dalvikvm(3845): Turning on JNI app bug workarounds for target SDK version 8...
11-05 03:31:46.395: D/dalvikvm(3845): GC_FOR_ALLOC freed 78K, 8% free 2671K/2884K, paused 80ms, total 82ms
11-05 03:31:46.405: I/dalvikvm-heap(3845): Grow heap (frag case) to 3.341MB for 635812-byte allocation
11-05 03:31:46.475: D/dalvikvm(3845): GC_FOR_ALLOC freed <1K, 7% free 3291K/3508K, paused 67ms, total 67ms
11-05 03:31:46.595: D/Insert:(3845): Inserting ..
11-05 03:31:46.595: D/Reading:(3845): Reading all naps..
11-05 03:31:47.395: D/(3845): HostConnection::get() New Host Connection established 0x2a20c298, tid 3845
11-05 03:32:01.885: D/dalvikvm(3845): GC_FOR_ALLOC freed 220K, 9% free 3584K/3936K, paused 78ms, total 91ms
11-05 03:32:30.646: D/dalvikvm(3895): GC_FOR_ALLOC freed 42K, 7% free 2671K/2848K, paused 90ms, total 93ms
11-05 03:32:30.667: I/dalvikvm-heap(3895): Grow heap (frag case) to 3.341MB for 635812-byte allocation
11-05 03:32:30.796: D/dalvikvm(3895): GC_FOR_ALLOC freed <1K, 6% free 3291K/3472K, paused 100ms, total 100ms
11-05 03:32:30.876: D/Insert:(3895): Inserting ..
11-05 03:32:30.876: D/Reading:(3895): Reading all naps..
11-05 03:32:30.976: E/CursorWindow(3895): Failed to read row 0, column 5 from a CursorWindow which has 11 rows, 5 columns.
11-05 03:32:30.986: D/AndroidRuntime(3895): Shutting down VM
11-05 03:32:30.986: W/dalvikvm(3895): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 03:32:31.016: E/AndroidRuntime(3895): FATAL EXCEPTION: main
11-05 03:32:31.016: E/AndroidRuntime(3895): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.androidsqlite/com.androidhive.androidsqlite.NapDbase}: java.lang.IllegalStateException: Couldn't read row 0, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.os.Looper.loop(Looper.java:137)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 03:32:31.016: E/AndroidRuntime(3895): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 03:32:31.016: E/AndroidRuntime(3895): at java.lang.reflect.Method.invoke(Method.java:525)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 03:32:31.016: E/AndroidRuntime(3895): at dalvik.system.NativeStart.main(Native Method)
11-05 03:32:31.016: E/AndroidRuntime(3895): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.database.CursorWindow.nativeGetString(Native Method)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.database.CursorWindow.getString(CursorWindow.java:434)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.androidhive.androidsqlite.DatabaseHandler.getAllNapChecks(DatabaseHandler.java:110)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.androidhive.androidsqlite.NapDbase.onCreate(NapDbase.java:75)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.Activity.performCreate(Activity.java:5133)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-05 03:32:31.016: E/AndroidRuntime(3895): ... 11 more
My Database.
package com.androidhive.androidsqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "NapsManager";
// NapChecks table name
private static final String TABLE_NapS = "Naps";
// NapChecks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_MALL = "mall";
private static final String KEY_LATIT = "latit";
private static final String KEY_LONGIT = "longit";
private static final String KEY_INTER = "inte";
private static final String KEY_CATE = "cate";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NapS_TABLE = "CREATE TABLE " + TABLE_NapS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_MALL + " TEXT," + KEY_LATIT + " TEXT,"
+ KEY_LONGIT + " TEXT," + KEY_INTER + " TEXT,"
+ KEY_CATE + " TEXT" +")";
db.execSQL(CREATE_NapS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NapS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new nap
void addNapCheck(NapCheck nap) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, nap.getName()); // NapCheck Name
values.put(KEY_MALL, nap.getMall()); // NapCheck Phone
values.put(KEY_LATIT, nap.getLatit()); // NapCheck Name
values.put(KEY_LONGIT, nap.getLongit());
values.put(KEY_INTER, nap.getInte());
// Inserting Row
db.insert(TABLE_NapS, null, values);
db.close(); // Closing database connection
}
// Getting single nap
NapCheck getNapCheck(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NapS, new String[] { KEY_ID,
KEY_NAME, KEY_MALL, KEY_LATIT, KEY_LONGIT, KEY_INTER, }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
NapCheck nap = new NapCheck(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3), cursor.getString(4), cursor.getString(5));
// return nap
return nap;
}
// Getting All NapChecks
public List<NapCheck> getAllNapChecks() {
List<NapCheck> NapList = new ArrayList<NapCheck>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NapS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
NapCheck nap = new NapCheck();
nap.setID(Integer.parseInt(cursor.getString(0)));
nap.setName(cursor.getString(1));
nap.setMall(cursor.getString(2));
nap.setLatit(cursor.getString(3));
nap.setLongit(cursor.getString(4));
nap.setLongit(cursor.getString(5));
// Adding nap to list
NapList.add(nap);
} while (cursor.moveToNext());
}
// return nap list
return NapList;
}
// Updating single nap
public int updateNapCheck(NapCheck nap) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, nap.getName());
values.put(KEY_MALL, nap.getMall());
values.put(KEY_LATIT, nap.getLatit());
values.put(KEY_LONGIT, nap.getLongit());
values.put(KEY_INTER, nap.getLongit());
// updating row
return db.update(TABLE_NapS, values, KEY_ID + " = ?",
new String[] { String.valueOf(nap.getID()) });
}
// Deleting single nap
public void deleteNapCheck(NapCheck nap) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NapS, KEY_ID + " = ?",
new String[] { String.valueOf(nap.getID()) });
db.close();
}
// Getting Naps Count
public int getNapChecksCount() {
String countQuery = "SELECT * FROM " + TABLE_NapS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And this is my Getters and Setters
package com.androidhive.androidsqlite;
public class NapCheck {
//private variables
int _id;
String _name;
String _mall;
String latit;
String longit;
String inte;
String cate;
// Empty constructor
public NapCheck(){
}
// constructor
public NapCheck(int id, String name, String _mall,String latit, String longit, String inte){
this._id = id;
this._name = name;
this._mall = _mall;
this.latit = latit;
this.longit = longit;
this.inte = inte;
}
// constructor
public NapCheck(String name, String _mall,String latit, String longit, String inte){
this._name = name;
this._mall = _mall;
this.latit = latit;
this.longit = longit;
this.inte = inte;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getMall(){
return this._mall;
}
// setting phone number
public void setMall(String phone_number){
this._mall = phone_number;
}
public String getLatit(){
return this.latit;
}
// setting phone number
public void setLatit(String latit){
this.latit = latit;
}
public String getLongit(){
return this.longit;
}
// setting phone number
public void setLongit(String longit){
this.longit = longit;
}
public String getInte(){
return this.inte;
}
public void setInte(String inte){
this.inte = inte;
}
public String getCate(){
return this.cate;
}
// setting phone number
public void setCate(String cate){
this.cate = cate;
}
}
I don't know what is wrong everytime i set a column in public List getAllNapChecks() it gets bugged and says i only have five columns i don't know i've been doing this for hours..Thanks in advance..Just tell if you need more
public List<NapCheck> getAllNapChecks() {
List<NapCheck> NapList = new ArrayList<NapCheck>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NapS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
NapCheck nap = new NapCheck();
nap.setID(Integer.parseInt(cursor.getString(0)));
nap.setName(cursor.getString(1));
nap.setMall(cursor.getString(2));
nap.setLatit(cursor.getString(3));
nap.setLongit(cursor.getString(4));
this line is where i get problem most of the time..
nap.setLongit(cursor.getString(5));
// Adding nap to list
NapList.add(nap);
} while (cursor.moveToNext());
}
// return nap list
return NapList;
}
Probably this isn't your first DB-schema, that you created.
You have to increase your DB-version, if you edit your DB-schema. Otherwise neither onUpdate() will not be called.
Try:
private static final int DATABASE_VERSION = 2;
I think the unwanted space and comma after the KEY_INTER(last field) is the problem change that.
Cursor cursor = db.query(TABLE_NapS, new String[] { KEY_ID,
KEY_NAME, KEY_MALL, KEY_LATIT, KEY_LONGIT, KEY_INTER}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
The onCreate (SQLiteDatabase db) method in DatabaseHandler is called only once when the database is accessed for the first time. This means that any changes to the schema will not result in this method being called.
To apply the change in schema, you can take either of two actions:
Uninstall and then install the application in the device/emulator.
Increase the value of DATABASE_VERSION in order to trigger a call to onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion). As per your implementation, this will result in the existing table being dropped and recreated.
I am getting error in my code which is not understandable.. please help me find out what issue is it.
i have database class and main activity.. it shows in log but when it comes to appear at my emulator's screen it gives me error.
my database class:
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database extends SQLiteOpenHelper {
//database name & version number
private static final String db_name = "nearby_places";
private static final int db_version = 1;
//tables
private static final String table_placetypes = "placetypes";
private static final String table_places = "table_places";
//column names
private static final String type_id = "type_id";
private static final String type_name = "type_name";
private static final String place_id = "place_id";
private static final String place_name = "place_name";
private static final String place_address = "place_address";
private static final String place_contact = "place_contact";
public Database(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
// create table queries
String create_table_placetypes = "CREATE TABLE IF NOT EXISTS " + table_placetypes + "("
+ type_id + " INTEGER PRIMARY KEY NOT NULL," + type_name + " TEXT" + ")";
String create_table_places = "CREATE TABLE IF NOT EXISTS table_places (place_id INTEGER PRIMARY KEY NOT NULL, place_name TEXT, place_address TEXT, place_contact TEXT, type_id INTEGER, FOREIGN KEY (type_id) REFERENCES table_placetypes(type_id))";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(create_table_placetypes);
Log.d("creating", "placetypes created");
db.execSQL(create_table_places);
Log.d("creating", "places created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + table_placetypes);
db.execSQL("DROP TABLE IF EXISTS " + table_places);
onCreate(db);
}
// add placetypes
void addplacetypes (placetypes pt) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(type_name, pt.getTypename());
db.insert(table_placetypes, null, values);
db.close();
}
// Getting single placetypes
placetypes getPlacetypes(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_placetypes, new String[] {type_id,
type_name }, type_id + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
placetypes pt = new placetypes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return pt;
}
// Getting All placetypes
public List<placetypes> getAllPlacetypes() {
List<placetypes> placetypesList = new ArrayList<placetypes>();
// Select All Query
String selectQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
placetypes pt = new placetypes();
pt.setTypeid(Integer.parseInt(cursor.getString(0)));
pt.setTypename(cursor.getString(1));
//String name = cursor.getString(1);
//MainActivity.ArrayofName.add(name);
// Adding contact to list
placetypesList.add(pt);
} while (cursor.moveToNext());
}
// return placetype list
return placetypesList;
}
// Getting placetypes Count
public int getPlacetypesCount() {
String countQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public void addplaces(places p) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(place_name, p.getPlace_name());
values.put(place_address, p.getPlace_address());
values.put(place_contact, p.getPlace_contact());
values.put(type_id, p.getT_id());
Log.d("Type ID", String.valueOf(p.getT_id()));
db.insert(table_places, null, values);
db.close();
}
places getPlaces(int pid) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(table_places, new String[] {place_id, place_name, place_address, place_contact,type_id}, place_id + "=?", new String[] { String.valueOf(pid) } , null, null, null, null);
if(cursor != null)
cursor.moveToFirst();
places p = new places(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)
);
cursor.close();
return p;
}
public List<places> getAllPlaces(String typeName) {
List<places> placeList = new ArrayList<places>();
//String selectQuery = "SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id ";
//String selectQuery = "SELECT * FROM table_places WHERE table_places.type_id="+Integer.toString(typeid);
String selectQuery ="SELECT * FROM table_places WHERE placetypes.place_name="+typeName+" INNER JOIN placetypes ON placetypes.type_id=table_places.type_id";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst() )
{
do{
places p = new places();
/*p.setT_id(cursor.getColumnIndex(type_id));
p.setPlace_id(cursor.getColumnIndex(place_id));
p.setPlace_name(cursor.getColumnIndex(place_name));
*/
p.setT_id(cursor.getInt(0));
p.setPlace_id(cursor.getInt(1));
p.setPlace_name(cursor.getString(2));
p.setPlace_address(cursor.getString(3));
p.setPlace_contact(cursor.getString(4));
/*String t_id = cursor.getString(4);
String p_name = cursor.getString(2);
String p_address = cursor.getString(3);
String p_contact = cursor.getString(1);*/
placeList.add(p);
}while(cursor.moveToNext());
}
cursor.close();
return placeList;
}
public int getPlaceCount () {
String selectQuery = "SELECT * FROM " +table_places;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(create_table_places, null);
cursor.close();
return cursor.getCount();
}
}
MainActivity
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
public static final String PLACETYPE = "com.example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database db = new Database(this);
if(db.getAllPlacetypes().isEmpty())
{
/**
* CRUD Operations
* */
// Inserting Places
Log.d("Insert: ", "Inserting ..");
db.addplacetypes(new placetypes("RESTURAUNTS"));
db.addplacetypes(new placetypes("MALLS"));
db.addplacetypes(new placetypes("GAS STATIONS"));
db.addplacetypes(new placetypes("HOTELS"));
db.addplacetypes(new placetypes("MOTELS"));
}
// Reading all Places
Log.d("Reading: ", "Reading all placetypes..");
if(ArrayofName.isEmpty())
{
List<placetypes> placetypes = db.getAllPlacetypes();
for (placetypes pt : placetypes)
{
String log = "Id: "+pt.getTypeid()+" ,Name: " + pt.getTypename();
// Writing Places to log
Log.d("Name: ", log);
System.out.println(log);
ArrayofName.add(pt.getTypename());
}
}
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String type = ((TextView) v).getText().toString();
Toast.makeText(getApplicationContext(), type, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
i.putExtra(PLACETYPE, type);
startActivity(i);
/*Cursor cursor = (Cursor) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "id: " +id+ "position: " +position+ "row id: " +(cursor.getColumnIndex("" +
"")), Toast.LENGTH_LONG).show();
*/
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
}
);
}
}
Logcat
10-11 17:21:51.871: D/Reading:(4932): Reading all placetypes..
10-11 17:21:51.871: D/Name:(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: I/System.out(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: D/Name:(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: I/System.out(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: D/Name:(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: I/System.out(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: D/Name:(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: D/Name:(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.887: D/AndroidRuntime(4932): Shutting down VM
10-11 17:21:51.887: W/dalvikvm(4932): threadid=1: thread exiting with uncaught exception (group=0x41c77300)
10-11 17:21:51.894: E/AndroidRuntime(4932): FATAL EXCEPTION: main
10-11 17:21:51.894: E/AndroidRuntime(4932): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nearby_places/com.example.nearby_places.MainActivity}: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Looper.loop(Looper.java:137)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invoke(Method.java:511)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-11 17:21:51.894: E/AndroidRuntime(4932): at dalvik.system.NativeStart.main(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Activity.performCreate(Activity.java:5008)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-11 17:21:51.894: E/AndroidRuntime(4932): ... 11 more
10-11 17:21:53.695: I/Process(4932): Sending signal. PID: 4932 SIG: 9
Your call to getAdapter is returning null because you're calling it before setAdapter, try this instead :
listView.setAdapter(adapter);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
If you have a NULLPOINTER Exception please have a deep look at your LogCat. Especial at the Line where it says Caused by.
Learn how to read and use your LogCat, and try to find the Line where it mentions your class/package name and analyse this line.
Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
The problem is in
List<placetypes> placetypes = db.getAllPlacetypes();
The query you are using is wrong. It should be
`SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id WHERE placetypes.place_name="+typeName+`"
I am trying to implement a SQLite database for a highscores table. I am just testing it to see if my database creation, insertion and selecting is working with the below code. I am trying to insert the first row into the database and then immediately pull from it and display the values to TextViews. All of the hardcoding is for testing purposes to just get the database working correctly.
I am getting a IllegalStateException on the below lines. I have commented in the errors on the appropriate lines.
Any additional advice on code structure is much appreciate too.
Thank you in advance!
Highscores.java
public class Highscores extends Activity {
DatabaseHelper dh;
SQLiteDatabase db;
int percentages;
long scores;
TableLayout table;
TableRow rowHeader, row1, row2, row3, row4, row5, row6, row7, row8, row9, row10;
TextView rank, percentage, score;
Button btn1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.highscoresmain);
dh = new DatabaseHelper(this);
db = dh.openDB();
long x = 11;
int y = 22;
dh.insert(x, y);
percentages = dh.getPercentage(db); //Line 45
scores = dh.getScore(db);
Button btn1 = (Button)findViewById(R.id.homeBtn);
TextView rank = (TextView)findViewById(R.id.rank);
TextView percentage = (TextView)findViewById(R.id.percentage);
TextView score = (TextView)findViewById(R.id.score);
TextView r1r = (TextView)findViewById(R.id.r1r);
TextView r1p = (TextView)findViewById(R.id.r1p);
TextView r1s = (TextView)findViewById(R.id.r1s);
rank.setText("Rank Column - TEST");
percentage.setText("Percentage Column - TEST ");
score.setText("Score Column - Test");
r1r.setText("test..rank");
r1p.setText(percentages);
r1s.setText("test..score");
table = (TableLayout)findViewById(R.id.tableLayout);
dh.closeDB(db);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
private static final String TABLE = "HighscoresList";
public static DatabaseHelper mSingleton = null;
// Table columns names.
private static final String RANK = "_id";
private static final String SCORE = "score";
private static final String PERCENTAGE = "percentage";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
}
public synchronized static DatabaseHelper getInstance(Context context) {
if(mSingleton == null) {
mSingleton = new DatabaseHelper(context.getApplicationContext());
}
return mSingleton;
}
public SQLiteDatabase openDB() {
db = this.getWritableDatabase();
return db;
}
//I am using hard coded numbers in the below 2 methods for testing purposes.
public long getScore(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + SCORE + " FROM " + TABLE + " WHERE " + SCORE + " = " + 11 + ";", null); //Line 45
long i = 0;
if(c.getCount() != 0) {
c.moveToFirst();
int columnIndex = c.getInt(c.getColumnIndex("SCORE"));
if(columnIndex != -1) {
i = c.getLong(columnIndex);
} else {
i = 999;
}
} else {
i = 555;
}
c.close();
return i;
}
public int getPercentage(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
int i = 0;
if(c.getCount() != 0) {
c.moveToFirst();
int columnIndex = c.getInt(c.getColumnIndex("PERCENTAGE"));
if(columnIndex != -1) {
i = c.getInt(columnIndex);
} else {
i = 999;
}
} else {
i = 555;
}
c.close();
return i;
}
//Insert new record.
public long insert(long score, int percentage) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values);
}
}
LogCat output
01-03 15:39:13.952: E/AndroidRuntime(938): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Highscores}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.os.Looper.loop(Looper.java:137)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 15:39:13.952: E/AndroidRuntime(938): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 15:39:13.952: E/AndroidRuntime(938): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 15:39:13.952: E/AndroidRuntime(938): at dalvik.system.NativeStart.main(Native Method)
01-03 15:39:13.952: E/AndroidRuntime(938): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.CursorWindow.nativeGetLong(Native Method)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.CursorWindow.getLong(CursorWindow.java:507)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.CursorWindow.getInt(CursorWindow.java:574)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:69)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.example.test.DatabaseHelper.getPercentage(DatabaseHelper.java:67)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.example.test.Highscores.onCreate(Highscores.java:45)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.Activity.performCreate(Activity.java:5104)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-03 15:39:13.952: E/AndroidRuntime(938): ... 11 more
EDIT: I updated my getScore() and getPercentage() methods. Anyways, I still used some hardcoded numbers so I know exactly what is going on but the program is still crashing. It seems that the if-else statement should set i to 555 instead of crashing but it isn't.
I updated the LogCat output also.
I don't see any database initializing code overriding onCreate but it says your column doesn't exist in the table check it's name again or check the table. Also get into the habit of closing your cursors once your done using them. Otherwise the database will throw errors when you haven't closed a previous cursor.
Just noticed the error its you're using "PERCENTAGE" while you defined it as
PERCENTAGE = "percentage";
so just be consistent in using the defined variable.
Android - SQLite Cursor getColumnIndex() is case sensitive?
public int getPercentage(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
int i = 0;
if (c.moveToFirst())
{
int colIdx = c.getColumnIndex(PERCENTAGE);
if (colIdx != -1) // Column exists
i = c.getInt(colIdx); //Line 54
}
c.close();
return i;
}
Building off of David's comment:
public int getPercentage(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
if(c.getCount() != 0){
c.moveToFirst();
int i = c.getInt(c.getColumnIndex(PERCENTAGE)); //Line 54
return i;
} else { return 0 }
}
Use the constant consistently, and make sure it's exactly like your sqllite DB. Apparently getColumnIndex is case sensitive ;)