2015-08-04 4 views
-2

Это мой класс фрагментов. У меня есть класс менеджера с фиктивными данными, а класс adpater расширяет базовый адаптер. В моем фрагменте есть ошибкаЯ не могу установить свой адаптер LISTVIEW в свой фрагмент

(questionsAdapter = new QuestionsAdapter(this, questionsManager.getAllQuestions());) 

и я, похоже, не понимаю ошибки. Потому что я прошел правильные параметры и аргументы в questtionsAdapter конструктора

 package sandwich.playmaker.com.afterschool.fragments; 

import android.app.Activity; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.Spinner; 

import sandwich.playmaker.com.afterschool.R; 
import sandwich.playmaker.com.afterschool.adapters.QuestionsAdapter; 
import sandwich.playmaker.com.afterschool.manager.QuestionsManager; 


/** 
* A simple {@link Fragment} subclass. 
* Activities that contain this fragment must implement the 
* {@link QuestionsFragment.OnFragmentInteractionListener} interface 
* to handle interaction events. 
* Use the {@link QuestionsFragment#newInstance} factory method to 
* create an instance of this fragment. 
*/ 
public class QuestionsFragment extends Fragment { 
    private ListView lvQuestions; 
    private EditText etSearchQuestion; 
    private Spinner spImportance; 
    private QuestionsAdapter questionsAdapter; 
    private QuestionsManager questionsManager; 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 


} 

    // TODO: Rename parameter arguments, choose names that match 
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
    private static final String ARG_PARAM1 = "param1"; 
    private static final String ARG_PARAM2 = "param2"; 

    // TODO: Rename and change types of parameters 
    private String mParam1; 
    private String mParam2; 

    private OnFragmentInteractionListener mListener; 

    /** 
    * Use this factory method to create a new instance of 
    * this fragment using the provided parameters. 
    * 
    * @param param1 Parameter 1. 
    * @param param2 Parameter 2. 
    * @return A new instance of fragment QuestionsFragment. 
    */ 
    // TODO: Rename and change types and number of parameters 
    public static QuestionsFragment newInstance(String param1, String param2) { 
     QuestionsFragment fragment = new QuestionsFragment(); 
     Bundle args = new Bundle(); 
     args.putString(ARG_PARAM1, param1); 
     args.putString(ARG_PARAM2, param2); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    public QuestionsFragment() { 
     // Required empty public constructor 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (getArguments() != null) { 
      mParam1 = getArguments().getString(ARG_PARAM1); 
      mParam2 = getArguments().getString(ARG_PARAM2); 
     } 

    } 



    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 


     View v = inflater.inflate(R.layout.fragment_questions, container, false); 

     etSearchQuestion = (EditText) v.findViewById(R.id.etSearchQuestion); 
     spImportance = (Spinner) v.findViewById(R.id.spImportance); 
     lvQuestions = (ListView) v.findViewById(R.id.lvQuestions); 

     questionsManager =new QuestionsManager(); 
     questionsAdapter = new QuestionsAdapter(this, questionsManager.getAllQuestions()); 
     lvQuestions.setAdapter(questionsAdapter); 

     return v; 
    } 

    // TODO: Rename method, update argument and hook method into UI event 
    public void onButtonPressed(Uri uri) { 
     if (mListener != null) { 
      mListener.onFragmentInteraction(uri); 
     } 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     try { 
      mListener = (OnFragmentInteractionListener) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() 
        + " must implement OnFragmentInteractionListener"); 
     } 
    } 

    @Override 
    public void onDetach() { 
     super.onDetach(); 
     mListener = null; 
    } 

    /** 
    * This interface must be implemented by activities that contain this 
    * fragment to allow an interaction in this fragment to be communicated 
    * to the activity and potentially other fragments contained in that 
    * activity. 
    * <p> 
    * See the Android Training lesson <a href= 
    * "http://developer.android.com/training/basics/fragments/communicating.html" 
    * >Communicating with Other Fragments</a> for more information. 
    */ 
    public interface OnFragmentInteractionListener { 
     // TODO: Update argument type and name 
     public void onFragmentInteraction(Uri uri); 
    } 

} 

Это мой менеджер класс

public class QuestionsManager { 

private ArrayList<QuestionsModel>allQuestions; 


public QuestionsManager() { 
    this.allQuestions = allQuestions; 
} 

public ArrayList<QuestionsModel>getAllQuestions(){ 
    allQuestions.add(new QuestionsModel(R.drawable.monarki, "How to eat Banku", "Food", 
      "9:00pm")); 
    allQuestions.add(new QuestionsModel(R.drawable.monarki, "How to eat Kenkey", "Food", 
      "9:00pm")); 
    allQuestions.add(new QuestionsModel(R.drawable.monarki, "How to eat Rice", "Food", 
      "10:00pm")); 
    allQuestions.add(new QuestionsModel(R.drawable.monarki, "How to eat Kelewele", "Food", 
      "11:00pm")); 
    allQuestions.add(new QuestionsModel(R.drawable.monarki, "How to eat Orange", "Food", 
      "12:00pm")); 
    allQuestions.add(new QuestionsModel(R.drawable.monarki, "How to eat Banana", "Food", 
      "13:00pm")); 
    allQuestions.add(new QuestionsModel(R.drawable.monarki, "How to eat Gob3", "Food", 
      "14:40pm")); 

    return allQuestions; 
} 

}

Это мой адаптер класса

 public class QuestionsAdapter extends BaseAdapter { 
private Context ctx; 
//private QuestionsModel questionsModel; 
private ArrayList<QuestionsModel>allQuestions; 

public QuestionsAdapter(Context ctx, ArrayList<QuestionsModel> allQuestions) { 
    this.ctx = ctx; 
    this.allQuestions = allQuestions; 

    // this.questionsModel = questionsModel; 
} 


@Override 
public int getCount() { 
    return allQuestions.size(); 
} 

@Override 
public Object getItem(int position) { 
    return allQuestions.get(position); 
} 

@Override 
public long getItemId(int position) 
{ 
    return allQuestions.get(position).getIvProfilePic(); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    QuestionsModel questionsModel = allQuestions.get(position); 
    LayoutInflater inflater= (LayoutInflater) ctx.getSystemService(Context 
      .LAYOUT_INFLATER_SERVICE); 
    convertView = inflater.inflate(R.layout.activity_questions, null); 
    ImageView ivProfilePic = (ImageView) convertView.findViewById(R.id.ivProfilePic); 
    TextView tvQuestion = (TextView) convertView.findViewById(R.id.tvQuestion); 
    TextView tvTag = (TextView) convertView.findViewById(R.id.tvQuestion); 
    TextView tvTime= (TextView) convertView.findViewById(R.id.tvQuestion); 

    ivProfilePic.setImageResource(questionsModel.getIvProfilePic()); 
    tvQuestion.setText(questionsModel.getTvQuestion()); 
    tvTag.setText(questionsModel.getTvQuestion()); 
    tvTime.setText(questionsModel.getTvTime()); 

    return convertView; 
} 

}

+0

Где ошибка>? –

+1

Возможный дубликат [Что такое исключение Null Pointer Exception и как его исправить?] (Http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -и-fix-it) ... серьезно? 'public QuestionsManager() { this.allQuestions = allQuestions; } '? как вы думаете, что он делает? – Selvin

+0

@ Jared (вопросыAdapter = new QuestionsAdapter (this, questionsManager.getAllQuestions());) –

ответ

3

Вы никогда не устанавливали allQuestions экземпляру всего.

public QuestionsManager() { 
    this.allQuestions = allQuestions; 
} 

должен быть

public QuestionsManager() { 
    allQuestions = new ArrayList<QuestionsModel>(); 
} 

Кроме того, некоторые советы на будущее: попробуйте прочитать StackTrace.


Поскольку вы, кажется, есть проблемы с пониманием, как написать вопрос, было бы также полезно, чтобы все знали, что есть ошибка в этой строке:

questionsAdapter = new QuestionsAdapter(this, questionsManager.getAllQuestions()); 

Это говорит что-то вдоль линий:

Incompatible types. Required: android.app.Context. Found: blah blah blah my fragment 

Изменение обижая линии к этому:

questionsAdapter = new QuestionsAdapter(getActivity(), questionsManager.getAllQuestions()); 

A Fragment не является Context, но Activity есть.

+0

Он все еще не работает –

Смежные вопросы