I am making a music player application for my Computing project. I got it working but found that using objects would get more more marks. As a result, I changed some of my code to incorporate the use of objects, but it doesn't work when I execute my application. Btw I am quite new to Java so it's possible I made a silly mistake.
When I used this code the function I tried to implement worked:
private void SongTitleEndTime(){
try {
TextViewSongTitle = (TextView)findViewById(R.id.songTitle);
if (id != 0 ){
String where = MediaStore.Audio.Media._ID + " = " + "'" + id + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID.toString(), MediaStore.Audio.Media.ALBUM_ID.toString()}, where , null,
null);
mCursor.moveToFirst();
String title = mCursor.getString(0);
String artist = mCursor.getString(1);
String name = title + " - " + artist;
TextViewSongTitle.setText(name);
String fulltime;
albumfullid = Long.parseLong(mCursor.getString(3));
TextView EndTime = (TextView) findViewById(R.id.endtime);
long Minutes = TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration());
long Seconds = TimeUnit.MILLISECONDS.toSeconds(mMediaPlayer.getDuration()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration()));
if (Seconds < 10) {
String second = "0" + String.valueOf(Seconds);
fulltime = Minutes + ":" + second;
} else {
//else display as normal
fulltime = Minutes + ":" + Seconds;
}
EndTime.setText(fulltime);
//display the duration of song
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} //catch for errors
}
But when I tried this, I got an error:
Main Class:
private void SongTitleEndTime() {
try {
final TextView TextViewSongTitle = (TextView) findViewById(R.id.songTitle);
if (CurrentSongID != 0) {
final Song CurrentSong = new Song(CurrentSongID);
SongName = CurrentSong.SongName;
TextViewSongTitle.setText(SongName);
AlbumID = CurrentSong.AlbumID;
final TextView EndTime = (TextView) findViewById(R.id.endtime);
final String TotalSongDuration = CurrentSong.TotalDuration;
EndTime.setText(TotalSongDuration);
}
} catch (final IllegalArgumentException e) {
e.printStackTrace();
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
Object Class:
package com.example.music.test;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;
public class Song extends Activity {
private final String where;
public String SongName;
public long AlbumID;
public String TotalDuration;
public Song(final long SongID) {
where = MediaStore.Audio.Media._ID + " = " + "'" + SongID + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID.toString(),
MediaStore.Audio.Media.ALBUM_ID.toString() }, where, null, null);
mCursor.moveToFirst();
final String SongTitle = getSongTitle(mCursor);
final String SongArtist = getSongArtist(mCursor);
SongName = SongTitle + " - " + SongArtist;
AlbumID = getAlbumID(mCursor);
TotalDuration = getTotalDuration();
}
public String getSongTitle(final Cursor mCursor) {
final String songtitle = mCursor.getString(0);
return songtitle;
}
public String getSongArtist(final Cursor mCursor) {
final String songartist = mCursor.getString(1);
return songartist;
}
public long getAlbumID(final Cursor mCursor) {
final long AlbumID = Long.parseLong(mCursor.getString(3));
return AlbumID;
}
public String getTotalDuration() {
String TotalTime;
final long Minutes = TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration());
final long Seconds = TimeUnit.MILLISECONDS
.toSeconds(Player.mMediaPlayer.getDuration())
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration()));
if (Seconds < 10) {
final String second = "0" + String.valueOf(Seconds);
TotalTime = Minutes + ":" + second;
} else {
TotalTime = Minutes + ":" + Seconds;
}
return TotalTime;
}
}
The error I get is:
01-02 21:55:41.941: E/AndroidRuntime(717): FATAL EXCEPTION: main
01-02 21:55:41.941: E/AndroidRuntime(717): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.music.test/com.example.music.test.Player}: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Looper.loop(Looper.java:137)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-02 21:55:41.941: E/AndroidRuntime(717): at dalvik.system.NativeStart.main(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): Caused by: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:91)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.managedQuery(Activity.java:1737)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Song.<init>(Song.java:21)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.SongTitleEndTime(Player.java:90)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.AllActivities(Player.java:80)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.onCreate(Player.java:66)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.performCreate(Activity.java:5008)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-02 21:55:41.941: E/AndroidRuntime(717): ... 11 more
Song is an Activity. Thus you can't call manageQuery before onCreate has been called. That's your error.
Related
When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}
I get error :
FATAL EXCEPTION: main at java.lang.Integer.invalidInt
for this block :
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
MAIN CODE:
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
String[] c = data.split("limit");
int x = c.length;
if(x>1){
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
}
What is wrong?
Here is the stack trace:
FATAL EXCEPTION: main
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.tos.hidro.Terminal$2$1.run(Terminal.java:207)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
I have followed a tutorial which shows you how you can connect to an rss feed, and pull down the data into a listView. The problem is, is that I want to be able to loop through multiple feeds adding them to the same listView, but when I try to do this....it brings back the following logCat error.
If anyone can help me, that would be great thanks!
Code:
package com.androidhive.xmlparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
String[] URL = new String[2];
int count = 0;
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rssRun();
}
public void rssRun()
{
URL[0] = "http://www.skysports.com/rss/0,20514,11661,00.xml";
URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
for (int f= 0;f < 2;f++)
{
count+=1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL[f]); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
if (count==2)
{
setListAdapter(adapter);
}
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
}
LogCat:
08-27 09:34:39.786: E/Error:(30651): Expected a quoted string (position:DOCDECL #1:50 in java.io.StringReader#42be4218)
08-27 09:34:39.786: D/AndroidRuntime(30651): Shutting down VM
08-27 09:34:39.786: W/dalvikvm(30651): threadid=1: thread exiting with uncaught exception (group=0x41966da0)
08-27 09:34:39.786: E/AndroidRuntime(30651): FATAL EXCEPTION: main
08-27 09:34:39.786: E/AndroidRuntime(30651): Process: com.androidhive.xmlparsing, PID: 30651
08-27 09:34:39.786: E/AndroidRuntime(30651): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.access$900(ActivityThread.java:161)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Handler.dispatchMessage(Handler.java:102)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Looper.loop(Looper.java:157)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.main(ActivityThread.java:5356)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invokeNative(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invoke(Method.java:515)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-27 09:34:39.786: E/AndroidRuntime(30651): at dalvik.system.NativeStart.main(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): Caused by: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.rssRun(AndroidXMLParsingActivity.java:57)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate(AndroidXMLParsingActivity.java:38)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Activity.performCreate(Activity.java:5426)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
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 ;)
i have my Mapactivity which addes some items from an overlay items but whenever i tap on an item, it gives me null pointer exception and of course crashes. I've made many researches and all results say that it's due to bad construtors and Context but the problem is that their solutions doesn't work for me. here are some related topics
link 1
link2
link3
i've tryied, this, this.getApplicationContext but stil, i'have a null pointer ewception
here is where i call my overlayItems in my mapActivity class:
marker1 =getResources().getDrawable(R.drawable.maps_position_marker);
marker1.setBounds( (int) (-marker1.getIntrinsicWidth()/2),
-marker1.getIntrinsicHeight(),
(int) (marker1.getIntrinsicWidth()/2),
0);
overlay4 notFunPlaces = new overlay4(marker1, this.getBaseContext());
mapView.getOverlays().add(notFunPlaces);
// GeoPoint pt1 = notFunPlaces.getCenterPt();
int latSpan1 = notFunPlaces.getLatSpanE6();
int lonSpan1 = notFunPlaces.getLonSpanE6();
Log.v("Overlays", "Lat span is " + latSpan1);
Log.v("Overlays", "Lon span is " + lonSpan1);
my itmizedOverlay class class:
#SuppressWarnings("rawtypes")
class overlay4 extends ItemizedOverlay {
private ArrayList<OverlayItem> locations =
new ArrayList<OverlayItem>();
private Context mContext;
private PopupPanel panel=new PopupPanel(R.layout.popup);
public <getBaseContext> overlay4(Drawable marker, getBaseContext context )
{
super(boundCenterBottom(marker));
mContext = (Context) context;
// my items
.........
populates();}
#Override
protected boolean onTap(int i) {
OverlayItem item=getItem(i);
GeoPoint geo=item.getPoint();
Bitmap bitmap = null;
Point pro= mapView.getProjection().toPixels(geo, null);
if (pro!=null)
{ View view=panel.getView();
String capteur= getType (locations.get(i).getSnippet());
((TextView)view.findViewById(R.id.poptext))
.setText(String.valueOf("image captured by : " + capteur + "\n" + "Latitude = " + locations.get(i).getPoint().getLatitudeE6()/1E6 +" " + "Longitude = "+ locations.get(i).getPoint().getLongitudeE6()/1E6 +" " +
"\n" + "Image can be found at the following directory :" + locations.get(i).getTitle()
));
ImageView image= (ImageView) findViewById(R.id.ImageV);
........
my logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at tfe.rma.ciss.be.TheMap$overlay4.onTap(TheMap.java:3705)
at com.google.android.maps.ItemizedOverlay.onTap(ItemizedOverlay.java:453)
at com.google.android.maps.OverlayBundle.onTap(OverlayBundle.java:83)
at com.google.android.maps.MapView$1.onSingleTapUp(MapView.java:356)
at com.google.android.maps.GestureDetector.onTouchEvent(GestureDetector.java:533)
at com.google.android.maps.MapView.onTouchEvent(MapView.java:683)
at android.view.View.dispatchTouchEvent(View.java:3885)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1750)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1135)
at android.app.Activity.dispatchTouchEvent(Activity.java:2096)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1734)
at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2216)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1887)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
: Force finishing activity tfe.rma.ciss.be/.TheMap
tate > /data/log/dumpstate_app_error
: Force finishing activity tfe.rma.ciss.be/.menu