Member 13347940 Ответов: 0

Приложение Navigation drawer остановилось с фрагментами и разбором JSON.


Эй, ребята, я застрял с моим приложением, которое включает в себя навигационный ящик и элементы, при нажатии на один из элементов он открывает вид recycler с разбором json, но мое приложение всегда закрывается, в чем проблема?Мое приложение вообще не открывается, и если вам нужен какой-либо xml-файл, я готов предоставить его, пожалуйста, помогите мне в этой ситуации и спасибо...

Мой Главный Activity.java
package com.pappu5.navigation;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import static com.pappu5.navigation.R.id.pappuLayout;
import static com.pappu5.navigation.R.id.recyclerView;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,GalleryFrag.OnFragmentInteractionListener {





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.pappuLayout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //add this line to display menu1 when the activity is loaded
        displaySelectedScreen(R.id.nav_gallery);
    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.pappuLayout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        displaySelectedScreen(item.getItemId());

        return true;
    }

    private void displaySelectedScreen(int itemId) {

        //creating fragment object
        Fragment fragment = null;

        //initializing the fragment object which is selected
        switch (itemId) {
            case R.id.nav_gallery:
                fragment = new GalleryFrag();
                break;
            /*case R.id.nav_menu2:
                fragment = new Menu2();
                break;
            case R.id.nav_menu3:
                fragment = new Menu3();
                break;*/
        }

        //replacing the fragment
        if (fragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, fragment);
            ft.commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(pappuLayout);
        drawer.closeDrawer(GravityCompat.START);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}


Фрагмент Моей Галереи

package com.pappu5.navigation;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.annotation.Nullable;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link GalleryFrag.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link GalleryFrag#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GalleryFrag 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";

    private RecyclerView rv;
    private RecyclerView.Adapter adapter;
    private List<ListItem> lt;
    private String url = "https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=8b66f69591fc49229753135fe44488a5";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public GalleryFrag() {
        // 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 GalleryFrag.
     */
    // TODO: Rename and change types and number of parameters
    public static GalleryFrag newInstance(String param1, String param2) {
        GalleryFrag fragment = new GalleryFrag();
        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);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rv = (RecyclerView)getView().findViewById(R.id.recyclerView);
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        lt =  new ArrayList<>();
        loadRecyclerData();
        View view =  inflater.inflate(R.layout.fragment_gallery, container, false);
        return view;
    }

    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("Menu 1");
    }

    private void loadRecyclerData() {
        final ProgressDialog pd = new ProgressDialog(getActivity());
        pd.setMessage("Fetching the data..");
        pd.show();

        StringRequest sr = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        pd.dismiss();
                        try {
                            JSONObject json = new JSONObject(response);
                            JSONArray jarray = new JSONArray("articles");
                            for (int i =0 ; i<jarray.length() ; i++){
                                JSONObject jo = jarray.getJSONObject(i);
                                ListItem lm = new ListItem(
                                        jo.getString("author"),
                                        jo.getString("title"),
                                        jo.getString("description"),
                                        jo.getString("url"),
                                        jo.getString("urlToImage"),
                                        jo.getString("publishedAt")
                                );
                                lt.add(lm);
                            }
                            adapter = new MyAdapter(lt,getActivity().getApplicationContext());
                            rv.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
        rq.add(sr);
    }

    // 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;
    }

    /**
     * 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);
    }
}


Ошибки, то есть stacktrace, которые я получаю

08-06 00:26:40.142 8894-8894/? I/art: Late-enabling -Xcheck:jni
08-06 00:26:40.218 8894-8894/com.pappu5.navigation W/System: ClassLoader referenced unknown path: /data/app/com.pappu5.navigation-2/lib/arm
08-06 00:26:40.366 8894-8894/com.pappu5.navigation D/AndroidRuntime: Shutting down VM
08-06 00:26:40.367 8894-8894/com.pappu5.navigation E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.pappu5.navigation, PID: 8894
                                                                     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pappu5.navigation/com.pappu5.navigation.MainActivity}: java.lang.IllegalArgumentException: No drawer view found with gravity LEFT
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
                                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                      Caused by: java.lang.IllegalArgumentException: No drawer view found with gravity LEFT
                                                                         at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1660)
                                                                         at com.pappu5.navigation.MainActivity.displaySelectedScreen(MainActivity.java:127)
                                                                         at com.pappu5.navigation.MainActivity.onCreate(MainActivity.java:54)
                                                                         at android.app.Activity.performCreate(Activity.java:6672)
                                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
                                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                         at android.os.Looper.loop(Looper.java:154) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6123) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 


Что я уже пробовал:

я перепробовал почти все, что мог, и я новичок в этом программировании android, пожалуйста, помогите мне ...спасибо..

Richard MacCutchan

Посмотрите на сообщения об ошибках и выясните, почему эти компоненты не могут быть найдены. Это ясно говорит вам, что /данных/приложение/ком.pappu5.навигация-2/Либ/рукоятки это неверный путь.

David Crow

В момент щелчка вы прошли через код с помощью отладчика?

0 Ответов