Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to fetch an array from a database on a remote server using the Android Volley library. The problem is that the JSONobject is not returning any data in the onResponse method. When I try to show the data in JSONobject, the application crashes and logcat shows a NullPointerException.
Java code is given below:
public class AudioFragmentThree extends Fragment {
View view;
TextView text;
String url = "http://www.muftiattaullahmultani.com/android/get_all_bayan.php";
int count = 0;
int i = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.audio_fragment_three, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
while(count<response.length())
{
JSONObject object= null;
try {
object = response.getJSONObject(count);
String s = object.getString("id") +" "+ object.getString("topic");
text.setText(s);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
text.setText("ERROR");
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(jsonArrayRequest);
}
}
LogCat is given below:
FATAL EXCEPTION: main Process: com.example.mashood.muftiattaullahmultanicom, PID: 22596
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at
com.example.mashood.muftiattaullahmultanicom.AudioFragmentThree$1.onResponse(AudioFragmentThree.java:81)
at com.example.mashood.muftiattaullahmultanicom.AudioFragmentThree$1.onResponse(AudioFragmentThree.java:69)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
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:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Below is my PHP code:
<?PHP include 'database.php';
$query = 'SELECT * FROM audio_bayan ORDER BY no DESC';
$result = $conn->query($query);
$response = array();
while($row = $result->fetch_assoc()) {
array_push($response,array("id"=>$row['no'],"topic"=>$row['topic']));
}
echo json_encode($response);
?>
You have to define textview like below:
Textview text;
text = (TextView) view.findViewById(R.id.textid);
You forget the findViewById your text field add :
text = (TextView) view.findViewById(R.id.text_id);
to your onCreateView method
Looks like your TextView is null.
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
It means you are trying to call setText on a null reference. You have to assign a reference of your TextView from xml layout to the TextView, something like this in onCreateView or onActivityCreated:
TextView text =(TextView) view.findViewById(R.id.text_view);
where, text_view is the id of your TextView in xml.
Related
Situation:
I am making a chat app with Skype like UI. The contacts recycler view is on the left side.
I have the custom ActionBar based theme.
I need to set the title in the ActionBar onClick.
So, basically, the onClick method is in the Adapter. OnClick of the contacts, the method is passed to the Activity with ActionBar and the name of the contact should come in the title.
The getActionBar() runs perfectly and the Title is set in onCreate method. But, app crashes when I do the same in method outside onCreate.
I referred links here and here but I couldn't solve my issue.
Please guide me regarding the same.
Example:
ChatActivity extends Activity {
//..onCreate here
if(getActionBar() != null) {
String title = " Chat: ";
if(userName != null) {
title = title + userName;
}
getActionBar().setTitle(title);
}
// onCreate finishes
// onContactChange
public void onContactChange(int position, ContactsVO addContact) {
userName = addContact.getName().toString();
String url = addContact.getDP();
if(getActionBar() != null) { //App crashes here
String title =" Chat: ";
if(userName != null)
title = title + userTo;
getActionBar().setTitle(title);
}
}
}
Async Task is called, webservice returns the data which is set in the Adapter.
Now,
in Adapter,
ChatActivity c1 = new ChatActivity();
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ContactsVO contactsvo = data.get(position);
holder.tv.setText(contactsvo.getName());
String url = contactsvo.getDP();
Glide.with(getContext())
.load(url)
.crossFade()
.into(holder.img);
holder.row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
c1.onContactChange(position,contactsvo); //method called here.
}
});
}
Stack Trace
E/ACRA: ACRA caught a NullPointerException exception for com.chat
Building report. 11-20 15:51:23.278 12797-12941/? E/ACRA: com.chat
fatal error : Attempt to invoke virtual method 'android.view.View
android.view.Window.getDecorView()' on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.Window.getDecorView()' on a null
object reference
at android.app.Activity.initWindowDecorActionBar(Activity.java:2397)
at android.app.Activity.getActionBar(Activity.java:2339)
at com.chat.activities.ChatActivity.onContactChange(ChatActivity.java:276)
at com.chat.utilities.adapters.ChatCustomAdapter$1.onClick(ChatCustomAdapter.java:74)
at android.view.View.performClick(View.java:5678)
at android.view.View$PerformClick.run(View.java:22667)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6293)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1065)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:926)
Please guide me to solve the solution for the same.
My suggestion is to use setSupportActionBar() for whole activity.
Here in your layout.
<android.support.v7.widget.Toolbar
android:id="#+id/home_activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways" />
//OnCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
toolbar = (Toolbar) findViewById(R.id.home_activity_toolbar);
configureHomeToolBar();
}
private void configureHomeToolBar() {
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setIcon(R.drawable.my_logo);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
Then you will be able to use it by calling getSupportActionBar() anywhere in your activity such as:
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setTitle(titlesArray[someIndex]);
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 .
For some reason I am getting a null pointer exception pointing to videosFound when it is indeed not null. Even the parameter, adapter, that is being passed in is not null. I check and verify this simply by printing out if its null or not (both of them are NOT null). So can someone please tell me how I am getting this error?
private ListView videosFound;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
searchInput = (EditText)findViewById(R.id.search_input);
videosFound = (ListView)findViewById(R.id.videos_found);
handler = new Handler();
addClickListener();
searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
searchOnYoutube(v.getText().toString());
return false;
}
return true;
}
});
}
private void updateVideosFound(){
ArrayAdapter<VideoItem> adapter = new ArrayAdapter<VideoItem>(getApplicationContext(), R.layout.video_item, searchResults){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = getLayoutInflater().inflate(R.layout.video_item, parent, false);
}
ImageView thumbnail = (ImageView)convertView.findViewById(R.id.video_thumbnail);
TextView title = (TextView)convertView.findViewById(R.id.video_title);
TextView description = (TextView)convertView.findViewById(R.id.video_description);
VideoItem searchResult = searchResults.get(position);
Picasso.with(getApplicationContext()).load(searchResult.getThumbnailURL()).into(thumbnail);
title.setText(searchResult.getTitle());
description.setText(searchResult.getDescription());
return convertView;
}
};
if(videosFound == null){
System.out.println("videoFound is null***********");
}else{
System.out.println("videoFound is NOT null***********");
}
if(adapter == null){
System.out.println("adapter is null***********");
}else{
System.out.println("adapter is NOT null***********");
}
videosFound.setAdapter(adapter);//ERROR HERE. neither videosFound no adapter are null
}
private void addClickListener(){
videosFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int pos,
long id) {
Intent intent = new Intent(getApplicationContext(), PlayerActivity.class);
intent.putExtra("VIDEO_ID", searchResults.get(pos).getId());
startActivity(intent);
}
});
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/search"
android:id="#+id/search_input"
android:singleLine="true" />
<ListView
android:id="#+id/videos_found"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="5dp" />
</LinearLayout>
Console:
03-24 18:04:31.833 17014-17440/com.example.shawn.myyoutube D/YC: Could not search: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "usageLimits",
"message" : "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
"reason" : "ipRefererBlocked",
"extendedHelp" : "https://console.developers.google.com"
} ],
"message" : "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
}
03-24 18:04:31.833 17014-17014/com.example.shawn.myyoutube I/System.out: videoFound is NOT null***********
03-24 18:04:31.833 17014-17014/com.example.shawn.myyoutube I/System.out: adapter is NOT null***********
03-24 18:04:31.843 17014-17014/com.example.shawn.myyoutube D/AndroidRuntime: Shutting down VM
03-24 18:04:31.843 17014-17014/com.example.shawn.myyoutube E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shawn.myyoutube, PID: 17014
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:502)
at com.example.shawn.myyoutube.SearchActivity.updateVideosFound(SearchActivity.java:98)
at com.example.shawn.myyoutube.SearchActivity.access$200(SearchActivity.java:23)
at com.example.shawn.myyoutube.SearchActivity$2$1.run(SearchActivity.java:61)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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)
In the stacktrace I see this:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
The adapter is trying to call size() on a null List. Make sure your list searchResults is not null.
NullPointerException occurred because searchResults is not initialized and is null.
Regarding your question in the comment -
do you know why the error did not actually point to the line where
searchResults was?
ArrayAdapter calls getCount() internally whenever you call setAdapter() or refresh the already created adapter using notifyDataSetChanged().
Till you call setAdapter() or notifyDataSetChanged(), ArrayAdapter won't create view for you and in order to create that, it needs to check the size of the data which you passed to it.
For that it calls getCount()
which is
public int getCount() {
return mObjects.size();
}
where mObjects is initialized to the data list which you pass while creating your adapter.
Apparently mObjects.size() will throw NullPointerException since mObjects is null because searchResults is null.
Hope you understood.
Ok so I know I should use interfaces to retrieve information from AsyncTask because they run in separate threads but I have been trying in vain to get this right. Can someone guide me to what is wrong with my code?
First I thought I was getting null pointer exception at callback.onJsonReady(movie) because I was still trying to reach movie that was not processed despite my attempt. So I tried sleeping it for 5000ms before it retrieves but I still get a null pointer exception. please help me.
If you need to look at more of my code, please tell me also.
Below is the method where I set up my interface
protected void onPostExecute(String s) {
super.onPostExecute(s);
processData(getmData());
}
private void processData (String mData){
try {
final String MOVIE_TITLE = "Title";
JSONObject jsonObject = new JSONObject(mData);
Log.v(LOG_TAG, mData);
String title = jsonObject.getString(MOVIE_TITLE);
Movie movie = new Movie(title);
callback.onJsonReady(movie);
Log.v(LOG_TAG, "Title of the movie is " + movie.getTitle());
}catch (JSONException e){
Log.e(LOG_TAG, "Error retrieving JsonData");
e.printStackTrace();
}
}
}
Below is my class where I call the interface
public class ResultsPage extends AppCompatActivity implements ParseJsonData.ParseJsonCallback{
private final String LOG_TAG = getClass().getSimpleName();
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTextViews();
}
private void setTextViews () {
Bundle bundle = getIntent().getExtras();
String movieTitle = bundle.getString("title");
Log.v(LOG_TAG, "title recieved is : " + movieTitle);
ParseJsonData parseJsonData = new ParseJsonData(movieTitle, this);
parseJsonData.execute();
}
#Override
public void onJsonReady(Movie movie) {
title.setText(movie.getTitle());
}
}
My logcat is
03-14 18:03:02.931 30827-30827/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jc.tagyourmovie, PID: 30827
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.jc.tagyourmovie.ResultsPage.onJsonReady(ResultsPage.java:44)
at com.jc.tagyourmovie.ParseJsonData$ParseJsonDataBackground.processData(ParseJsonData.java:83)
at com.jc.tagyourmovie.ParseJsonData$ParseJsonDataBackground.onPostExecute(ParseJsonData.java:69)
at com.jc.tagyourmovie.ParseJsonData$ParseJsonDataBackground.onPostExecute(ParseJsonData.java:53)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Your Textview title is not initialized... that is the reason
you need to do something like:
title = (TextView)findViewById(R.id.<your_tv_id>);
Error is in title.setText line. Logcat says so >
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Seems you haven't initialize your textview named title, initialize it before using it.
Your code declared a textview named title
private TextView title;
you have to initialize this textview in onCreate() like below
title = (TextView)findViewById(R.id.TEXTVIEWID);
You need to move code that changes UI to the onPostExecute part of the AsyncTask.
callback.onJsonReady(movie);
This part can be in the doInBackground, but use a field of the AsynchTask rather than a local var so you can access it in the onPostExecute:
Movie movie = new Movie(title);
private TextView title;
You need to give a value to title, something like this:
title = (TextView) R.findViewById(R.id.textviewid);
And after that you can call setText() on it.
Replace textviewid with your textview's id in xml file.
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");
}
}