Android ArrayList Index Out Of Bounds - java

I'm fairly new to Android and am having an issue with fetching data from my database. I have an activity class which calls the database helper to get a list of questions according to a particular category. The database should then put all of the questions into an ArrayList and return them. The error seems to be occurring when I try and get the first question in the list of questions using:
Question question = questions.get(0);
Here is the relevant method in the activity class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atomic_structure_questions);
DatabaseHelper database = new DatabaseHelper(getApplicationContext());
List<Question> questions = database.getQuestions(1);
Question question = questions.get(0);
TextView questionText = (TextView) findViewById(R.id.QuestionText);
questionText.setText(question.getText());
}
Database Helper:
// Get All The Question From Database For A Specific Category And Put Them Into A List Of Question
public List<Question> getQuestions(int category) {
List<Question> questions = new ArrayList<Question>();
String selectQuery = "SELECT * FROM " + TABLE_QUESTION +
" WHERE " + KEY_CATEGORY_ID + " = '" + category + "'";
Log.e(LOG, selectQuery);
database = this.getReadableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
// Loops Through The Database To Get All Question Matching Category
do {
Question question = new Question();
question.setId(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ID)));
question.setNumber(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUMBER)));
question.setText(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_TEXT)));
question.setMarks(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_MARKS)));
question.setAnswer(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ANSWER)));
question.setMC1(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC1)));
question.setMC2(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC2)));
question.setMC3(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC3)));
question.setMC4(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC4)));
// Add The Question To The List Of Question
questions.add(question);
} while (cursor.moveToNext());
}
return questions;
}
Finally, here is the logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.revision.aschemistry/com.revision.aschemistry.AtomicStructureQuestions}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
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:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.revision.aschemistry.AtomicStructureQuestions.onCreate(AtomicStructureQuestions.java:26)
at android.app.Activity.performCreate(Activity.java:4465)
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:787)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
            at dalvik.system.NativeStart.main(Native Method)
Any help is much appreciated, thanks in advance.

It seems your ArrayList Question is Empty. So just check size before getting data from it.
List<Question> questions = database.getQuestions(1);
if(!questions.isEmpty())
{
Question question = questions.get(0);
}else
{
Log.e("LOG","questions is Empty")
}
Also check Cursor size in your getQuestions() method from DatabaseHelper class.

Obviously you can use:
if(!questions.isEmpty())
To avoid the the ArrayIndexOutOfBounds Exception. But I guess that dosen't Solve our problem dose it?
I hope our solution here is to read the data properly and then retrieve the data using the get() method of Arraylist.
There needs to be a check before reading the data. Please check if the data are feed properly first and then go for getting them. I would like to suggest some posts you can follow to get idea about Databases.
http://www.vogella.com/tutorials/AndroidSQLite/article.html
http://infobloggall.com/2014/05/06/sqlite-database-example
Also the developer site.

Related

IllegalStateException when trying selecting photo from Google Photos app

This code used to work fine with the Nexus 5 image gallery. Ever since moving to the newer Google Photos app selecting images crash this code.
Error:
08-07 10:10:10.792 25086-25086/com.app.app E/CursorWindow﹕ Failed to
read row 0, column -1 from a CursorWindow which has 1 rows, 7 columns.
08-07 10:10:10.795 25086-25086/com.app.app D/AndroidRuntime﹕ Shutting
down VM 08-07 10:10:10.801 25086-25086/com.app.app E/AndroidRuntime﹕
FATAL EXCEPTION: main
Process: com.app.app, PID: 25086
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent {
dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/17870/ACTUAL/1285012603
flg=0x1 (has clip) }} to activity
{com.app.app/com.app.app.PhotoActivity}:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from
CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
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.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at android.database.CursorWrapper.getString(CursorWrapper.java:114)
at com.app.app.PhotoActivity.getRealPathFromURI(PhotoActivity.java:456)
at com.app.app.PhotoActivity.onActivityResult(PhotoActivity.java:436)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
            at android.app.ActivityThread.access$1300(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
ONACTIVITYRESULT:
case ACTION_SELECT_PHOTO: {
if (resultCode == RESULT_OK) {
Uri selectedImageURI = data.getData();
File imageFile = new File(getRealPathFromURI(selectedImageURI)); // LINE 436
mCurrentPhotoPath = imageFile.toString();
if (mCurrentPhotoPath != null) {
setPic();
mCurrentPhotoPath = null;
}
}
break;
}
GETREALPATHFROMURI:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx); // HERE IS THE ERROR: LINE 456
cursor.close();
}
return result;
}
I'd guess my issue is in one of two places, either getContentResolver().query needs to use some newer method. OR the getColumnIndex(MediaStore.Images.ImageColumns.DATA) MediaStore is the incorrect way to deal with the newer cloud based photo apps.
A URI does not mean there is a file. An app is able to provide the contents through any mechanism it wants (a local file, a local file in a private directory you can't read, streamed over the internet, built dynamically on the fly).
Instead, you should use ContentResolver.openInputStream(contentUri) to get the contents from a URI. You can then transform that into a Bitmap via BitmapFactory.decodeStream()

android Unable to start activity ComponentInfo NULL Point Exception

My app work strange on diffrent phones - once everything is fine and other time it crash when i try to make photo and save it in my phone's memory. Photo shows up in folder in memory, but when we should come back to application it is shut down:
06-14 23:58:37.448 12344-12344/com.apps.madzia.photo_application E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.apps.madzia.photo_application, PID: 12344
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apps.madzia.photo_application/com.apps.madzia.photo_application.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2412)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
at android.app.ActivityThread.access$1000(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.GridView.setAdapter(GridView.java:187)
at com.apps.madzia.photo_application.fragments.FragmentGallery.onCreateView(FragmentGallery.java:42)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1917)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:544)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5468)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2385)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
            at android.app.ActivityThread.access$1000(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
The code of my function to make photos:
public void make_photo() {
Calendar c;
c = Calendar.getInstance();
imageName = "fotka_" + c.get(Calendar.YEAR) + "_" + c.get(Calendar.MONTH) + "_" + c.get(Calendar.DAY_OF_MONTH)
+ "_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE) + "_" + c.get(Calendar.SECOND);
File katalog = new File(IMAGE_FILE_PATH);
File photo = new File(IMAGE_FILE_PATH+imageName + ".jpg");
if( Environment.getExternalStorageState() == Environment.MEDIA_UNKNOWN || Environment.getExternalStorageState() == Environment.MEDIA_REMOVED || Environment.getExternalStorageState() == Environment.MEDIA_UNMOUNTED) {
Log.d("ExternalStorage", "cannot find memory SD card");
File file = new File(getFilesDir(), imageName);
IMAGE_FILE_PATH = file.getParent()+"/";
Log.d("IMAGE_FILE_PATH", IMAGE_FILE_PATH);
}else {
}
Log.d("photo", photo.getPath());
if (!katalog.exists()) {
katalog.mkdirs();
}
try {
// fotka = File.createNewFile(imageName, ".jpg", katalog);
photo.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent zdjecie = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
zdjecie.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(zdjecie, 1);
}
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.GridView.setAdapter(GridView.java:187)
at com.apps.madzia.photo_application.fragments.FragmentGallery.onCreateView(FragmentGallery.java:42)
This means that in your FragmentGallery in onCreateView method on line 42 u are setting null ArrayAdapter

I can't find this NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have an issue I need help with. I am running into a NullPointerException no matter what I do with this app, and at this point it is seriously holding up this project. I have reviewed the logcat multiple times, made changes and re run the app and every time it turns out a nullpointerexception. For the life of me I can't seem to figure out what is causing it. Can someone point out where it is, and if possible, why it occurred since as far as I can tell I have everything assigned a value.
GameStart.java:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity {
/**
* Necessary activity variables
*/
int clickCount = 0;
TextView storyText;
Button advanceGame;
DecisionFragment decisionFragment;
ControlsFragment controlsFragment;
public View.OnClickListener decisionTime = new View.OnClickListener(){
public void onClick(View v) {
clickCount = clickCount + 1; // Increments clickCount by 1 per click
// /**
// * Will handle checking how far into the story the player is
// * and update components as necessary.
// */
// switch (clickCount) {
// case 1:
// storyText.setText(R.string.story_opening_two);
// break;
//
// case 2:
// FragmentTransaction decisionTime = fragmentManager.beginTransaction();
// // Replace the fragment currently inside of the fragmentContainer
// decisionTime.replace(R.id.fragmentContainer, decisionFragment);
// decisionTime.commit();
// break;
//
// default:
// System.out.println("An error occurred");
// }
// System.out.println(clickCount);
}
};
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
// UI element handles
advanceGame = (Button) findViewById(R.id.advanceButton);
storyText = (TextView) findViewById(R.id.storyText);
decisionFragment = new DecisionFragment();
controlsFragment = new ControlsFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// UI will add the ControlsFragment in it's starting state for that activity.
fragmentTransaction.add(R.id.fragmentContainer, controlsFragment).commit();
// Sets the advanceButton to run decisionTime method
advanceGame.setOnClickListener(decisionTime);
}
}
LogCat:
12-07 13:16:10.142 19915-19915/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.saphiric.simproject, PID: 19915
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
            at android.app.ActivityThread.access$800(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5872)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
            at dalvik.system.NativeStart.main(Native Method)
The null pointer happens at line 75 , i.e.
advanceGame.setOnClickListener(decisionTime);
Here, the only thing that can be null is advanceGame. This means that
advanceGame = (Button) findViewById(R.id.advanceButton);
is not able to find your button from your view. Check the id of the button if its exactly the same as you defined it in your android xml.
I believe that advanceGame is null.
You can't find button by findViewById(R.id.advanceButton);
NPE is at line 75
advanceGame.setOnClickListener(decisionTime);
it is clear from
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
Looks like at
advanceGame = (Button) findViewById(R.id.advanceButton);
view was not found. You can debug that or add check at 75
if(null != advanceGame) advanceGame = (Button) findViewById(R.id.advanceButton);
I think just check #+id of your activity_game_start.xml layout of advanceGame button
it might have different name

ListViewAnimation insert() NullPointerException on notifyDataSetChanged()

I'm using the ListViewAnimation library and been trying to do the add-item animation for my ListView.
In order to implement such animation, their documentation says that I should do this:
To use this functionality, simply let your adapter implement Insertable, and call one of the insert methods on the DynamicListView:
MyInsertableAdapter myAdapter = new MyInsertableAdapter(); // MyInsertableAdapter implements Insertable
mDynamicListView.setAdapter(myAdapter);
mDynamicListView.insert(0, myItem); // myItem is of the type the adapter represents.
So here's what I did:
I had my Listview be a DynamicListView(I'm using ButterKnife) and set it to use my adapter
#InjectView(R.id.flow_list)
DynamicListView mFlowList;
mFlowListAdapter = new FlowListAdapter(getActivity(), mItems);
mFlowList.setAdapter(mFlowListAdapter);
Made my adapter implement the 'Insertable' interface and overridden its abstract method:
#Override
public void add(int i, #NonNull Object o) {
Item newItem = (Item)o;
mList.add(Item);
notifyDataSetChanged();
}
Call insert() on my ListView
#OnClick(R.id.done)
void addItem() {
...
mFlowList.insert(0,item);
}
But when I ran my app and clicked that done button that triggers the insert() of my ListView I got a NullPointerException saying:
09-15 11:51:41.046 14660-14660/com.jezer.MyApp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter$HeightUpdater.onAnimationUpdate(AnimateAdditionAdapter.java:352)
at com.nineoldandroids.animation.ValueAnimator.animateValue(ValueAnimator.java:1178)
at com.nineoldandroids.animation.ValueAnimator.animationFrame(ValueAnimator.java:1139)
at com.nineoldandroids.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:545)
at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:928)
at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:951)
at com.nineoldandroids.animation.AnimatorSet.start(AnimatorSet.java:502)
at com.nineoldandroids.animation.AnimatorSet.start(AnimatorSet.java:502)
at com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter.getView(AnimateAdditionAdapter.java:318)
at android.widget.AbsListView.obtainView(AbsListView.java:2232)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1253)
at android.widget.ListView.onMeasure(ListView.java:1162)
at android.view.View.measure(View.java:15775)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15775)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2193)
at android.view.View.measure(View.java:15775)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2212)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1291)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1486)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1181)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4942)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
I'm not getting this exception when I commented out the notifyDataSetChanged() on the add() method. However that's the only way I know to refresh my listview and hopefully see an addition animation to it.
Are you perhaps doing this:
convertView = inflater.inflate(R.layout.cell, null);
Instead of this? convertView = inflater.inflate(R.layout.page_cell, parent, false);

Getting CheckBox Data into a Bundle

I've done it before. It's not rocket science. A beautiful activity containing a perfect form. An EditText here... A Spinner there. But this time there are CheckBox'es.
This should be easy: setup the onClick() method declared in the XML, grab the ID of the view...
...thing is, I've been using a Bundle to gather all the data in the form together and send to my IntentService to drop into the SQLite database.
/**
* Called when the user changes the state of any CheckBox
* #param view The View that was checked/unchecked */
public void onCheckBoxChng(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
String mField = new String();
// Check which checkbox was clicked
switch(view.getId()){
case R.id.dlg_add_ply_chk1:
mField = "Platinum";
break;
case R.id.dlg_add_ply_chk2:
mField = "Gold";
break;
case R.id.dlg_add_ply_chk3:
mField = "Silver";
break;
case R.id.dlg_add_ply_chk4:
mField = "Bronze";
break;
case R.id.dlg_add_ply_chk5:
mField = "HQ";
break;
case R.id.dlg_add_ply_chk6:
mField = "Aurora-1";
break;
}
if (checked) {
setBundleChk(mField,1);
} else {
setBundleChk(mField,0);
}
}
/**
* Set the boolean fields in mBdlgForm based on user action on the checkboxes
*
* #param Field The field name to change
* #param State The state to set (<code>true</code> or <code>false</code> */
private void setBundleChk(String Field, int State){
if (BuildConfig.DEBUG) {
Log.i(Constants.TAG_ACTDLGADDPLYR,
"setBundleChk(Field, State) called with: "+Field+", and "+State);
Log.i(Constants.TAG_ACTDLGADDPLYR, "setBundleChk(): mBdlgForm Keys :");
for (String key: mBdlgForm.keySet()){
Log.d (Constants.TAG_FRGACTPLAYERS, "mBdlgForm."+key);
}
}
if (State == 1) {
mBdlgForm.putBoolean(Field, true);
} else {
mBdlgForm.putBoolean(Field, false);
}
}
Piece of cake, right?
Problem is, though the Bundle's scope is the entire activity, it can't been seen in the onClick() callback for the CheckBox'es NOR in any function I call from the onClick() callback...
...Please tell me... What am I missing?
Even after implementing "Activity.this.method()" I'm still getting the following Logcat messages:
03-04 20:09:32.349: E/AndroidRuntime(641): FATAL EXCEPTION: main
03-04 20:09:32.349: E/AndroidRuntime(641): java.lang.IllegalStateException: Could not execute method of the activity
03-04 20:09:32.349: E/AndroidRuntime(641): at android.view.View$1.onClick(View.java:3591)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.view.View.performClick(View.java:4084)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.widget.CompoundButton.performClick(CompoundButton.java:100)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.view.View$PerformClick.run(View.java:16966)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.os.Handler.handleCallback(Handler.java:615)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.os.Handler.dispatchMessage(Handler.java:92)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.os.Looper.loop(Looper.java:137)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-04 20:09:32.349: E/AndroidRuntime(641): at java.lang.reflect.Method.invokeNative(Native Method)
03-04 20:09:32.349: E/AndroidRuntime(641): at java.lang.reflect.Method.invoke(Method.java:511)
03-04 20:09:32.349: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-04 20:09:32.349: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-04 20:09:32.349: E/AndroidRuntime(641): at dalvik.system.NativeStart.main(Native Method)
03-04 20:09:32.349: E/AndroidRuntime(641): Caused by: java.lang.reflect.InvocationTargetException
03-04 20:09:32.349: E/AndroidRuntime(641): at java.lang.reflect.Method.invokeNative(Native Method)
03-04 20:09:32.349: E/AndroidRuntime(641): at java.lang.reflect.Method.invoke(Method.java:511)
03-04 20:09:32.349: E/AndroidRuntime(641): at android.view.View$1.onClick(View.java:3586)
03-04 20:09:32.349: E/AndroidRuntime(641): ... 12 more
03-04 20:09:32.349: E/AndroidRuntime(641): Caused by: java.lang.NullPointerException
03-04 20:09:32.349: E/AndroidRuntime(641): at net.clmitchell.ewtraker.pPlayers.ActDlgAddPlyr.setBundleChk(ActDlgAddPlyr.java:260)
03-04 20:09:32.349: E/AndroidRuntime(641): at net.clmitchell.ewtraker.pPlayers.ActDlgAddPlyr.onCheckBoxChng(ActDlgAddPlyr.java:231)
03-04 20:09:32.349: E/AndroidRuntime(641): ... 15 more
The two line identified at the end are, respectively:
if (checked){ActDlgAddPlyr.this.setBundleChk(mField,1);}
for (String key: ActDlgAddPlyr.this.mBdlgForm.keySet()){
The following is the 2nd method:
/**
* Set the boolean fields in mBdlgForm based on user action on the checkboxes
*
* #param Field The field name to change
* #param State The state to set (<code>true</code> or <code>false</code> */
private void setBundleChk(String Field, int State){
if (BuildConfig.DEBUG) {
Log.i(Constants.TAG_ACTDLGADDPLYR, "setBundleChk(Field, State) called with: "+Field+", and "+State);
Log.i(Constants.TAG_ACTDLGADDPLYR, "setBundleChk(): mBdlgForm Keys :");
for (String key: ActDlgAddPlyr.this.mBdlgForm.keySet()){
Log.d (Constants.TAG_FRGACTPLAYERS, "mBdlgForm."+key);
}
}
if(State == 1){ActDlgAddPlyr.this.mBdlgForm.putBoolean(Field, true);}
else{ActDlgAddPlyr.this.mBdlgForm.putBoolean(Field, false);}
}
Try this out:-
Activity.this.setBundleChk(mField,1);
It seems your problem is a NullPointerException when you try to add the checked state to the Bundle. Have you properly initialized your Bundle?
The onClick xml attribute should just work. I used it a few times without any issues.
I assume that your xml has this attribute set to onCheckBoxChng:
Just be sure to declare the public void onCheckBoxChng(View view) as a proper method of your activity (not a static method, not a method of an inner class of you Activity, etc). When it is called, the this in your onCheckBoxChng method should be the Activity you expect, the one that hosts these CheckBoxes.
Based on the stack-trace, it seems that your onCheckBoxChng is actually invoked, however, the onCheckBoxChng method throws an exception, which was caused by a null pointer exception in setBundleChk.
What code is on line 260, inside your setBundleChk method? If it is String key: ActDlgAddPlyr.this.mBdlgForm.keySet() then it looks like the mBdlgForm is null. The mBdlgForm Bundle is there, it can be 'seen'. It is just null. Make sure you assign a proper value to mBdlgForm before any onclicks are handled.
Problem solved.
Valuable lessons learned:
It was a mistake to try and get the CheckBox data at the moment the user touched a CheckBox; I needed to trust the Android OS and gather the data AFTER the user pressed the "Save" Button using tried and true techniques.
Using "android:onClick" is useful in certain situations, but one must be sure when such an approach is appropriate.
You can use an Intent ANYWHERE in an Activity, not just to communicate with another Activity. In this case the Intent class saved my bacon: declaring a method as a listener cuts it off from nearly everything in an Activity BUT THE INTENT; I was able to grab my Activity's existing Intent, add the user input to it, then access and validate that data from where I would run the actual INSERT:
// Grab the current Activity's Intent
Intent iNewPlyr = getIntent();
// Put the bundle containing user input into the Intent
iNewPlyr.putExtras(mB);
// process and INSERT the data from somewhere else
validate();
I am grateful to everyone who chimed in...may all your stock options triple in value!

Categories