0

я получил это нулевой указатель ошибки execeptionновообращенный recycleview залп активность ошибки фрагмента

03-10 14:08:27.510 9297-9297/? E/AndroidRuntime: FATAL 

    EXCEPTION: main 
                Process: com.anakacara.anakacara, PID: 9297 
                java.lang.NullPointerException 
                 at com.anakacara.anakacara.Fragment.EventFragment.getDataFromServer(EventFragment.java:163) 
                 at com.anakacara.anakacara.Fragment.EventFragment.getData(EventFragment.java:192) 
                 at com.anakacara.anakacara.Fragment.EventFragment.onCreateView(EventFragment.java:127) 
                 at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) 
                 at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
                 at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) 
                 at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 

вот мой customVolleyRequest код

public class CustomVolleyRequest { 

    private static CustomVolleyRequest customVolleyRequest; 
    private static Context context; 
    private RequestQueue requestQueue; 
    private ImageLoader imageLoader; 

    private CustomVolleyRequest(Context context) { 
     this.context = context; 
     this.requestQueue = getRequestQueue(); 

     imageLoader = new ImageLoader(requestQueue, 
       new ImageLoader.ImageCache() { 
        private final LruCache<String, Bitmap> 
          cache = new LruCache<String, Bitmap>(20); 

        @Override 
        public Bitmap getBitmap(String url) { 
         return cache.get(url); 
        } 

        @Override 
        public void putBitmap(String url, Bitmap bitmap) { 
         cache.put(url, bitmap); 
        } 
       }); 
    } 

    public static synchronized CustomVolleyRequest getInstance(Context context) { 
     if (customVolleyRequest == null) { 
      customVolleyRequest = new CustomVolleyRequest(context); 
     } 
     return customVolleyRequest; 
    } 

    public RequestQueue getRequestQueue() { 
     if (requestQueue == null) { 
      Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024); 
      Network network = new BasicNetwork(new HurlStack()); 
      requestQueue = new RequestQueue(cache, network); 
      requestQueue.start(); 
     } 
     return requestQueue; 
    } 

    public ImageLoader getImageLoader() { 
     return imageLoader; 
    } 
} 

это мой AppConfig класс для хранения тег

public class AppConfig { 
    // Server user login url 
    public static String URL_LOGIN = "http://192.168.0.13:80/task_manager/v1/login"; 

    // Server user register url 
    public static String URL_REGISTER = "http://192.168.0.13/task_manager/v1/register"; 

    //URL of my even 
    public static final String DATA_URL = "http://192.168.0.13/task_manager/v1/even/"; 

    //Tags for my JSON 

    public static final String TAG_IMAGE_URL = "gambar"; 
    public static final String TAG_JUDUL = "judul"; 
    public static final String TAG_DESKRIPSI = "deskripsi"; 
    public static final String TAG_DUIT = "duit"; 
    public static final String TAG_PERSEN = "persen"; 
    public static final String TAG_SISA_HARI = "sisahari"; 
} 

это геттер и сеттер

public class Event { 
     //Data Variables 
     private String imageUrl; 
     private String name; 
     private String rank; 
     private int realName; 
     private int createdBy; 
     private int firstAppearance; 
     //private ArrayList<String> powers; 

     //Getters and Setters 
     public String getImageUrl() { 
      return imageUrl; 
     } 

     public void setImageUrl(String imageUrl) { 
      this.imageUrl = imageUrl; 
     } 

     //GET AND SET JUDUL 
     public String getJudul() { 
      return name; 
     } 

     public void setJudul(String name) { 
      this.name = name; 
     } 

     //GET AND SET DESKRIPSI 
     public String getDeskripsi() { 
      return rank; 
     } 

     public void setDeskripsi(String rank) { 
      this.rank = rank; 
     } 

     //GET AND SET DUIT 

     public int getDuit() { 
      return realName; 
     } 

     public void setDuit(int realName) { 
      this.realName = realName; 
     } 

     //GET AND SET PERSEN 

     public int getPersen() { 
      return createdBy; 
     } 

     public void setPersen(int createdBy) { 
      this.createdBy = createdBy; 
     } 

     //GET AND SET SISA HARI 

     public int getSisaHari() { 
      return firstAppearance; 
     } 

     public void setSisaHari(int firstAppearance) { 
      this.firstAppearance = firstAppearance; 
     } 


    } 

и это мой основной фрагмент

public class EventFragment extends Fragment { 
    // 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; 

    //Creating a List of event 
    private List<Event> listEvent; 

    //Creating Views 
    private RecyclerView recyclerView; 
    private RecyclerView.LayoutManager layoutManager; 
    private RecyclerView.Adapter adapter; 
    private int requestCount = 1; 
    private OnFragmentInteractionListener mListener; 
    private RequestQueue requestQueue; 
    public EventFragment() { 
     // Required empty public constructor 
    } 

    /** 
    * 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 EventFragment. 
    */ 
    // TODO: Rename and change types and number of parameters 
    public static EventFragment newInstance(String param1, String param2) { 
     EventFragment fragment = new EventFragment(); 
     Bundle args = new Bundle(); 
     args.putString(ARG_PARAM1, param1); 
     args.putString(ARG_PARAM2, param2); 
     fragment.setArguments(args); 
     return fragment; 
    } 

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

    private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() { 
     @Override 
     public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) { 
      // code 
      if (isLastItemDisplaying(recyclerView)) { 
       //Calling the method getdata again 
       getData(); 
      } 
     } 

     @Override 
     public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) { 
      // code 
      if (isLastItemDisplaying(recyclerView)) { 
       //Calling the method getdata again 
       getData(); 
      } 
     } 
    }; 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View x = inflater.inflate(R.layout.fragment_event,null);; 
     recyclerView = (RecyclerView) x.findViewById(R.id.recyclerView); 
     recyclerView.setHasFixedSize(true); 
     layoutManager = new LinearLayoutManager(getActivity()); 
     recyclerView.setLayoutManager(layoutManager); 


     //Initializing our event list 
     listEvent = new ArrayList<>(); 
     requestQueue = Volley.newRequestQueue(getActivity().getApplication()); 
     //Calling method to get data 
     getData(); 
     recyclerView.addOnScrollListener(rVOnScrollListener); 
     adapter = new CardAdapter(listEvent, getActivity().getApplication()); 

     //Adding adapter to recyclerview 
     recyclerView.setAdapter(adapter); 
//  RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator(); 
//  itemAnimator.setAddDuration(1000); 
//  itemAnimator.setRemoveDuration(1000); 
//  recyclerView.setItemAnimator(itemAnimator); 
//  recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() { 
//   @Override 
//   public void onClick(View view, int position) { 
//    Intent intent = new Intent(getActivity(), DetailEvent.class); 
//    intent.putExtra("event_judul", listEvent.get(position).getJudul()); //you can name the keys whatever you like 
//    intent.putExtra("event_deskripsi", listEvent.get(position).getDeskripsi()); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.) 
//    intent.putExtra("event_duit", listEvent.get(position).getDuit()); 
//    intent.putExtra("event_persen", listEvent.get(position).getPersen()); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.) 
//    intent.putExtra("event_sisa_hari", listEvent.get(position).getSisaHari()); 
//    intent.putExtra("event_image", listEvent.get(position).getImageUrl()); 
//    startActivity(intent); 
//   } 
// 
//   @Override 
//   public void onLongClick(View view, int position) { 
//    Toast.makeText(getActivity(), "Kepencet Lama " + position, Toast.LENGTH_LONG).show(); 
//   } 
//  })); 

     return x; 
    } 
    private JsonArrayRequest getDataFromServer(int requestCount) { 
     //Initializing ProgressBar 
     final ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progressBar1); 

     //Displaying Progressbar 
     progressBar.setVisibility(View.VISIBLE); 
     getActivity().getParent().setProgressBarIndeterminateVisibility(true); 

     //JsonArrayRequest of volley 
     JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(AppConfig.DATA_URL + String.valueOf(requestCount), 
       new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         //Calling method parseData to parse the json response 
         parseData(response); 
         //Hiding the progressbar 
         progressBar.setVisibility(View.GONE); 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         progressBar.setVisibility(View.GONE); 
         //If an error occurs that means end of the list has reached 
         Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show(); 
        } 
       }); 

     //Returning the request 
     return jsonArrayRequest; 
    } 

    private void getData(){ 
     //Adding the method to the queue by calling the method getDataFromServer 
     requestQueue.add(getDataFromServer(requestCount)); 
     //Incrementing the request counter 
     requestCount++; 

    } 

    //This method will parse json data 
    private void parseData(JSONArray array){ 
     for(int i = 0; i<array.length(); i++) { 
      Event event = new Event(); 
      JSONObject json = null; 
      try { 
       json = array.getJSONObject(i); 

       event.setJudul(json.getString(AppConfig.TAG_JUDUL)); 
       event.setDeskripsi(json.getString(AppConfig.TAG_DESKRIPSI)); 
       event.setDuit(json.getInt(AppConfig.TAG_DUIT)); 
       event.setPersen(json.getInt(AppConfig.TAG_PERSEN)); 
       event.setSisaHari(json.getInt(AppConfig.TAG_SISA_HARI)); 
       event.setImageUrl(json.getString(AppConfig.TAG_IMAGE_URL)); 



      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      listEvent.add(event); 
     } 
     adapter.notifyDataSetChanged(); 

     //Finally initializing our adapter 

    } 
    // 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(Context context) { 
     super.onAttach(context); 
     if (context instanceof OnFragmentInteractionListener) { 
      mListener = (OnFragmentInteractionListener) context; 
     } else { 
      throw new RuntimeException(context.toString() 
        + " must implement OnFragmentInteractionListener"); 
     } 
    } 

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

    class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{ 
     private GestureDetector mGestureDetector; 
     private ClickListener mClickListener; 


     public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) { 
      this.mClickListener = clickListener; 
      mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){ 
       @Override 
       public boolean onSingleTapUp(MotionEvent e) { 
        return true; 
       } 

       @Override 
       public void onLongPress(MotionEvent e) { 
        View child = recyclerView.findChildViewUnder(e.getX(),e.getY()); 
        if (child!=null && clickListener!=null){ 
         clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child)); 
        } 
        super.onLongPress(e); 
       } 
      }); 
     } 

     @Override 
     public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { 
      View child = rv.findChildViewUnder(e.getX(), e.getY()); 
      if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){ 
       mClickListener.onClick(child, rv.getChildAdapterPosition(child)); 
      } 
      return false; 
     } 

     @Override 
     public void onTouchEvent(RecyclerView rv, MotionEvent e) { 

     } 

     @Override 
     public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { 

     } 
    } 

    private boolean isLastItemDisplaying(RecyclerView recyclerView) { 
     if (recyclerView.getAdapter().getItemCount() != 0) { 
      int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition(); 
      if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1) 
       return true; 
     } 
     return false; 
    } 
    private RecyclerView.OnScrollListener rVOnScrollListener = new RecyclerView.OnScrollListener(){ 
     @Override 
     public void onScrollStateChanged(RecyclerView recyclerView, 
             int newState) { 
      super.onScrollStateChanged(recyclerView, newState); 
//   Toast.makeText(getApplicationContext(), 
//     Config.DATA_URL+String.valueOf(requestCount), Toast.LENGTH_LONG).show(); 
     } 

     @Override 
     public void onScrolled(RecyclerView recyclerView, int dx, int dy) { 
      super.onScrolled(recyclerView, dx, dy); 
      if (isLastItemDisplaying(recyclerView)) { 
//Calling the method getdata again 
       getData(); 
      } 

     } 
    }; 
    public static interface ClickListener{ 
     public void onClick(View view, int position); 
     public void onLongClick(View view, int position); 
    } 
    /** 
    * 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 
     void onFragmentInteraction(Uri uri); 
    } 



} 

Я не знаю, где является причиной ошибки, если я не использую на изменение прокрутки слушателем и просто получать все данные JSon он работал. я использовать учебник по этой ссылке https://www.simplifiedcoding.net/android-feed-example-using-php-mysql-volley/ , и я хочу, чтобы изменить его фрагмент

+0

Что находится в строке 163 вашего класса EventFragment? – aribeiro

+0

, который является методом анализа данных json –

+0

Я использую учебное пособие по этой ссылке https://www.simplifiedcoding.net/android-feed-example-using-php-mysql-volley/, и я хочу изменить его на фрагмент –

ответ

1

Move ProgressBar связывают линии onCreateView():

private ProgressBar progressBar; 

Кодекс должен, как:

View x = inflater.inflate(R.layout.fragment_event,null); 
progressBar = (ProgressBar) x.findViewById(R.id.progressBar1); 

Причина: Каждый вид из Фрагмент будет связываться с rootView с Фрагмент.

Edit 1:

Удалить ниже линии:

getActivity().getParent().setProgressBarIndeterminateVisibility(true); 

Надеется, что это поможет.

+0

. для попытки, но он по-прежнему дает мне ту же ошибку, что и expoception. getDataFromServer (EventFragment.java:160), getData (EventFragment.java:192), onCreateView (EventFragment.java:127) –

+0

@PhilipusSilaen, я отредактировал свой ответ, пожалуйста, проверьте –

+0

@PhilipusSilaen, вы пробовали? –

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