我有以下代码-
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
// ASYNC TASK VARIABLES
NewsAsyncTask crackerTask = new NewsAsyncTask();
String NEWSURL = "http://acs.bg/Home/About_ACS/News_and_Events/News.aspx";
String ALERTSURL = "http://acs.bg/Home/About_ACS/News_and_Events/Announcements.aspx";
String EVENTSURL = "http://acs.bg/Home/About_ACS/News_and_Events/Events.aspx";
String string1 = "";
String FINALSTRING = "";
// LISTVIEW tutorial: http://www.youtube.com/watch?v=WRANgDgM2Zg
private List<NewsItem> myNews = new ArrayList<NewsItem>();
String controlTitle = "";
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
executeThisShit();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
controlTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if (Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("1")) {
rootView = inflater.inflate(R.layout.news, container, false);
/*TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));*/
} else {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
}
return rootView;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
// CUSTOM MINI CLASSES /////////////////////////////////////////////////
public class NewsAsyncTask extends AsyncTask<String, String, String> {
// Genetics of an AsyncTask:
// 1. Type of reference(s) passed to doInBackground()
// 2. Type of reference passed to onProgressUpdate()
// 3. Type of reference returned by doInBackground(). Value passed to
// onPostExecute()
ProgressDialog dialog1;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog1 = ProgressDialog.show(MainActivity.this, "Loading",
"Fetching data from web...");
}
@Override
protected String doInBackground(String... arguments) {
// extract arguments
String newsurl = arguments[0];
//
Document root = null;
try {
root = Jsoup.connect(newsurl).get();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
if (root != null) {
Elements myElements = root.getElementsByClass("news_list")
.first().getElementsByTag("table");
for (Element el : myElements) {
Element title = el.getElementsByClass("home_title").first();
Element date = el.getElementsByClass("home_date").first();
Element link = el.getElementsByClass("news_list_image")
.first();
Element summary = el.getElementsByClass("summary").first();
populateNewsList(title.text(), summary.text(), date.text(),
link.child(0).attr("href"));
}
Log.i("ELEMENTS HTML", string1);
} else {
string1 = "FAILED TO LOAD";
}
return string1;
}
@Override
protected void onPostExecute(String string1) {
// super.onPostExecute(result);
if (string1.equals("FAILED TO LOAD")) {
/*tv2.setText("Failed to load. Check your internet connection.");*/
if (dialog1 != null) {
if (dialog1.isShowing()) {
dialog1.dismiss();
}
}
Toast.makeText(MainActivity.this,
"No web connectivity. Try again later.",
Toast.LENGTH_LONG).show();
}
FINALSTRING = string1;
/* tv2.setText(FINALSTRING); */
if (dialog1 != null) {
if (dialog1.isShowing()) {
dialog1.dismiss();
}
}
}
}
public class MyListAdapter extends ArrayAdapter<NewsItem> {
public MyListAdapter() {
super(MainActivity.this, R.layout.newsitem, myNews);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// make sure we have a view to work with in the lines below, may be
// given null
View newsItem = convertView;
if (newsItem == null) {
newsItem = getLayoutInflater().inflate(R.layout.newsitem,
parent, false);
}
// find the NewsItem we have to work with.
NewsItem currentNews = myNews.get(position);
// fill the view.
ImageView imageView = (ImageView) newsItem
.findViewById(R.id.newsitem_icon);
imageView.setImageResource(R.drawable.test_icon); // THIS IS GOING
// TO BE CHANGED
// SO IT DOESN'T
// USE THE
// DRAWABLE
// Summary
TextView summaryText = (TextView) newsItem
.findViewById(R.id.newsitem_summary);
summaryText.setText(currentNews.getSummary());
// Date
TextView dateText = (TextView) newsItem
.findViewById(R.id.newsitem_date);
dateText.setText(currentNews.getDate());
// Title
TextView titleText = (TextView) newsItem
.findViewById(R.id.newsitem_title);
titleText.setText(currentNews.getTitle());
return newsItem;
}
}
// CUSTOM METHODS ////////////////////////////////////////////////////
private void actionButtonRefreshPressed() {
if (this.isNetworkAvailable()) {
new NewsAsyncTask().execute(NEWSURL); // calling NEW asynctask
populateListView();
registerClickOnListItem();
/*container.invalidate(); */
// because an asynctask
// can be executed only
// once.
} else {
Toast.makeText(MainActivity.this,
"No web connectivity. Try again later.", Toast.LENGTH_LONG)
.show();
}
}
private void populateNewsList(String title, String summary, String date,
String link) {
myNews.add(new NewsItem(title, summary, date, link));
}
private void populateListView() {
ArrayAdapter<NewsItem> adapter = new MyListAdapter();
ListView newslist = (ListView) findViewById(R.id.newsListView);
newslist.setAdapter(adapter);
}
private void registerClickOnListItem() {
ListView list = (ListView) findViewById(R.id.newsListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
// shows toast with info
NewsItem clickedNewsItem = myNews.get(position);
String message = "You clicked position " + position
+ " Which is " + clickedNewsItem.title;
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_SHORT).show(); // .show is important!
// otherwise it won't show.
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void executeThisShit() {
if (isNetworkAvailable()) {
crackerTask.execute(NEWSURL);
populateListView();
registerClickOnListItem();
} else {
Toast.makeText(MainActivity.this,
"No web connectivity. Try again later.", Toast.LENGTH_LONG)
.show();
}
}
}
但是,当我尝试在智能手机上执行该合并时,它说它在第353行遇到了致命错误(java.lang.NullPointerException)-newslist.setAdapter(adapter);。 379-executeThisShit()方法和72-调用executeThisShit()方法。它以前在正常活动中仍在工作。我只是将其转移到“片段活动”,而这发生了。为什么?
先感谢您!
最佳答案
在ListView newslist = (ListView) findViewById(R.id.newsListView);
中
您是否检查过新闻列表不为空?
在R.layout.activity_main中的所有单词中,有一个带有newsListView id的视图