This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a SQLite database with two tables: Topic table and Vocab table. I want to display the vocab images when i click on the pictureButton, but the app crashes.
Choice.java
public class Choice extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choice);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.pictureButton: {
Intent intent = new Intent(Choice.this, Pictureandtext.class);
startActivity(intent);
break;
}
case R.id.textButton: {
break;
}
}
}
}
I get my intent from
this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(Smode.this, Choice.class);
intent.putExtra("SelectedTopicId", id);
startActivity(intent);
}
});
This is my getImage() method from the DatabaseAccess.java
public byte[] getImage(int i) {
//byte[] data = null;
String selectImage = "SELECT VocabImage FROM Vocab WHERE VocabTopic =" + i;
Cursor cursor = database.rawQuery(selectImage, null);
if (cursor == null) {
cursor.moveToFirst();
do {
cursor.getBlob(0);
} while (cursor.moveToNext());
}
cursor.close();
return null;
}
Pictureandtext.java
public class Pictureandtext extends AppCompatActivity {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
protected Cursor cursor;
private ImageView imageView;
private TextView textView;
private int topicId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pictureandtext);
imageView = (ImageView)findViewById(R.id.imageView);
textView = (TextView)findViewById(R.id.textView);
topicId = getIntent().getIntExtra("SelectedTopicId", 0);
databaseAccess.open();
byte[] data = databaseAccess.getImage(topicId);
Bitmap image = toBitmap(data);
imageView.setImageBitmap(image);
/*String name = databaseAccess.getVocabName(topicId);
textView.setText(name);*/
databaseAccess.close();
}
public static Bitmap toBitmap(byte[] image){
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
EDITED!!
I edited some coding and im still getting some error. Your help is much appreciated. Thank you.
FATAL EXCEPTION: main
Process: com.example.user.displayvocab, PID: 29339
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.displayvocab/com.example.user.displayvocab.Pictureandtext}: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.example.user.displayvocab.Pictureandtext.toBitmap(Pictureandtext.java:47)
at com.example.user.displayvocab.Pictureandtext.onCreate(Pictureandtext.java:38)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
FATAL EXCEPTION: main Process: com.example.user.displayvocab, PID:
24087 java.lang.IllegalStateException: Could not execute method for
android:onClick at
Problem
case R.id.pictureButton: {
setContentView(R.layout.pictureandtext); // Remove this line
............
case R.id.textButton: {
setContentView(R.layout.menu); // Remove this line
break;
}
setContentView->Set the activity content to an explicit view. This
view is placed directly into the activity's view hierarchy.
Why you calling setContentView multiple-time ? Remove this line .You can show DIALOG there .
Related
I was trying to use intent to pass a string array to my next activity but I keep getting a null array reference error when I try to use the array in the next activity
This is the first activity
Button next;
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(first_activity.this, second_activity.class);
intent.putExtra("strarr", strarr);
}
The next activity has the following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
String[] strarr = intent.getStringArrayExtra("strarr");
TextView textview = findViewById(R.id.textView10);
textview.setText("when did you take strarr[i]);
// the error happens here when I try to reference I get the following message:
"Caused by: java.lang.NullPointerException: Attempt to read from null array"
Any help is appreciated, Thank You
Use getIntent(), then add a null check:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent != null && intent.getStringArrayExtra("strarr") != null){
String[] strarr = intent.getStringArrayExtra("strarr");
TextView textview = findViewById(R.id.textView10);
textview.setText("when did you take " + strarr[i]);
}
}
I am using list. Want to change font in it items. Theres a title textview and description. All views are initialized in adapter and they are final. Adapter extened from CursorAdapter thats why i can't use getAssets method.
So what i should do if im extended from CursorAdapter but at the same time i need to use AppCombat methods as getAssets?
Main activity:
public class CatalogActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "myLogs";
/** Identifier for the pet data loader */
private static final int LIST_LOADER = 0;
/** Adapter for the ListView */
ListCursorAdapter mCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Changing font
Log.v(TAG, "--- WE ARE IN CATALOG ACTIVITY ---");
// Setup FAB to open EditorActivity
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
// Find the ListView which will be populated with the list data
ListView listListView = (ListView) findViewById(R.id.list);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
listListView.setEmptyView(emptyView);
// Setup an Adapter to create a list item for each row of list data in the Cursor.
// There is no items data yet (until the loader finishes) so pass in null for the Cursor.
mCursorAdapter = new ListCursorAdapter(this, null);
listListView.setAdapter(mCursorAdapter);
// Setup the item click listener
listListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
ShoppingListBdHelper helper = new ShoppingListBdHelper(view.getContext());
if (helper.setCompleted(id)) {
mCursorAdapter.setCompleted(view);
}
}
});
// Kick off the loader
getSupportLoaderManager().initLoader(LIST_LOADER, null, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Insert dummy data" menu option
case R.id.action_share_button:
shareButton(mCursorAdapter.getCursor());
return true;
// Respond to a click on the "Delete all entries" menu option
case R.id.action_delete_all_entries:
deleteAllItems();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Share button
*/
private void shareButton(Cursor cursor) {
Log.v(TAG, "--- WE ARE IN SHARE BUTTON METHOD ---");
List<String> test;
test = new ArrayList<String>();
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Log.d(TAG, "field: " + cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME)));
test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME)) + " - " + cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION))); //add the item
// test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION))); //add the item
cursor.moveToNext();
}
cursor.moveToFirst();
cursor.close();
// for (String comma : )
Log.v(TAG, "--- OUR LIST INCLUDES: " + test.toString());
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_SEND);
myIntent.putStringArrayListExtra("test", (ArrayList<String>) test);
myIntent.putExtra(android.content.Intent.EXTRA_TEXT, test.toString());
Log.v(TAG, "--- INTENT EXTRAS ARE: " + myIntent.getExtras());
myIntent.setType("text/plain");
startActivity(Intent.createChooser(myIntent, "Share using"));
}
/**
* Helper method to delete all list in the database.
*/
private void deleteAllItems() {
Log.v(TAG, "Сработал метод удаления всех данных");
long rowsDeleted = getContentResolver().delete(ListContract.ListEntry.CONTENT_URI, null, null);
Log.v("CatalogActivity", rowsDeleted + " rows deleted from list database");
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
Log.v(TAG, "Начал работать loader cursor");
// Define a projection that specifies the columns from the table we care about.
String[] projection = {
ListContract.ListEntry._ID,
ListContract.ListEntry.COLUMN_ITEM_NAME,
ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION,
ListContract.ListEntry.COLUMN_ITEM_COMPLETED
};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
ListContract.ListEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Update {#link ListCursorAdapter} with this new cursor containing updated pet data
mCursorAdapter.swapCursor(data);
Log.v(TAG, "Cursor adapter загрузился");
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// Callback called when the data needs to be deleted
mCursorAdapter.swapCursor(null);
}
}
List adapter
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find individual views that we want to modify in the list item layout
final TextView nameTextView = (TextView) view.findViewById(R.id.name);
final TextView summaryTextView = (TextView) view.findViewById(R.id.summary);
Typeface titleTypeface = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
Typeface descriptionTypeface = Typeface.createFromAsset(getAssets(), "OpenSans-Italic.ttf");
Log.v(TAG, "--- FONT IS ---" + titleTypeface );
nameTextView.setTypeface(titleTypeface);
summaryTextView.setTypeface(descriptionTypeface);
// Find the columns of pet attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(ListEntry.COLUMN_ITEM_NAME);
int breedColumnIndex = cursor.getColumnIndex(ListEntry.COLUMN_ITEM_DESCRIPTION);
// Read the pet attributes from the Cursor for the current pet
String petName = cursor.getString(nameColumnIndex);
String petBreed = cursor.getString(breedColumnIndex);
// If the pet breed is empty string or null, then use some default text
// that says "Unknown breed", so the TextView isn't blank.
if (TextUtils.isEmpty(petBreed)) {
petBreed = context.getString(R.string.unknown_description);
}
// Update the TextViews with the attributes for the current pet
nameTextView.setText(petName);
summaryTextView.setText(petBreed);
view.findViewById(R.id.editImageView).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "--- WE ARE IN IMAGEVIEW LISTENER ---");
Intent intent = new Intent(v.getContext(), EditorActivity.class);
// Form the content URI that represents the specific pet that was clicked on,
// by appending the "id" (passed as input to this method) onto the
// {#link PetEntry#CONTENT_URI}.
// For example, the URI would be "content://com.example.android.pets/pets/2"
// if the pet with ID 2 was clicked on.
Uri currentPetUri = ContentUris.withAppendedId(
ListContract.ListEntry.CONTENT_URI,
cursor.getInt(cursor.getColumnIndex(ListEntry._ID))
);
Log.v(TAG, "--- CONTENT URI " + cursor.getInt(cursor.getColumnIndex(ListEntry._ID)));
// Set the URI on the data field of the intent
intent.setData(currentPetUri);
// Launch the {#link EditorActivity} to display the data for the current pet.
v.getContext().startActivity(intent);
}
}
);
view.findViewById(R.id.leftSide).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "--- WE ARE IN LEFTSIDE LISTENER ---");
//
// Intent intent = new Intent(v.getContext(), EditorActivity.class);
//
// // Form the content URI that represents the specific pet that was clicked on,
// // by appending the "id" (passed as input to this method) onto the
// // {#link PetEntry#CONTENT_URI}.
// // For example, the URI would be "content://com.example.android.pets/pets/2"
// // if the pet with ID 2 was clicked on.
// Uri currentPetUri = ContentUris.withAppendedId(
// ListContract.ListEntry.CONTENT_URI,
// cursor.getInt(cursor.getColumnIndex(ListEntry._ID))
// );
//
// // Set the URI on the data field of the intent
// intent.setData(currentPetUri);
//
// // Launch the {#link EditorActivity} to display the data for the current pet.
// v.getContext().startActivity(intent);
nameTextView.setPaintFlags(nameTextView.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
summaryTextView.setPaintFlags(summaryTextView.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
}
}
);
Boolean completed = cursor.getInt(cursor.getColumnIndex(ListEntry.COLUMN_ITEM_COMPLETED)) == 1;
if (completed) {
setCompleted(view);
}
}
Error type 2
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.list, PID: 10811
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.list/com.example.android.list.CatalogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
at com.example.android.list.CatalogActivity.onCreate(CatalogActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
sorry for the stupid and repetitive question. I am new to android programming and in progress of making an app which can scan QR Codes and save the data to an SQLite database and show it in a ListView of another activity.
Also, the ListView has a "search" function which enables the user to type text which will bring up a similar result (if found in the listview) from the items in the listview. Lastly, the delete function deletes the item from the ListView when the user taps on the item.
The application worked fine and opened the ListView Activity showing the ListView with the contents until I integrated the search and delete function.
The application states that I am trying to invoke a virtual method on a null object reference. I have looked up on how to solve it, but couldn't find anything.
Now it shows this error:
07-31 18:52:31.688 2900-2900/app.num.barcodescannerproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.num.barcodescannerproject, PID: 2900
java.lang.RuntimeException: Unable to start activity ComponentInfo{app.num.barcodescannerproject/app.num.barcodescannerproject.ListActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void app.num.barcodescannerproject.CustomCursorAdapter.changeCursor(android.database.Cursor)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void app.num.barcodescannerproject.CustomCursorAdapter.changeCursor(android.database.Cursor)' on a null object reference
at app.num.barcodescannerproject.ListActivity.onCreate(ListActivity.java:41)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
07-31 18:52:32.968 2900-2900/app.num.barcodescannerproject I/Process: Sending signal. PID: 2900 SIG: 9
Here is the code for the Activity which sends the Intent with the data to the ListView Activity:
public void saveOnClick (View saveButton){
String prescriptionName = scanResult.getText().toString();
if (prescriptionName.length() != 0) {
Intent newIntent = new Intent (this, ListActivity.class);
newIntent.putExtra("tag_person_name", prescriptionName);
startActivity(newIntent);
finish();
}
}
And this is the code for the ListActivity with the ListView, search and delete functions:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new PersonDatabaseHelper(this);
listView = (ListView) findViewById(R.id.list_data);
databaseHelper.insertData(getIntent().getExtras().getString("tag_person_name"));
customAdapter.changeCursor(databaseHelper.getAllData());
listView.setOnItemClickListener(listContentOnItemClickListener);
customAdapter = new CustomCursorAdapter(ListActivity.this, databaseHelper.getAllData());
listView.setAdapter(customAdapter);
Cursor cursor = databaseHelper.getAllData();
EditText myFilter = (EditText) findViewById(R.id.editText);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
customAdapter.getFilter().filter(s.toString());
}
});
customAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return databaseHelper.fetchDataByName(constraint.toString());
}
});
}
//public void onClickEnterData(View btnAdd) {
// startActivityForResult(new Intent(this, ResultActivity.class), ENTER_DATA_REQUEST_CODE);
//}
// #Override
//protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
// databaseHelper.insertData(data.getExtras().getString("tag_person_name"));
// customAdapter.changeCursor(databaseHelper.getAllData());
// }
// }
private OnItemClickListener listContentOnItemClickListener
= new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
final int item_id = cursor.getInt(cursor.getColumnIndex(PersonDatabaseHelper.PERSON_TABLE_COLUMN_ID));
String item_name = cursor.getString(cursor.getColumnIndex(PersonDatabaseHelper.PERSON_TABLE_COLUMN_NAME));
AlertDialog.Builder myDialog
= new AlertDialog.Builder(ListActivity.this);
myDialog.setTitle("Delete?");
TextView dialogTxt_id = new TextView(ListActivity.this);
ViewGroup.LayoutParams dialogTxt_idLayoutParams
= new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialogTxt_id.setLayoutParams(dialogTxt_idLayoutParams);
dialogTxt_id.setText(String.valueOf(item_id));
TextView dialogC1_id = new TextView(ListActivity.this);
ViewGroup.LayoutParams dialogC1_idLayoutParams
= new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialogC1_id.setLayoutParams(dialogC1_idLayoutParams);
dialogC1_id.setText(item_name);
LinearLayout layout = new LinearLayout(ListActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(dialogTxt_id);
layout.addView(dialogC1_id);
myDialog.setView(layout);
myDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
databaseHelper.delete_byID(item_id);
updateList();
}
});
myDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialog.show();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
databaseHelper.close();
}
private void updateList() {
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
According to what I see, the error is here, at the changeCursor:
databaseHelper.insertData(getIntent().getExtras().getString("tag_person_name"));
customAdapter.changeCursor(databaseHelper.getAllData());
listView.setOnItemClickListener(listContentOnItemClickListener);
I have also noticed that when I remove the changeCursor, the error will be shown at the setOnItemClickListener, stating that this virtual method is also being invoked on a null object reference.
Is there anything I can do about this? I have searched far and wide across many sites but cannot find the solution anywhere. Perhaps I'm blind.
UPDATE: Thank you for the help, I have realised that I did not initialise the customAdapter first. However, now that I did, I keep getting two exactly same NPE errors as the one with the customAdapater, except the first one is at the setOnItemClickListener and the other at the listView.setAdapter. Both are apparently also invoked on a null object. However this time, unlike with the customAdapter, I really can't spot the mistake. Any help?
You are initializing the CursorAdapter after its first use. This is wrong as you first need to create the CursorAdapter object before using it.
...
databaseHelper.insertData(getIntent().getExtras().getString("tag_person_name"));
/* This line is moved from below to this place i.e before you use the changeCursor method on it*/
customAdapter = new CustomCursorAdapter(ListActivity.this, databaseHelper.getAllData());
customAdapter.changeCursor(databaseHelper.getAllData());
listView.setOnItemClickListener(listContentOnItemClickListener);
...
You are getting a Null Pointer Exception (NPE) because you are using an object that has not been created yet using the new operator
Also should this line go first before customAdpater is declared?
Cursor cursor = databaseHelper.getAllData();
I'm trying to create 2 activities, in the first one I'm showing the "nome" and the "tipo_pessoa" in a listview, I want to show the "cargo" in the second activity. As you can see in my parsed Json, I'm using 2 models, my question is, do I need to use 2 adapters in order to do that? here is what I tried so far:
public void parseJson(JSONObject json) throws JSONException {
try {
JSONArray dados = json.getJSONArray("dados");
feedList = new ArrayList<ClientesModel>();
contatoList = new ArrayList<ClientesContatosModel>();
// parsing json object
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
ClientesModel mClientesModel = new ClientesModel();
mClientesModel.setNome(item.optString("nome"));
mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
mClientesModel.setCpf(item.optString("cpf"));
mClientesModel.setCnpj(item.optString("cnpj"));
JSONArray contatos = item.getJSONArray("contatos");
for (int j = 0; j < contatos.length(); j++) {
JSONObject data = contatos.getJSONObject(j);
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
contatoList.add(mClientesContatoModel);
mClientesContatoModel.setNomeContato(data.optString("nome"));
mClientesContatoModel.setCargo(data.optString("cargo"));
}
feedList.add(mClientesModel);
System.out.println(contatoList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
MainActivity:
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
feedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
ntent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("data", contatoList);
startActivity(intent);
}
});
}
the second Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_details);
ListView lv = (ListView) findViewById(R.id.listViewContatos);
lv.setAdapter(new ContatosListAdapter(this, contatoList));
feed = (ClientesContatosModel) this.getIntent().getSerializableExtra("data");
TextView title = (TextView) findViewById(R.id.textView);
title.setText(feed.getNomeContato());
}
Now here is my log:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javatechig.feedreader/com.javatechig.feedreader.FeedDetailsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.javatechig.feedreader.ContatosListAdapter.getCount(ContatosListAdapter.java:33)
at android.widget.ListView.setAdapter(ListView.java:480)
at com.javatechig.feedreader.FeedDetailsActivity.onCreate(FeedDetailsActivity.java:33)
java line 33 is : lv.setAdapter(new ContatosListAdapter(this, contatoList));
The data from your first activity is not completely passed into the second activity. The error is from contatoList being null, which appears to be populated in the MainActivity, but only the feed data is passed using the intent.
You need to find a way to pass the contatoList data to your second activity as well. One way to do this is to pass your JSON string as an Extra in the second activity launch Intent (if it is not too large) just like you are passing "nome" and re-parse is in the second activity.
You could also store the data using Sqlite or even SharedPreferences.
And if you have two different displays, then you will need two different adapters.
I could solve it:
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
final ListView V = (ListView) findViewById(R.id.contato_list);
//V.setVisibility(View.VISIBLE);
V.setAdapter(new ContatosListAdapter(this, contatoList));
feedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = V.getItemAtPosition(position);
ClientesContatosModel newsData = (ClientesContatosModel) o;
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
So I've been stuck on this for hours. I'm trying to setup an async task that will load up an images for my listview in another class and I'm passing information that gives me an error
Any help would be appreciated!
public class TheResults extends Activity {
public static final String DEFAULTNAME = "DefaultFile";
private GETTHEIMAGE imgFetch;
private ArrayList<Item_Info> Info = new ArrayList<Item_Info>();
String Data = null;
String THESTRING = null;
TextView httpStuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.theresults);
SharedPreferences Search = getSharedPreferences(DEFAULTNAME, 0);
Data = Search.getString("THERESULTS", null);
GetINFO();
populatelist();
}
private void GetINFO() {
}
}
}
private void populatelist() {
ArrayAdapter<Item_Info> adapter = new TheListAdapter();
ListView list = (ListView) findViewById(R.id.listings);
list.findFocus();
list.getWindowToken();
list.setAdapter(adapter);
}
public class TheListAdapter extends ArrayAdapter<Item_Info> {
public TheListAdapter() {
super(TheResults.this, R.layout.items, Info);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item_View = convertView;
ImageHolder holder = null;
if (item_View == null) {
item_View = getLayoutInflater().inflate(R.layout.items, parent, false);
Item_Info CurrentItem = Info.get(position);
holder = new ImageHolder();
holder.ICON_IMG = (ImageView)item_View.findViewById(R.id.icon_image);
holder.ICON_IMG.setTag(CurrentItem.getItemPIC());
Drawable MYIMG = imgFetch.GetTheImagedata(this, holder.ICON_IMG);
holder.ICON_TITLE = (TextView)item_View.findViewById(R.id.icon_title);
holder.ICON_TITLE.setText(CurrentItem.getItemTITLE());
holder.ICON_LOCATION = (TextView)item_View.findViewById(R.id.icon_location);
holder.ICON_LOCATION.setText(CurrentItem.getItemLOCATION());
holder.ICON_PRICE = (TextView)item_View.findViewById(R.id.icon_price);
if (CurrentItem.getItemPRICE() == null) {
holder.ICON_PRICE.setText(CurrentItem.getItemPRICE());
holder.ICON_PRICE.setBackgroundResource(R.drawable.tempbg);
} else {
holder.ICON_PRICE.setBackgroundResource(R.drawable.pricebg);
holder.ICON_PRICE.setText(CurrentItem.getItemPRICE());
}
holder.ICON_DATE = (TextView)item_View.findViewById(R.id.icon_date);
holder.ICON_DATE.setText(CurrentItem.getItemLOCATION());
}else{
holder = (ImageHolder)item_View.getTag();
}
return item_View;
}
}
static class ImageHolder{
ImageView ICON_IMG;
TextView ICON_TITLE;
TextView ICON_LOCATION;
TextView ICON_PRICE;
TextView ICON_DATE;
}
}
By looking at the logcat after the line
06-21 19:15:06.887: E/AndroidRuntime(11408): FATAL EXCEPTION: main
is the exception
java.lang.NullPointerException
which tells us that something is null and that is throwing the exception. If we look for the first line of the code that references your project we will see where the problem occurs. Here, it happens to be the next line in logcat
at com.clistc.TheResults$TheListAdapter.getView(TheResults.java:178)
Which tells us that the line is 178 of TheResults.java and that it is inside the getView() method. We have established that it is this line
Drawable MYIMG = imgFetch.GetTheImagedata(this, holder.ICON_IMG);
which means that imgFetch is probably null and you try to call a function on it which returns null since the variable is null. I don't know what that variable is but it isn't being initialized before this line
Edit
imgFetch isn't initialized anywhere. It is declared here
private GETTHEIMAGE imgFetch;
but you never initialize it by giving it a value. You need to do something like
private GETTHEIMAGE imgFetch = new GETTHEIMAGE();
assuming it has an empty constructor