Unable To Start Activity - NullPointerException - java

I can't seem to trace the culprit of this bug. Here's my whole activity:
public class CalendarActivity extends Activity implements OnClickListener {
private GestureDetector mGestureDetector;
private ProgressDialog mProgressDialog;
private int mGridWidth, mGridHeight;
private MonthlyCalendarWidget mMonthlyCalendar;
private Button mNext;
private Button mPrev;
private CalendarGridAdapter mDayGridAdapter;
private CalendarEventsListAdapter mEventsListAdapter;
private CalendarAssignmentsListAdapter mAssignmentsListAdapter;
private Calendar mCalendarSource;
private String mMonthId;
private int mMonth, mYear;
private CalendarDbAdapter mCalendarDb;
private CalendarSQLiteAdapter mCalendarSQL;
private CalendarEventData mCalendarEvent;
private ArrayList<CalendarEventData> mEventsList;
private CalendarAssignmentData mCalendarAssignment;
private ArrayList<CalendarAssignmentData> mAssignmentsList;
public ArrayList<CalendarEventData> getCalendarEventData() throws Exception {
ArrayList<CalendarEventData> eventsList = CalendarDbAdapter
.getCalendarEvent("2011", 9, 36, "ParentAndroidSerpong");
return eventsList;
}
public void cacheCalendarEventData(ArrayList<CalendarEventData> data) {
for (int i = 0; i < data.size(); i++) {
mCalendarSQL.addEvents(data.get(i));
}
}
private SimpleCursorAdapter fillEventData() {
Cursor c = mCalendarSQL.fetchAllEvents();
startManagingCursor(c);
String[] from = new String[] { CalendarSQLiteAdapter.KEY_EVENTS_NAME, CalendarSQLiteAdapter.KEY_EVENTS_START_DATE };
int[] to = new int[] { R.id.monthlylistchip_texttop, R.id.monthlylistchip_textbottom };
return new SimpleCursorAdapter(this, R.layout.monthly_listchip, c, from, to);
}
public ArrayList<CalendarAssignmentData> getCalendarAssignmentData()
throws Exception {
ArrayList<CalendarAssignmentData> assignmentList = CalendarDbAdapter
.getCalendarAssignment("0970001931", "2011", "4", 36,
"ParentAndroidSerpong");
return assignmentList;
}
public void cacheCalendarAssignmentData(
ArrayList<CalendarAssignmentData> data) {
for (int i = 0; i < data.size(); i++) {
mCalendarSQL.addAssignments(data.get(i));
}
}
private void updateView(int month, int year) {
mDayGridAdapter = new CalendarGridAdapter(this,
R.id.monthly_gridchip_date, mGridWidth, mGridHeight, month,
year);
mEventsListAdapter = new CalendarEventsListAdapter(this,
R.layout.monthly_listchip, mEventsList);
mAssignmentsListAdapter = new CalendarAssignmentsListAdapter(this,
R.layout.monthly_listchip, mAssignmentsList);
mCalendarSource.set(year, month - 1,
mCalendarSource.get(Calendar.DAY_OF_MONTH));
mMonthId = (String) DateUtils.getFormattedDateString(
mCalendarSource.getTime(), DateUtils.MONTH_AND_YEAR);
mMonthlyCalendar.instantiate(this, mMonthId, mDayGridAdapter,
fillEventData(), mAssignmentsListAdapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGridHeight = ScreenUtils.getDisplayHeight(this) / 10;
mGridWidth = ScreenUtils.getDisplayWidth(this) / 7;
mNext = (Button) findViewById(R.id.monthlyview_header_monthnext);
mNext.setOnClickListener(this);
mPrev = (Button) findViewById(R.id.monthlyview_header_monthprev);
mPrev.setOnClickListener(this);
mCalendarSQL = new CalendarSQLiteAdapter(this);
mCalendarSQL.open();
try {
cacheCalendarEventData(getCalendarEventData());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCalendarSource = Calendar.getInstance(Locale.getDefault());
mMonth = mCalendarSource.get(Calendar.MONTH) + 1;
mYear = mCalendarSource.get(Calendar.YEAR);
updateView(mMonth, mYear);
}
#Override
public void onClick(View v) {
if (v == mPrev) {
if (mMonth <= 1) {
mMonth = 12;
mYear--;
} else {
mMonth--;
}
updateView(mMonth, mYear);
} else if (v == mNext) {
if (mMonth > 11) {
mMonth = 1;
mYear++;
} else {
mMonth++;
}
updateView(mMonth, mYear);
}
}
}
This is the LogCat entries of the error:
07-03 09:58:29.112: E/AndroidRuntime(5185): FATAL EXCEPTION: main
07-03 09:58:29.112: E/AndroidRuntime(5185): java.lang.RuntimeException: Unable to start activity ComponentInfo{stub.binusitdirectorate.calendar/stub.binusitdirectorate.calendar.controller.CalendarActivity}: java.lang.NullPointerException
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.os.Handler.dispatchMessage(Handler.java:99)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.os.Looper.loop(Looper.java:123)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-03 09:58:29.112: E/AndroidRuntime(5185): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 09:58:29.112: E/AndroidRuntime(5185): at java.lang.reflect.Method.invoke(Method.java:521)
07-03 09:58:29.112: E/AndroidRuntime(5185): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-03 09:58:29.112: E/AndroidRuntime(5185): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-03 09:58:29.112: E/AndroidRuntime(5185): at dalvik.system.NativeStart.main(Native Method)
07-03 09:58:29.112: E/AndroidRuntime(5185): Caused by: java.lang.NullPointerException
07-03 09:58:29.112: E/AndroidRuntime(5185): at stub.binusitdirectorate.calendar.controller.CalendarActivity.updateView(CalendarActivity.java:117)
07-03 09:58:29.112: E/AndroidRuntime(5185): at stub.binusitdirectorate.calendar.controller.CalendarActivity.onCreate(CalendarActivity.java:151)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-03 09:58:29.112: E/AndroidRuntime(5185): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-03 09:58:29.112: E/AndroidRuntime(5185): ... 11 more
All I know is that the code breaks when I called this:
mMonthlyCalendar.instantiate(this, mMonthId, mDayGridAdapter,
mEventsListAdapter, mAssignmentsListAdapter);
That method is supposed to bind adapters to my custom view.
All of the required variables are supplied, so why did the system gave me a NullPointerException?

Related

FatalCrash when I click on a Button

I have this RemoteCar App which has the Buttons,
"LOCK" -> leads you to another Acitivity.
"LOCATION" -> leads you to another Activity.
"START ENGINE" -> Lets you click on it and it changes the txt into
"ENGINE RUNNING".
"REFUEL" -> lets you refuel and increments my ProgressBar(FuelBar).
So the problem I have is that I can't click on START ENGINE or REFUEL anymore since the App keeps crashing for reasons I can not resolve, yet. I can easily click on LOCATION and LOCK those work perfectly fine.
Here I have the ErrorMessage:
05-21 13:39:52.887 1869-1869/? W/gralloc_ranchu: Gralloc pipe failed 05-21 13:39:52.897 1869-1869/? D/OpenGLRenderer: Enabling debug mode 0 05-21 13:39:53.097 1402-1429/system_process I/ActivityManager: Displayed com.example.schwarzerritter.remotecv02/.MainActivity: +546ms 05-21 13:39:53.297 1402-1429/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread) 05-21 13:39:56.857 1402-1486/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory) 05-21 13:42:00.387 1869-1869/? D/AndroidRuntime: Shutting down VM 05-21 13:42:00.387 1869-1869/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6661228) 05-21 13:42:00.387 1869-1869/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
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:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NumberFormatException: Invalid int: "AC : 18"
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.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511)
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button plusButton;
public Button minusButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
int acNum = 0;
public void onClick(View v) {
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
acNum = Integer.parseInt(seekText.getText().toString());
switch (v.getId()) {
case engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this,"Starting engine..",Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else
if(fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "No fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
}else
engButton.setText("START ENGINE");
}
break;
case refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this,"Tank is full",Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar(){
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
int acNum;
seek_bar();
lockPage();
locationPage();
}
}
java.lang.NumberFormatException: Invalid int: "AC : 18"
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
You are trying to convert the string AC : 18 to an integer in MainActivity.java line 41.
(Reading error messages helps)

How to rectify this error iin Recyclerview with database

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();
}
}
}

Music Player - Function doesn't work when trying to use objects

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.

setText make apk crash

I'm trying to develop a very simple apk.
I'm using a textView to show two team's name that i enter in a previous activity (brought here with the intent that open this activity).
When i try to use setText to show the names of these teams the apk crash.
This is the class that crash:
public class MatchPage extends Activity {
private String locali= null;
private String ospiti= null;
private TextView localiTV;
private TextView ospitiTV;
private MatchRugby partita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
localiTV =(TextView) findViewById(R.id.localiTV);
ospitiTV =(TextView) findViewById(R.id.ospitiTV);
getLocali();
getOspiti();
createMatch();
localiTV.setText("Locali /n"+ partita.teamA.getName());
ospitiTV.setText("Ospiti /n"+ partita.teamB.getName());
}
/**
* Prende il nome della squadra locale dall'intent
* #return
*/
public String getLocali(){
Intent matchStart = getIntent();
String locali = matchStart.getStringExtra(NewMatchPage.LOCALI);
return locali;
}
/**
* prende il nome della squadra ospite dall'intent
* #return
*/
public String getOspiti(){
Intent matchStart = getIntent();
String ospiti = matchStart.getStringExtra(NewMatchPage.OSPITI);
return ospiti;
}
public MatchRugby createMatch(){
TeamRugby teamLocali= new TeamRugby(locali);
TeamRugby teamOspiti= new TeamRugby(ospiti);
MatchRugby partita= new MatchRugby(teamLocali, teamOspiti);
return partita;
}
}
This is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/localiTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/ospitiTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
This is the class that send the intent:
public class NewMatchPage extends Activity {
public static final String LOCALI = null;
public static final String OSPITI = null;
private Button startMatch;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_match);
startMatch= (Button) findViewById(R.id.startMatch);
startMatch.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
startMatch();
}
});
}
public void startMatch(){
Intent startMatch= new Intent(this, MatchPage.class);
//Prendo il testo scritto nella casella locali e la porto nella partita
EditText locali= (EditText) findViewById(R.id.Locali);
String locali1 = locali.getText().toString();
startMatch.putExtra(LOCALI, locali1);
//Prendo il testo scritto nella casella ospiti e la porto nella partita
EditText ospiti= (EditText) findViewById(R.id.Ospiti);
String ospiti1 = ospiti.getText().toString();
startMatch.putExtra(OSPITI, ospiti1);
//inizio la partita
startActivity(startMatch);
}
}
And finally that's the logcat log:
04-24 16:49:08.928: W/dalvikvm(1377): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
04-24 16:49:08.958: E/AndroidRuntime(1377): FATAL EXCEPTION: main
04-24 16:49:08.958: E/AndroidRuntime(1377): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gmail.david.corsalini.sportscout/com.gmail.david.corsalini.sportscout.MatchPage}: java.lang.NullPointerException
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.os.Looper.loop(Looper.java:137)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.main(ActivityThread.java:4424)
04-24 16:49:08.958: E/AndroidRuntime(1377): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 16:49:08.958: E/AndroidRuntime(1377): at java.lang.reflect.Method.invoke(Method.java:511)
04-24 16:49:08.958: E/AndroidRuntime(1377): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-24 16:49:08.958: E/AndroidRuntime(1377): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-24 16:49:08.958: E/AndroidRuntime(1377): at dalvik.system.NativeStart.main(Native Method)
04-24 16:49:08.958: E/AndroidRuntime(1377): Caused by: java.lang.NullPointerException
04-24 16:49:08.958: E/AndroidRuntime(1377): at com.gmail.david.corsalini.sportscout.MatchPage.onCreate(MatchPage.java:25)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.Activity.performCreate(Activity.java:4465)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
04-24 16:49:08.958: E/AndroidRuntime(1377): ... 11 more
MatchRugby class
public class MatchRugby {
public TeamRugby teamA;
public TeamRugby teamB;
/**
* Costruttore della partita
*/
public MatchRugby(TeamRugby teamA, TeamRugby teamB){
this.teamA=teamA;
this.teamB=teamB;
}
/**
* #return the teamA
*/
public TeamRugby getTeamA() {
return teamA;
}
/**
* #param teamA the teamA to set
*/
public void setTeamA(TeamRugby teamA) {
this.teamA = teamA;
}
/**
* #return the teamB
*/
public TeamRugby getTeamB() {
return teamB;
}
/**
* #param teamB the teamB to set
*/
public void setTeamB(TeamRugby teamB) {
this.teamB = teamB;
}
public void EndOfMatch(){
//nothing to do with the problem
}
}
Your variable scoping is all off. set up your class like this:
public class MatchPage extends Activity {
private String locali= null;
private String ospiti= null;
private TextView localiTV;
private TextView ospitiTV;
private MatchRugby partita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
localiTV =(TextView) findViewById(R.id.localiTV);
ospitiTV =(TextView) findViewById(R.id.ospitiTV);
getLocali();
getOspiti();
createMatch();
localiTV.setText("Locali /n"+ partita.teamA.getName());
ospitiTV.setText("Ospiti /n"+ partita.teamB.getName());
}
/**
* Prende il nome della squadra locale dall'intent
* #return
*/
public String getLocali(){
if (locali == null) {
Intent matchStart = getIntent();
locali = matchStart.getStringExtra(NewMatchPage.LOCALI);
}
return locali;
}
/**
* prende il nome della squadra ospite dall'intent
* #return
*/
public String getOspiti(){
if (ospiti == null) {
Intent matchStart = getIntent();
ospiti = matchStart.getStringExtra(NewMatchPage.OSPITI);
}
return ospiti;
}
public MatchRugby createMatch(){
TeamRugby teamLocali= new TeamRugby(locali);
TeamRugby teamOspiti= new TeamRugby(ospiti);
partita = new MatchRugby(teamLocali, teamOspiti);
return partita
}
private String locali
private String ospiti
private MatchRugby partita
}
You have a NullPointerException at line #25 of your MatchPage class in onCreate method. Not sure which line exactly it is in the code you posted, but my best guess is your findViewById call fails to find anything.
java.lang.NullPointerException
at com.gmail.david.corsalini.sportscout.MatchPage.onCreate(MatchPage.java:25)
Seem that you partita object is null from the above error. And from your code where you are initializing it
createMatch();
replace the above method with below line
partita = createMatch();
Also you can change the following code::
public void createMatch(){
TeamRugby teamLocali= new TeamRugby(locali);
TeamRugby teamOspiti= new TeamRugby(ospiti);
partita= new MatchRugby(teamLocali, teamOspiti);
}

Android program problem, NullPointerExc

Well, my program keeps giveing me a null point exception and I don't know why? I know it has something to do with the lvl variable, but I don't know what? What can I do to fix this problem?
Logcat:
03-18 16:14:55.852: ERROR/AndroidRuntime(277): FATAL EXCEPTION: main
03-18 16:14:55.852: ERROR/AndroidRuntime(277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.games.think/com.games.think.Think}: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Looper.loop(Looper.java:123)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invokeNative(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invoke(Method.java:521)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at dalvik.system.NativeStart.main(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): Caused by: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.games.think.Think.onCreate(Think.java:38)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): ... 11 more
Here is some of my code:
package com.games.think;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
public class Think extends Activity implements OnClickListener{
int question = 1, lvl;
/** Called when the activity is first created. */
RadioButton lvl1;
RadioButton lvl2;
RadioButton lvl3;
RadioButton lvl4;
RadioButton lvl5;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(this);
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(this);
Button exit = (Button)findViewById(R.id.exit);
exit.setOnClickListener(this);
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
lvl1 = (RadioButton)findViewById(R.id.lvl1);
lvl2 = (RadioButton)findViewById(R.id.lvl2);
lvl3 = (RadioButton)findViewById(R.id.lvl3);
lvl4 = (RadioButton)findViewById(R.id.lvl4);
lvl5 = (RadioButton)findViewById(R.id.lvl5);
lvl = getLevel();
if(lvl == -1) {
lvl=getLevel();
}
}
#SuppressWarnings("null")
private int getLevel() {
String FILENAME = "think_level";
FileInputStream fis;
byte[] buffer = new byte[1000];
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
setLevel("1");
return -1;
}
try {
fis.read(buffer,0,1000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String level = buffer.toString();
int iLevel = Integer.valueOf(level);
return iLevel;
}
private void setLevel(String level) {
String FILENAME = "think_level";
String string = level;
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch( v.getId()){
case R.id.play:
setContentView(R.layout.play);
setQuestion();
case R.id.level:
setContentView(R.layout.level);
switch(getLevel()) {
case 1:
lvl1.setChecked(true);
case 2:
lvl2.setChecked(true);
case 3:
lvl3.setChecked(true);
case 4:
lvl4.setChecked(true);
case 5:
lvl5.setChecked(true);
}
case R.id.setLevel:
if(lvl1.isChecked()) {
setLevel("1");
}
if(lvl2.isChecked()) {
setLevel("2");
}
if(lvl3.isChecked()) {
setLevel("3");
}
if(lvl4.isChecked()) {
setLevel("4");
}
if(lvl5.isChecked()) {
setLevel("5");
}
}
}
private void setQuestion() {
}
}
Check if the button with id "setLevel" is in your main.xml. If it is somewhere else, you can not find it like this:
Button setLevel = (Button)findViewById(R.id.setLevel);
But you need an inflater.
If iunderstand this is 37-38 lines
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
Seems like setLevel is null. Is button with id setLevel described in xml layout ?
Button setLevel = (Button)findViewById(R.id.setLevel);
This line is not returning an object. Make sure you have the id right and that there is a button registered with it.

Categories

Resources