cramile cramile - 1 year ago 77
Android Question

How can I change the android code to make it work again?

I am a android beginner who follows a I have a problem.the test app is an news app and have code like this:

public class NewsTitleFragment extends Fragment implements OnItemClickListener {
private ListView newsTitleListView;
private List<News> newsList;
private NewsAdapter adapter;
public void onAttach(Activity activity) {
newsList = getNews();
adapter = new NewsAdapter((Activity)activity, R.layout.news_item, newsList);

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.news_title_frag, container, false);
newsTitleListView = (ListView) view
return view;

public void onActivityCreated(Bundle savedInstanceState) {
if (getActivity().findViewById( != null) {
isTwoPane = true;
} else {
isTwoPane = false;

public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
News news = newsList.get(position);
if (isTwoPane) {
NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager()
newsContentFragment.refresh(news.getTitle(), news.getContent());
} else {
NewsContentActivity.actionStart(getActivity(), news.getTitle(),

private List<News> getNews() {
List<News> newsList = new ArrayList<News>();
News news1 = new News();
news1.setTitle("It's news 1");
news1.setContent("It's news 1 content");
News news2 = new News();
news2.setTitle("It's news 2");
news2.setContent("It's news 2 content");
return newsList;


but in new android API,the code

public void onAttach(Activity activity)

must change to

public void onAttach(Context context)

I change it,but the app shows anything after change!
I want to know why i'm wrong and how to alter it.
Thanks a lot.
P.S.The class NewsAdapter extends ArrayAdapter.The class News has only two Strings
The NewsAdapter method is:

public class NewsAdapter extends ArrayAdapter<News> {

private int resourceId;

public NewsAdapter(Context context, int textViewResourceId, List<News> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;

public View getView(int position, View convertView, ViewGroup parent) {
News news = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
} else {
view = convertView;
TextView newsTitleText = (TextView) view.findViewById(;
return view;


Answer Source

Put this in onCreateView

newsList = new ArrayList<News>();
adapter = new NewsAdapter(getActivity(), R.layout.news_item, newsList);

Instead of newsList = getNews(), use


Or, re-write getNews() to add directly to the adapter.

Then, don't re-assign the adapter or newsList outside of onCreateView because there is no need to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download