This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Since this is my second app, and my first app was 99% designing, this could be a duplicate because i might not be using the proper keywords for my searches, but i'm searching for 3 hours now for the solution, which is probably very simple, and i can't seem to find it.
When I try to save information to my database with 2 TextViews, 1 Spinner, and a Button, i get this error message:
FATAL EXCEPTION: main
Process: nl.pluuk.gelduren, PID: 29876
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at nl.pluuk.gelduren.Add_client.saveData(Add_client.java:76)
at nl.pluuk.gelduren.Add_client$3.onClick(Add_client.java:67)
at android.view.View.performClick(View.java:5233)
at android.view.View$PerformClick.run(View.java:21209)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5497)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
This is my code which i'm currently using to not save any data
public void save(){
save = (Button)findViewById(R.id.button_save_client);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Save Button Clicked");
Client_textView = (TextView)findViewById(R.id.inputform_client_name);
Rate_textView = (TextView)findViewById(R.id.inputform_rate);
Pay_Period_textView = (Spinner)findViewById(R.id.spinner_pay_period);
Client = "" + Client_textView.getText();
Rate = Integer.parseInt("" + Rate_textView.getText());
Pay_Period = "" + Pay_Period_textView.getSelectedItem();
saveData();
}
});
}
public void saveData(){
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CLIENT_NAME, Client);
System.out.println("Yes, i'm in your log");
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_RATE, Rate);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_PAY_PERIOD, Pay_Period);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedReaderContract.FeedEntry.TABLE_NAME,
null,
values);
}
This code is all inside Add_client.
The error Add_client.java:76 is referring to the line: SQLiteDatabase db = mDbHelper.getWritableDatabase();
The error Add_client.java:67 is referring to the line: saveData();
Which is probably caused by line 76.
I made sure that there are columns inside the database, by executing System.out.println("Column count:" + c.getColumnCount());
This told me that there where 3 columns, which is what I was expecting.
I also checked if there was any data inside the columns with:
Boolean rowExists;
if (c.moveToFirst())
{
System.out.println(c.getColumnName(0));
rowExists = true;
} else
{
System.out.println("Nothing to see here");
rowExists = false;
}
This gave me the output: Nothing to see here, which is was also expecting because the database starts empty.
Where is the mistake in my code which keeps smashing me these errors?
Is there is any other information needed, I will be happily include it in an edit.
It seems like the context you passed into your SQliteOpenHelper, in this case, mDBHelper, is null.
Related
The project is an assignment on an ecommerce application and I'd be delightful with an assistance. I'm trying to check if product quantity is greater than the product in the cart in the Firestore console but I keep having the NumberFormatException error. Below is the code for when the user tries to increase the number of order which is giving the error
holder.itemView.findViewById<ImageButton>(R.id.ib_add_cart_item).setOnClickListener {
// converting the carQuantity to Int from String
val cartQuantity: Int = cartProductItemListModel.cart_quantity.toInt()
// check if the cart_quantity is less than the stock_quantity
if (cartQuantity < cartProductItemListModel.product_quantity.toInt()){
val itemHashMap = HashMap<String, Any>()
itemHashMap[Constants.CART_QUANTITY] = (cartQuantity + 1).toString()
if (context is CartListActivity){
context.showProgressDialogue("Updating Cart")
}
FirestoreClass().updateMyCartItem(context, cartProductItemListModel.id, itemHashMap)
} else{
if (context is CartListActivity){
Toast.makeText(context, "Available stock for your order is (${cartProductItemListModel.product_quantity}). " +
"You can not add more than stock quantity", Toast.LENGTH_LONG).show()
}
}
}
The error from the debugging console is this
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hardextech.store, PID: 9807
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.parseInt(Integer.java:650)
at com.hardextech.store.ui.activities.ui.adapter.CartItemListAdapter.onBindViewHolder$lambda-4(CartItemListAdapter.kt:126)
at com.hardextech.store.ui.activities.ui.adapter.CartItemListAdapter.$r8$lambda$cL9k5ufbU_up2kCEhVgh9sgpi9I(Unknown Source:0)
at com.hardextech.store.ui.activities.ui.adapter.CartItemListAdapter$$ExternalSyntheticLambda3.onClick(Unknown Source:4)
at android.view.View.performClick(View.java:7044)
at android.view.View.performClickInternal(View.java:7017)
at android.view.View.access$3200(View.java:784)
at android.view.View$PerformClick.run(View.java:26596)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
The code for reducing the number of order works perfectly which is similar to when the user increase the order.
holder.itemView.findViewById<ImageButton>(R.id.ib_remove_cart_item).setOnClickListener {
// when the user clicks on the remove imageButton
if (cartProductItemListModel.cart_quantity == "1"){
// perform the same end function as when the user clicks on the delete button
FirestoreClass().deleteItemFromCart(context, cartProductItemListModel.id)
} else{
// converting the cart_quantity from string to Int
val cartQuantity: Int = cartProductItemListModel.cart_quantity.toInt()
// creating an HashMap for updating the changes
val itemHashMap = HashMap<String, Any>()
itemHashMap[Constants.CART_QUANTITY] = (cartQuantity - 1).toString()
//show the progress Dialogue
if (context is CartListActivity){
context.showProgressDialogue("Updating Cart")
}
FirestoreClass().updateMyCartItem(context, cartProductItemListModel.id, itemHashMap)
}
}
If you try to parse "" Into int it will through same exception, before calling to toInt make sure string is not blank or null
I'm a newbie in Android Studio and I'm trying to make a simple quiz app in Android Studio, and I'm following a tutorial while changing some things to mold into what I wanted. There's one error message that says :
')',, or comma expected, got '1'
and when I run it, it says android.database.sqlite.SQLiteException: near ": syntax error (code 1):
When I clean the project and rebuild it, it changes to another error code.
Here's the error code :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.exsple.localdbkebin, PID: 12335
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exsple.localdbkebin/com.exsple.localdbkebin.Reading}: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2791)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1574)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6364)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1076)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:937)
Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1348)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1195)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1066)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1234)
at com.exsple.localdbkebin.DBHelper.getQwithCriteria(DBHelper.java:209)
at com.exsple.localdbkebin.Reading.onCreate(Reading.java:44)
at android.app.Activity.performCreate(Activity.java:6695)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1124)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2744)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1574)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6364)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1076)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:937)
And here's the getQwithCriteria method :
public ArrayList<Pertanyaan> getQwithCriteria(String IDLevel, String Jenis){
ArrayList<Pertanyaan> qList = new ArrayList<>();
db = getReadableDatabase();
String selection = QuestionsTable.COLUMN_IDLEVEL + " LIKE ? " +
" AND " + QuestionsTable.COLUMN_JENIS + " = ? ";
String[] selectionArgs = new String[]{IDLevel,Jenis};
Cursor c = db.query(
QuestionsTable.TABLE_NAME,
null,
selection,
selectionArgs,
null,
null,
null
);
And this is the OnCreate in Reading class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
txtQCount = findViewById(R.id.txtQCount);
txtPertanyaan = findViewById(R.id.txtSoal);
rbGroup = findViewById(R.id.radio_group);
rb1 = findViewById(R.id.radio_button1);
rb2 = findViewById(R.id.radio_button2);
rb3 = findViewById(R.id.radio_button3);
rb4 = findViewById(R.id.radio_button4);
btnNext = findViewById(R.id.btnEnter);
Intent i = getIntent();
String levelID = i.getStringExtra("Level");
String jenis = i.getStringExtra("Choice");
DBHelper dbh = DBHelper.getInstance(this);
qList = dbh.getQwithCriteria(levelID,jenis);
Are the two of them related with each other? I'm really confused, please help. Thank you in advance.
String[] selectionArgs = new String[]{IDLevel,Jenis};
One of your selection arguments is null. Add a null check before creating the query.
if (IDLevel == null || Jenis == null) {
return null; // Add error handling as required
}
String[] selectionArgs = new String[]{IDLevel,Jenis};
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to retrieve a bundle from another activity but when I try this, the following error appears in my logs: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
The part of the code where I try to retrieve and show the bundle is this:
Bundle bundlefrankrijk = getIntent().getExtras();
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk");
TextView highscoreLabelfranrkijk = (TextView) findViewById(R.id.highscorefrankrijk);
SharedPreferences settingsfrankrijk = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highScorefrankrijk = settingsfrankrijk.getInt("HIGH_SCORE", 0);
if (scorefrankrijk > highScorefrankrijk) {
highscoreLabelfranrkijk.setText("High Score : " + scorefrankrijk);
SharedPreferences.Editor editor = settingsfrankrijk.edit();
editor.putInt("HIGH_SCORE", scorefrankrijk);
editor.commit();
} else {
highscoreLabelfranrkijk.setText("High Score : " + highScorefrankrijk);
}
This is how I'm sending the intent to the current activity:
Intent i = new Intent(QuizActivityFrankrijk.this,
QuizResultaatFrankrijk.class);
Bundle bundlefrankrijk = new Bundle(0);
bundlefrankrijk.putInt("finalScoreFrankrijk", mScoreFrankrijk);
i.putExtras(bundlefrankrijk);
QuizActivityFrankrijk.this.finish();
startActivity(i);
Thanks in advance!
Better if you could post the code to see how you are sending the intent with extras to current activity too, for what I´m seeing here, the error is in this line:
Bundle bundlefrankrijk = getIntent().getExtras(); // is returning null object
And when youre trying to:
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk"); // NullPointerException throwed
Cause your bundle is null from beginning, you should check if you´re sending correctly the intent with extras, please use the method:
mIntent.putExtra("key", intValue)
and check that youre receiving it like this:
if (getIntent().getExtras() != null){
getIntent().getExtras().getInt("key");}
or just like this too:
if (getIntent().getExtras() != null){
getIntent().getExtras().get("key");}
Remember, if the key is just different in some character, it will return NULL.
Please read this for more info: https://developer.android.com/reference/android/content/Intent.html
I have a list of "Persons" profiles that contains some usual identifying information.
I'm able to add new entries programmatically without any issues.
I'm able to retrieve and display in a list the entries in firebase
The issue I am having is with retrieving the profile of the Person whose entry is clicked in the list mentioned above. The code for this is listed below. I have verified that thisPersonRef contains the correct path. As far as I can tell, the event listener is just skipped over/not triggered. I believe I am following the instructions and samples show at https://www.firebase.com/docs/android/guide/retrieving-data.html and https://firebase.google.com/docs/database/android/retrieve-data#attach_an_event_listener
The error I get is:
java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.bcll_tech.ptapp.Persons.Person.barCodeText' on a null object reference
I've also tried using addListenerForSinglevalueEvent as well as ChildEventListener and I get the same results. This makes me think that I must be missing some other step in the process.
Any help is appreciated as I've scoured the list and haven't seen anything quite the same.
Thanks.
public void onPersonSelected(String listRecordId) {
Log.d(logtag, "Activity: List item recordId = " + listRecordId);
final Firebase thisPersonRef = mPersonRef.child("barCodeId").child(listRecordId);
thisPersonRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.d(logtag, "PersonsListViewDetailsFragment: in listener. snapshot of " + thisPersonRef);
Person thisPerson = snapshot.getValue(Person.class);
Log.d(logtag, "From Get Data: Bar Code ID = " + thisPerson.barCodeText + "; Last name = " + thisPerson.lastName);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Log.d(logtag, "Activity: Get Person: BarCodeId = " + thisPerson.barCodeText);
}
Try like this
final Firebase thisPersonRef = mPersonRef.child("barCodeId").setValue(listRecordId);
and
Person thisPerson = snapshot.getChildren().getValue(Person.class);
Can someone help me understand what is wrong with this code?
I want to be able to add all contacts associated with the query to a ArrayList.
But using just the 'add' command make the loop apparently override it and make the size 1 again. But using the 'add' method with a index causes this error. 'IndexOutOfBoundsError'.
pls. do help me.
This the error log.
08-14 21:36:29.893 20439-20439/? E/Zygote﹕ MountEmulatedStorage()
08-14 21:36:29.893 20439-20439/? E/Zygote﹕ v2
08-14 21:36:29.943 20439-20439/? E/SELinux﹕ [DEBUG] get_category: variable
seinfo: default sensitivity: NULL, cateogry: NULL
08-14 21:36:44.973 20439-20439/com.cmpe277.personalassistant E/MA﹕
search_intent_has_started
08-14 21:36:45.103 20439-20439/com.cmpe277.personalassistant E/DU﹕
startQuery has launched
08-14 21:36:45.103 20439-20439/com.cmpe277.personalassistant E/DU﹕ query =
chemist
08-14 21:36:45.383 20439-20439/com.cmpe277.personalassistant
E/CLoaderCallbacks﹕ Nothing is null?!
08-14 21:36:53.293 20439-20439/com.cmpe277.personalassistant E/MA﹕
search_intent_has_started
08-14 21:36:53.393 20439-20439/com.cmpe277.personalassistant E/DU﹕
startQuery has launched
08-14 21:36:53.393 20439-20439/com.cmpe277.personalassistant E/DU﹕ query =
leela ashok
08-14 21:36:53.533 20439-20439/com.cmpe277.personalassistant
E/CLoaderCallbacks﹕ Nothing is null?!
08-14 21:36:53.563 20439-20439/com.cmpe277.personalassistant
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.cmpe277.personalassistant, PID: 20439
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.add(ArrayList.java:147)
at
com.cmpe277.personalassistant.ContactablesLoaderCallbacks.onLoadFinished(ContactablesLoaderCallbacks.java:117)
at com.cmpe277.personalassistant.ContactablesLoaderCallbacks.onLoadFinished(ContactablesLoaderCallbacks.java:22)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:483)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:451)
at android.content.Loader.deliverResult(Loader.java:144)
at android.content.CursorLoader.deliverResult(CursorLoader.java:109)
at android.content.CursorLoader.deliverResult(CursorLoader.java:42)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:265)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
This is my code:
package com.kishore_kumar.callbacks;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Helper class to handle all the callbacks that occur when interacting with
loaders. Most of the
* interesting code in this sample app will be in this file.
*/
public class ContactablesLoaderCallbacks implements
LoaderManager.LoaderCallbacks<Cursor> {
Context mContext;
int counter = 0;
public static final String QUERY_KEY = "query";
public static final String TAG = "CLoaderCallbacks";
public ContactablesLoaderCallbacks(Context context) {
mContext = context;
}
#Override
public Loader<Cursor> onCreateLoader(int loaderIndex, Bundle args) {
// Where the Contactables table excels is matching text queries,
// not just data dumps from Contacts db. One search term is used to query
// display name, email address and phone number. In this case, the
query was extracted
// from an incoming intent in the handleIntent() method, via the
// intent.getStringExtra() method.
// BEGIN_INCLUDE(uri_with_query)
String query = args.getString(QUERY_KEY);
Uri uri = Uri.withAppendedPath(
CommonDataKinds.Contactables.CONTENT_FILTER_URI, query);
// END_INCLUDE(uri_with_query)
// BEGIN_INCLUDE(cursor_loader)
// Easy way to limit the query to contacts with phone numbers.
String selection =
CommonDataKinds.Contactables.HAS_PHONE_NUMBER + " = " + 1;
// Sort results such that rows for the same contact stay together.
String sortBy = CommonDataKinds.Contactables.LOOKUP_KEY;
return new CursorLoader(
mContext, // Context
uri, // URI representing the table/resource to be queried
null, // projection - the list of columns to return. Null
means "all"
selection, // selection - Which rows to return (condition rows
must match)
null, // selection args - can be provided separately and
subbed into selection.
sortBy); // string specifying sort order
// END_INCLUDE(cursor_loader)
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
TextView tv = (TextView)
((Activity)mContext).findViewById(R.id.sample_output);
if(tv == null) {
Log.e(TAG, "TextView is null?!");
} else if (mContext == null) {
Log.e(TAG, "Context is null?");
} else {
Log.e(TAG, "Nothing is null?!");
}
// Reset text in case of a previous query
tv.setText(mContext.getText(R.string.intro_message) + "\n\n");
if (cursor.getCount() == 0) {
return;
}
// Pulling the relevant value from the cursor requires knowing the
column index to pull
// it from.
// BEGIN_INCLUDE(get_columns)
int phoneColumnIndex =
cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
int emailColumnIndex =
cursor.getColumnIndex(CommonDataKinds.Email.ADDRESS);
int nameColumnIndex =
cursor.getColumnIndex(CommonDataKinds.Contactables.DISPLAY_NAME);
int lookupColumnIndex =
cursor.getColumnIndex(CommonDataKinds.Contactables.LOOKUP_KEY);
int typeColumnIndex =
cursor.getColumnIndex(CommonDataKinds.Contactables.MIMETYPE);
// END_INCLUDE(get_columns)
cursor.moveToFirst();
// Lookup key is the easiest way to verify a row of data is for the same
// contact as the previous row.
String lookupKey = "";
do {
// BEGIN_INCLUDE(lookup_key)
String currentLookupKey = cursor.getString(lookupColumnIndex);
if (!lookupKey.equals(currentLookupKey)) {
String displayName = cursor.getString(nameColumnIndex);
tv.append(displayName + "\n");
lookupKey = currentLookupKey;
}
// END_INCLUDE(lookup_key)
// BEGIN_INCLUDE(retrieve_data)
// The data type can be determined using the mime type column.
String mimeType = cursor.getString(typeColumnIndex);
if (mimeType.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
tv.append("\tPhone Number: " +
cursor.getString(phoneColumnIndex) + "\n");
//#TeneCursum this is roughly about where the error gets thrown out
ArrayList<String> mylist = new ArrayList<String>();
mylist.add(counter, cursor.getString(phoneColumnIndex)); //this
adds an element to the list.
tv.append("size = "+mylist.size());
counter++;
} else if (mimeType.equals(CommonDataKinds.Email.CONTENT_ITEM_TYPE))
{
tv.append("");
}
// END_INCLUDE(retrieve_data)
// Look at DDMS to see all the columns returned by a query to
Contactables.
// Behold, the firehose!
for(String column : cursor.getColumnNames()) {
Log.d(TAG, column + column + ": " +
cursor.getString(cursor.getColumnIndex(column)) + "\n");
}
} while (cursor.moveToNext());
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
}
I am a beginner. So please do help me understand.
Put ArrayList<String> mylist = new ArrayList<String>(); before the do { construct. The problem is that you are incrementing counter, but you're making a new List each time. The second time that the do-while is executing, the counter = 1 and the array is new, so it's size it 0. Hence, adding with myList.add(1, object) will fail.
ArrayList<String> mylist = new ArrayList<String>();
is put too late in the code.
It should be created before any operations can happen on it.
What you are actually doing is refreshing and re-creating mylist everytime.
Therefore, when you run it a second time through the loop, mylist was remade, and it has nothing inside of it.
You are accessing the 1st index of a freshly made ArrayList that only contains 1 object, even though you are searching for 2 objects since count is 1. (Remember? Arrays start at 0.)
You are creating an empty Array (with lenght = 0) and you try to put into it an element in a different position of 0. Watch you are creating an empty array every time. If you know how many contacts have you got, you can create an Array with the constructor new ArrayList(int initialCapacity)