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);
}
});
}
Related
I have created Activity with a listView which uses setOnItemClickListener to determine which index has been pressed. Then it should pass the data into the next activity based on the selected index.
Passing of the values works, but it only works for the first listView index pressed after the app is reloaded.
To make it more clear. When the app is loaded I can press on any index of the ListView which will pass the data to the next Activity and display it correctly, but then when I go back to the ListView and select different index it still displays the same data from the previous index without updating it. Therefore, I have to reload the app to get new index results displayed.
Here is my ViewListActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_artist);
artistList = (ListView) findViewById(R.id.artistList);
databasehandler = new SqliteHandler(ViewArtistActivity.this);
allArtists = databasehandler.getAllArtists();
artistName = new ArrayList<>();
singleArtistDetails = new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (allArtists.size() > 0) {
for (int i=0; i < allArtists.size(); i++) {
ArtistModel artistModel = allArtists.get(i);
artistName.add(artistModel.getArtistName());
}
}
adapter = new ArrayAdapter(ViewArtistActivity.this, android.R.layout.simple_list_item_1, artistName);
artistList.setAdapter(adapter);
artistList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArtistModel artistModel = allArtists.get(position);
singleArtistDetails.add(artistModel.getArtistName());
singleArtistDetails.add(artistModel.getArtistDOB());
singleArtistDetails.add(artistModel.getArtistBiography());
Intent intent = new Intent(ViewArtistActivity.this, SavedArtistDetailsActivity.class);
intent.putExtra("NAME", singleArtistDetails.get(0));
intent.putExtra("DOB", singleArtistDetails.get(1));
intent.putExtra("BIOGRAPHY", singleArtistDetails.get(2));
startActivity(intent);
}
});
}
Here is my code for displaying selected index results Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_artist_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
artistSavedNameLbl2 = (TextView) findViewById(R.id.artistSavedNameLbl2);
artistSavedDOBLbl2 = (TextView) findViewById(R.id.artistSavedDOBLbl2);
artistSavedBiographyLbl2 = (TextView) findViewById(R.id.artistSavedBiographyLbl2);
btnDeleteDetails = (Button) findViewById(R.id.btnDeleteDetails);
updateUI();
}
private void updateUI() {
artistSavedNameLbl2.setText(getIntent().getStringExtra("NAME"));
artistSavedDOBLbl2.setText(getIntent().getStringExtra("DOB"));
artistSavedBiographyLbl2.setText(getIntent().getStringExtra("BIOGRAPHY"));
}
Do one thing , initialize [not saying declare] your array list singleArtistDetails inside the onClick method, before adding any values to it.
like
singleArtistDetails = new ArrayList();
Hope this will help.
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 .
I open the IndividualCouponsActivity from the fragment foodCouponsFragment within the parent CouponsActivity. I open the IndividualCouponsActivity with an Intent. After opening it, I want to edit the textViews and ImageViews of the IndividualCouponActivity. It should be noted that the IndividualCouponActivity is not a parent of the fragment.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = foodCoupons.get(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
startActivity(foodCouponsIntent);
IndividualCouponActivity activity = new IndividualCouponActivity();
activity.setValue(coupon.getCouponValue());
activity.setCompany(coupon.getCompanyName());
activity.setInfo(coupon.getDescription());
activity.setPts(coupon.getPts());
activity.setQr(coupon.getPicImageResourceId());
}
});
However, when I run the app, clicking on the listView makes the app shut down. This is what the log says at that time:
FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.support.v7.app.AppCompatDelegateImplBase.
I suspect that this is rooting from my use of the new IndividualCouponActivity activity to access the class methods. Thanks!
Don't create your activity with new...
Pass the Coupon object to your activity like this:
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("coupon", coupon); // or putSerializable()
intent.putExtras(bundle);
intent.setClass(context, IndividualCouponActivity.class);
context.startActivity(intent);
In your activity in onCreate() you can get the passed coupon with:
getIntent().getExtras().getParcelable("coupon"); // or putSerializable()
Then set the values to your views.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = (Coupon) adapterView.getItemAtPosition(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
Bundle extras = new Bundle();
extras.put("value", coupon.getCouponValue());
extras.put("companyName", coupon.getCompanyName());
extras.put("description",coupon.getDescription());
extras.put("pts", coupon.getPts());
extras.put("picImageResourceId", coupon.picImageResourceId());
foodCouponsIntent.putExtras(extras);
startActivity(foodCouponsIntent);
}
});
and then in your IndividualCouponActivity's onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get reference to views...
textViewValue = (TextView) findViewById(R.id.textViewValue);
//do this for all views....
//if all objects are String values, if not you know what you have to do...
//here you get values from extras
Bundle data = getIntent().getExtras();
String value = data.getStringExtra("value");
String companyName = data.getStringExtra("companyName");
String description = data.getStringExtra("description");
String pts = data.getStringExtra("pts");
String picImageResourceId = data.getStringExtra("picImageResourceId");
//here update UI views
//example
textViewValue.setText(value);
//do this for all views....
}
maybe there is some typo mistake, but this is the solution...
You can pass data between both activities using "putExtra"
Intent intent = new Intent(getBaseContext(), IndividualCouponActivity.class);
intent.putExtra("COUPON_COMPANY_NAME", coupon.getCompanyName());
startActivity(intent);
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 making a simple RSS reader with NavigationDrawer. I've done a Parser class using RssParserSax and a RSS handler. My app crash when I execute the AsynTask. My logcat:
java.lang.NullPointerException
at me.apps.rss.News$LoadXMLTask.onPostExecute(CNews.java:53)
at me.apps.rss.News$LoadXMLTask.onPostExecute(CNews.java:45)
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:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
And my View code. Note that the task only executes when I press the button.
public class News extends android.support.v4.app.Fragment {
private List<whatsnew> news;
private TextView txtresult;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.lay_news, container, false);
Button but = (Button) v.findViewById(R.id.but);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoadXMLTask task1 = new LoadXMLTask();
task1.execute("http://www.feedforall.com/sample-feed.xml");
}
});
return v;
}
private class LoadXMLTask extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground (String ... params){
RssParserSax saxparser= new RssParserSax(params[0]);
news = saxparser.parse();
return true;
}
protected void onPostExecute (Boolean result){
txtresult.setText("");
for(int i=0; i<news.size(); i++)
{
//nothing
}
}
}
}
txtresult.setText("");
This is the problem, reference is probably null.
Actually, this 2 lines in your stack trace tell you exactly what the problem is:
at me.apps.rss.News$LoadXMLTask.onPostExecute(CNews.java:53)
at me.apps.rss.News$LoadXMLTask.onPostExecute(CNews.java:45)
Lines 45, 53 in CNews.java are the places where Exception is thrown. If you look at this lines you'll know which reference is null.
So the solution is to add inside onCreateView:
txtresult = (TextView) v.findViewById(R.id.your_id);
At the onCreateView you forgot to initialize txtresult field, that is why txtresult.setText(""); gives you a NPE.
In addition to uninitialized txtResult this operation for(int i=0; i<news.size(); i++) is also unsafe because news is not initialized either. I think a better way to utilize your AsyncTask is:
protected Boolean doInBackground (String ... params){
RssParserSax saxparser= new RssParserSax(params[0]);
news = saxparser.parse(); //assuming this doesn't throw exception
if (news != null){
return true;
}
return false;
}
protected void onPostExecute (Boolean result){
if (result){
for (int i =0; i<news.size();i++){...}
txtresult.setText("success");
}else{
txtresult.setText("failed");
}
}