SQLite crashes when trying to enter a String with a space - java

I am creating an application that has a default table that stores what the other tables are so that when your trying to put your own input into the app it will store the tables but when you try to add a table to the default table it works perfectly unless there is a space "test" would work perfect "test 1" would crash the app. This is my code retrieving the String that is inputed by the user:
t = new Table(this);
t.open();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
rListName = input.getText().toString();
t.createNew(rListName + "DB");
t.createList(rListName, rListName + "DB");
t.close();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
This is my createNew and createList:
public void createNew(String TABLE_NAME){
if(DATABASE_STATUS == "new"){
ourHelper.createNew(ourDatabase, TABLE_NAME);
System.out.println("Creating " + TABLE_NAME);
}else{
System.out.print("Already Created");
}
}
public long createList(String listName, String listDB){
ContentValues cv = new ContentValues();
cv.put(KEY_LISTNAME, listName);
cv.put(KEY_LISTDB, listDB);
return ourDatabase.insert(DEFAULT_TABLE, null, cv);
}
my createNew() that is executed to make new tables
public void createNew(SQLiteDatabase db, String TABLE_NAME){
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_QUESTION + " TEXT NOT NULL, " +
KEY_PATH + " TEXT NOT NULL);"
);
}
last but not lease, my logcat:
11-25 22:02:30.418: I/SqliteDatabaseCpp(24726): sqlite returned: error code = 1, msg = near "helloDB": syntax error
11-25 22:02:30.428: D/AndroidRuntime(24726): Shutting down VM
11-25 22:02:30.428: W/dalvikvm(24726): threadid=1: thread exiting with uncaught exception (group=0x40ab9228)
11-25 22:02:30.438: E/AndroidRuntime(24726): FATAL EXCEPTION: main
11-25 22:02:30.438: E/AndroidRuntime(24726): android.database.sqlite.SQLiteException: near "helloDB": syntax error: , while compiling: CREATE TABLE hello helloDB (_id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, path TEXT NOT NULL);
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:141)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:368)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:272)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:84)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:2031)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1971)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.mitterederStudios.Quiz.Table$DbHelper.createNew(Table.java:49)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.mitterederStudios.Quiz.Table.createNew(Table.java:94)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.mitterederStudios.Quiz.Menu$1.onClick(Menu.java:56)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.os.Looper.loop(Looper.java:154)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.app.ActivityThread.main(ActivityThread.java:4945)
11-25 22:02:30.438: E/AndroidRuntime(24726): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 22:02:30.438: E/AndroidRuntime(24726): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-25 22:02:30.438: E/AndroidRuntime(24726): at dalvik.system.NativeStart.main(Native Method)

You need to put quotes around your table name so its "test 1" if you really want spaces. However this is generally a bad idea, I would replace the spaces with underscores so it becomes test_1.

Related

Handler{40664220} sending message to a Handler on a dead thread

I am getting this error my code is, can anyone help please
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new FetchAddressTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Constants.USER_CURRENT_LOCATION);
else
new FetchAddressTask().execute(Constants.USER_CURRENT_LOCATION);
class FetchAddressTask extends AsyncTask<LatLng, String, String> {
#Override
protected void onPreExecute() {
// showDialog();
// showMyDialog();
DialogHelper.showTrasparentDialog(EnterBikeInfoActivity.this);
super.onPreExecute();
}
#Override
protected String doInBackground(LatLng... latLngs) {
String result = getCurrentLocationViaJSON(latLngs[0].latitude, latLngs[0].longitude);
if (result == null)
result = "";
return result;
}
#Override
protected void onPostExecute(String result) {
if (result == null || result.length() == 0) {
DialogHelper.showDialogMessage(BikeApp.getInstance(), "Unable to retrieve the address.");
} else {
addressEditText.setText(result);
}
DialogHelper.dismissTransparentDialog();
super.onPostExecute(result);
}
}
public String getCurrentLocationViaJSON(double lat, double lng) {
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
// String street_address = null;
// String postal_code = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if (status.equalsIgnoreCase("OK")) {
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i + "," + results.length()); // TODO delete this
JSONObject r0 = results.getJSONObject(i);
String v = r0.getString("formatted_address");
currentLocation = v;
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing", "Failed to load JSON");
e.printStackTrace();
}
return "";
}
getLocationInfo(lat, lng); funtion fetches address info from an http request, my flow is coming into FetchAddressTask doInBackground with correct address but when it return the address it give me this error message.
11-25 11:20:01.746: W/MessageQueue(2593): Handler{40664220} sending message to a Handler on a dead thread
11-25 11:20:01.746: W/MessageQueue(2593): java.lang.RuntimeException: Handler{40664220} sending message to a Handler on a dead thread
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessageAtTime(Handler.java:457)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessageDelayed(Handler.java:430)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessage(Handler.java:367)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Message.sendToTarget(Message.java:349)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.AsyncTask$3.done(AsyncTask.java:214)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask$Sync.innerSet(FutureTask.java:253)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask.set(FutureTask.java:113)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:311)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
11-25 11:20:01.746: W/MessageQueue(2593): at java.lang.Thread.run(Thread.java:1019)

java.lang.NullPointerException is caused by getContentResolver() in Fragment

I have this code below. It works before in Activity. Now I want to convert it to Fragment. I have tried context.getContentResolver(); or getActivity().getContentResolver(); But it doesn't work. How to fix this ?
public class MyFragmentA extends Fragment {
//song list variables
private ArrayList<Song> songList;
private ListView songView;
public Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
//retrieve list view
songView = (ListView) myFragmentView.findViewById(R.id.song_list);
//instantiate list
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
//create and set adapter
SongAdapter songAdt = new SongAdapter(this.getActivity(), songList);
songView.setAdapter(songAdt);
return myFragmentView;
}
public void getSongList() {
ContentResolver musicResolver = context.getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
----------------------
----------------------
----------------------
----------------------
}
}
}
This my logcat trace
11-25 20:29:34.001: E/AndroidRuntime(4092): FATAL EXCEPTION: main
11-25 20:29:34.001: E/AndroidRuntime(4092): Process: com.ddev.delta, PID: 4092
11-25 20:29:34.001: E/AndroidRuntime(4092): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ddev.delta/com.ddev.delta.AndroidNavigationTabsActivity}: java.lang.NullPointerException
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.access$800(ActivityThread.java:144)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.os.Handler.dispatchMessage(Handler.java:102)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.os.Looper.loop(Looper.java:136)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.main(ActivityThread.java:5146)
11-25 20:29:34.001: E/AndroidRuntime(4092): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 20:29:34.001: E/AndroidRuntime(4092): at java.lang.reflect.Method.invoke(Method.java:515)
11-25 20:29:34.001: E/AndroidRuntime(4092): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
11-25 20:29:34.001: E/AndroidRuntime(4092): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
11-25 20:29:34.001: E/AndroidRuntime(4092): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
11-25 20:29:34.001: E/AndroidRuntime(4092): at dalvik.system.NativeStart.main(Native Method)
11-25 20:29:34.001: E/AndroidRuntime(4092): Caused by: java.lang.NullPointerException
11-25 20:29:34.001: E/AndroidRuntime(4092): at com.ddev.delta.AndroidNavigationTabsActivity.onCreate(AndroidNavigationTabsActivity.java:17)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.Activity.performCreate(Activity.java:5231)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
11-25 20:29:34.001: E/AndroidRuntime(4092): ... 12 more
ContentResolver musicResolver = context.getContentResolver();
Your context is not initialized.
Since you're in a fragment lifecycle callback onCreateView() or a method called from one, you can use getActivity() for a Context:
ContentResolver musicResolver = getActivity().getContentResolver();
Remove the Context context; declaration as unnecessary, too.
public Context context;
Your context is null, try use getActivity().getContentResolver();
Initialize context object in onCreateView() before call getSongList():
context = getActivity();
OR
getActivity().getContentResolver()
Create an object of Activity and then initialize it by
Activity a=getActivity();
And then use
ContentResolver musicResolver = a.getContentResolver();
Use Following for these Cases:
Application :- getApplicationContext()
activity :- context
Fragment :- getActivity()

Android: Unable to find resource ID Exception

In my Android application i am creating a pie chart using achartengine library. When click a button it takes data from sqlite database and draw a pie chart. This is my code segment.
btnpieChart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SelectDBAdapter selectDBAdapter = SelectDBAdapter
.getDBAdapterInstance(getActivity());
try {
selectDBAdapter.openDataBase();
chartDataMap = selectDBAdapter
.getPieChartData(strBusinessUnit,
currentPeriod, currentYear);
} catch (Exception e) {
selectDBAdapter.close();
e.printStackTrace();
} finally {
selectDBAdapter.close();
}
System.out.println("chartDataMap === "+ chartDataMap);
if (chartDataMap.size() > 0) {
for (Map.Entry<String, Double> entry : chartDataMap.entrySet()) {
lstBrandNames.add(entry.getKey());
lstAchievedVals.add(entry.getValue());
}
ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
System.out.println("distribution === " + distribution);
lstBrandNames = set_lables(lstBrandNames, distribution);
CategorySeries distributionSeries = new CategorySeries(
"Brands - Achievement Progress");
for (int i = 0; i < distribution.size(); i++) {
distributionSeries.add(lstBrandNames.get(i), distribution.get(i));
}
DefaultRenderer defaultRenderer = new DefaultRenderer();
defaultRenderer.setApplyBackgroundColor(true);
defaultRenderer.setBackgroundColor(Color.WHITE);
for (int i = 0; i < distribution.size(); i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
seriesRenderer.setColor(color);
seriesRenderer.setGradientEnabled(false);
seriesRenderer.setDisplayChartValues(true);
seriesRenderer.setShowLegendItem(false);
defaultRenderer.setLabelsTextSize(25);
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsColor(Color.BLACK);
defaultRenderer.setChartTitle("Brands - Achievement Progress");
defaultRenderer.setChartTitleTextSize(30);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setShowLabels(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
}
});
My mChartView is,
private GraphicalView mChartView = null;
Log cat says:
11-25 07:03:58.311: E/AndroidRuntime(2706): FATAL EXCEPTION: main
11-25 07:03:58.311: E/AndroidRuntime(2706): android.content.res.Resources$NotFoundException: Unable to find resource ID #0xffffffff
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.content.res.Resources.getResourceName(Resources.java:1659)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.handleCallback(Handler.java:725)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.dispatchMessage(Handler.java:92)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Looper.loop(Looper.java:137)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-25 07:03:58.311: E/AndroidRuntime(2706): at dalvik.system.NativeStart.main(Native Method)
I would be much obliged if anyone could explain what's going on here and how can I solve this issue.
Thanks
Check these lines
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
especially mChartView.getId() log this value and check it with what you expected

Error in fetching data from database table

I am making an android app. and am trying to fetching data from column, name and score from
the database table but getting this error at run time,
Sorry this application has stopped unexpectedly.
This is my Code from Database Class,
public long addscore(String name, int score)
{
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_score, score);
// Inserting Row
return db.insert(DATABASE_TABLE, null, values);
}
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },,KEY_scoreid + "="
+ rowid,null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
And this is the code of class from where i m trying to
fetch the Data from Database table (Highscore.java),
public class Highscore extends Activity
{
TextView name1,name2,name3,name4,name5,score1,score2,score3,score4,score5;
DBAdapter db1;
Cursor c;
int id;
String n1,n2,n3,n4,n5;
String s1,s2,s3,s4,s5;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
Button backbtn=(Button)findViewById(R.id.backbtn);
OnClickListener listener=new OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Highscore.this,MainActivity.class);
startActivity(i);
finish();
}
};
backbtn.setOnClickListener(listener);
id=1;
name1=(TextView)findViewById(R.id.name1);
score1=(TextView)findViewById(R.id.score1);
db1=new DBAdapter(this);
db1.open();
c=db1.getScore(1);
n1=c.getString(1);
name1.setText(n1);
s1=c.getString(2);
score1.setText(s1);
c=db1.getScore(2);
n2=c.getString(1);
name2.setText(n2);
s2=c.getString(2);
score2.setText(s2);
c=db1.getScore(3);
n3=c.getString(1);
name3.setText(n3);
s3=c.getString(2);
score3.setText(s3);
id++;
c=db1.getScore(4);
n4=c.getString(1);
name4.setText(n4);
s4=c.getString(2);
score4.setText(s4);
id++;
c=db1.getScore(5);
n5=c.getString(1);
name5.setText(n5);
s5=c.getString(2);
score5.setText(s5);
c.deactivate();
c.close();
db1.close();
}
}
This time i am only fetching 5 names and scores.
Here's my Logcat Error,
09-19 12:01:36.046: D/AndroidRuntime(455): Shutting down VM
09-19 12:01:36.046: W/dalvikvm(455): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-19 12:01:36.066: E/AndroidRuntime(455): FATAL EXCEPTION: main
09-19 12:01:36.066: E/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.Highscore}: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Looper.loop(Looper.java:123)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invoke(Method.java:521)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-19 12:01:36.066: E/AndroidRuntime(455): at dalvik.system.NativeStart.main(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at com.example.quizapp.Highscore.onCreate(Highscore.java:59)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-19 12:01:36.066: E/AndroidRuntime(455): ... 11 more
If you people are not getting any thing from my question so please ask..
Please help me to Solve out the Error.
Thanks in Advance
From what I see you problem is not in the database connection, you have some untreated exceptions. You have a NULL pointer exception also in onCreate(Highscore.java:59)
You can do a thing: comment parts of the code until you get a working app(that does nothing) and then uncomment until you find the exact code that crashes the app, it is easy to do and usually you will find the line that is problematic
Good luck
Use this code insted of your.....
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },KEY_scoreid + " ='"
+ rowid + "'",null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}

App Crashes When Reading Contacts

I've got a crash while trying to read the contacts of the user, I thought because it's because of the Emulator, but I want to triple check, as I don't have an android based phone. The Logcat gives an error that, it can't read the row "id" did I incorrectly name that string?
Lastly, how would I implement a dialogue box, to see if the user wants the app to read the contacts?
Thanks so much:)
Code:
private void checkandImportContacts() {
// TODO Auto-generated method stub
SharedPreferences sp = getSharedPreferences(PREFS_CHECK, 0);
String checkfirstime = sp.getString("key3", null);
if(checkfirstime !=null && equals("sdhdasudafdsugdiasgdas38ey98d1diass")) {
finish();
} else {
Cursor cursor = getContacts();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Toast.makeText(getApplicationContext(), displayName, Toast.LENGTH_LONG).show();
}
}
}
private Cursor getContacts() {
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ‘" + ("1") + "’";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
LogCat:
04-23 16:49:48.288: E/AndroidRuntime(437): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: android.database.sqlite.SQLiteException: no such column: ‘1’: , while compiling: SELECT _id, display_name FROM view_contacts_restricted WHERE (in_visible_group = ‘1’) ORDER BY display_name COLLATE LOCALIZED ASC
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.os.Looper.loop(Looper.java:123)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-23 16:49:48.288: E/AndroidRuntime(437): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 16:49:48.288: E/AndroidRuntime(437): at java.lang.reflect.Method.invoke(Method.java:521)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-23 16:49:48.288: E/AndroidRuntime(437): at dalvik.system.NativeStart.main(Native Method)
04-23 16:49:48.288: E/AndroidRuntime(437): Caused by: android.database.sqlite.SQLiteException: no such column: ‘1’: , while compiling: SELECT _id, display_name FROM view_contacts_restricted WHERE (in_visible_group = ‘1’) ORDER BY display_name COLLATE LOCALIZED ASC
04-23 16:49:48.288: E/AndroidRuntime(437): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentResolver.query(ContentResolver.java:245)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.Activity.managedQuery(Activity.java:1520)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.getContacts(ChatService.java:73)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.checkandImportContacts(ChatService.java:56)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:46)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
You use the wrong chars in your query
Caused by: android.database.sqlite.SQLiteException: no such column: ‘1’
SQLite tries to interpret the ‘1’ as column name since it is no primitive value. Values in SQLite are surrounded by ', column names by " or nothing.
if that group thing is dynamic do it like this:
int group = 1;
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?";
String[] selectionArgs = new String[] { String.valueOf(group) };
The value is automatically wrapped in ' & escaped then. If the value is static you can simply do
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = 1";
String[] selectionArgs = null;
private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
The above retrun all the name and number from from your contact database..

Categories