Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在片段内解析RecylcerView中的JSON数据_Java_Android_Json_Android Fragments - Fatal编程技术网

Java 在片段内解析RecylcerView中的JSON数据

Java 在片段内解析RecylcerView中的JSON数据,java,android,json,android-fragments,Java,Android,Json,Android Fragments,我需要一些关于我问题逻辑的帮助。我已经在这里搜索了讨论类似问题的帖子,但是还没有成功解决我的问题,所以我不想重复这篇帖子 我正在开发一个应用程序,在幻灯片选项卡片段的回收器视图中显示解析的JSON数据时遇到问题。我在我的主要活动上有一个滑动选项卡,总共有五个片段,每个选项卡一个(总共5个选项卡)。对于第三个选项卡,我要做的是显示一个recycler视图,其中包含从服务器检索的已解析JSON数据。我的其他recyclerviews在活动中具有相同的功能,它们工作正常。我只是在为如何在一个片段中实现

我需要一些关于我问题逻辑的帮助。我已经在这里搜索了讨论类似问题的帖子,但是还没有成功解决我的问题,所以我不想重复这篇帖子

我正在开发一个应用程序,在幻灯片选项卡片段的回收器视图中显示解析的JSON数据时遇到问题。我在我的主要活动上有一个滑动选项卡,总共有五个片段,每个选项卡一个(总共5个选项卡)。对于第三个选项卡,我要做的是显示一个recycler视图,其中包含从服务器检索的已解析JSON数据。我的其他recyclerviews在活动中具有相同的功能,它们工作正常。我只是在为如何在一个片段中实现这一点而挣扎。我提供以下代码用于故障排除和调试目的:

以下是myMainActivity.java的代码

public class MainActivity extends BaseActivity {

private ViewPager mPager;
private SlidingTabLayout mTabs;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // To track statistics around application
    ParseAnalytics.trackAppOpened(getIntent());

    // inform the Parse Cloud that it is ready for notifications
    ParseInstallation.getCurrentInstallation().saveInBackground();

    //Calling Activate Toolbar method
    activateToolBar();

    mPager = (ViewPager) findViewById(R.id.pager);
    //Setting the Adapter on the view pager first. Passing the fragment manager through as an argument
    mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    mTabs = (SlidingTabLayout) findViewById(R.id.tabs);

    //Setting the custom Tab View as the Sliding Tabs Layout
    mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabText);

    mTabs.setDistributeEvenly(true);

    //mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.tabIndicatorColour));

    mTabs.setBackgroundColor(getResources().getColor(R.color.basePrimaryBackgroundColour));

    //Setting the ViewPager as the tabs
    mTabs.setViewPager(mPager);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.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);
}

class MyPagerAdapter extends FragmentPagerAdapter {


    String[] tabs;

    public  MyPagerAdapter(FragmentManager fm) {
        super(fm);

        //Initialising the strings array of the tabs
        tabs = getResources().getStringArray(R.array.tabs);

    }

    /*
    //Setting up integer array of icons
    int icons[] = {R.drawable.about_us, R.drawable.campus, R.drawable.events, R.drawable.learning, R.drawable.sewa};

    //Defined from strings.xml
    String[] tabText = getResources().getStringArray(R.array.tabs);

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        //Initialising the strings array of tabs
        tabText = getResources().getStringArray(R.array.tabs);

    }
    */

    @Override
    public Fragment getItem(int position) {

        if (position == 0) // if the position is 0 we are returning the First tab
        {
            Tab1 tab1 = new Tab1();
            return tab1;

        } else if (position == 1)
        {
            Tab2 tab2 = new Tab2();
            return tab2;

        } else if (position == 2)
        {
            Tab3 tab3 = new Tab3();
            return tab3;

        } else if (position == 3)
        {
            Tab4 tab4 = new Tab4();
            return tab4;

        } else
        {
            Tab5 tab5 = new Tab5();
            return tab5;
        }
    }


    @Override
    public CharSequence getPageTitle(int position) {

        //Return the text of the position clicked and display this as the title for the tab
        return tabs[position];
    }

    @Override
    public int getCount() {
        return 5;
    }
  }
}
public class RecyclerViewAdapterEvents extends RecyclerView.Adapter<RecyclerViewAdapterEvents.MyViewHolder> {

private LayoutInflater inflater;

//private EventsActivity activity;

private List<JSONEventsItem> data = Collections.emptyList();

private Context mContext;

//Variable for the on click Listener
private ClickListener clickListener;

//Passing in the array list argument
public RecyclerViewAdapterEvents(Context context, List<JSONEventsItem> data) {

    this.mContext = context;
    //this.activity = activity;

    inflater = LayoutInflater.from(context);

    //Setting the array list data to the argument passed in
    this.data = data;

}

@Override
public RecyclerViewAdapterEvents.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    //Inflating the row and getting the root of view of the custom row (Linear Layout)
    View view = inflater.inflate(R.layout.custom_row, parent, false);

    //Passing the root view through as an argument
    MyViewHolder holder = new MyViewHolder(view);

    //Returning the view holder
    return holder;
}

@Override
public void onBindViewHolder(RecyclerViewAdapterEvents.MyViewHolder holder, int position) {

    //This will get the current position of the JSONEventItem object from the array
    JSONEventsItem eventsItem = data.get(position);

    //Setting the event name to the name of the event retrieved from the Database (converting from JSON)
    holder.eventName.setText(Html.fromHtml(eventsItem.getEventName()));

}

@Override
public int getItemCount() {

    return (null != data ? data.size() : 0);
}

public void setClickListener(ClickListener clicklistener) {
    this.clickListener = clicklistener;
}

public interface ClickListener {
}

class MyViewHolder extends RecyclerView.ViewHolder {

    TextView eventName;

    public MyViewHolder(View itemView) {
        super(itemView);

        //Here setting the id of the textview in the recycler view holder to be the list view from the custom_row xml
        eventName = (TextView) itemView.
                findViewById(R.id.listText);
    }
  }
}
public class Tab3 extends Fragment implements RecyclerViewAdapterEvents.ClickListener{

private RecyclerView mRecyclerView;

//Creating an instance of the adapter object
private RecyclerViewAdapterEvents adapter;

private List<JSONEventsItem> EventsList;

private String jsonString = "";


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

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

    //Instantiating the recycler view as defined in tab_1
    mRecyclerView = (RecyclerView) v.findViewById(R.id.about_us_recycler_view);

    //Adding item decoration. Recycler view divider
    mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

    //Initialising the adapter - Passing in the activity and the getData method
    adapter = new RecyclerViewAdapterEvents(getActivity(), EventsList);

    //Here passing in the click listener into the Adapter. 'this' signifies that it is the fragment that handles the click listener.
    //This is possible as the on Click Listener interface is being implemented.
    adapter.setClickListener(this);

    //Setting the adapter
    mRecyclerView.setAdapter(adapter);

    //Setting the Layout
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    //Downloading data from below url (Universal Resource Locator) to obtain data from the Admin database
    final String url = "http://dbchudasama.webfactional.com/jsonscript.php";
    new AsyncHTTPTask().execute(url);

    return v;

    }

public class AsyncHTTPTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP OK
            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                jsonString = response.toString();
                parseResult();
                result = 1; // Successful
            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            Log.d("Exception Caught", e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {

        super.onPostExecute(result);

        //adapter.getItemCount();

        if (result == 1) {
            //Intent intent = getIntent();
            //intent.getSerializableExtra("JSON Admin");
            //Initialising the adapter - Passing in the activity and the parsed Admin Team List
            adapter = new RecyclerViewAdapterEvents(getActivity(), EventsList);
            //Setting the adapter
            mRecyclerView.setAdapter(adapter);
        } else {
            Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
        }
    }
}

//This method will parse the RAW data downloaded from the server
private void parseResult() {

    try {

        JSONArray AdminArrays = new JSONArray(jsonString);
        EventsList = new ArrayList<>();

        for (int i = 0; i < AdminArrays.length(); i++) {
            JSONObject AdminArrayObject = AdminArrays.getJSONObject(i);
            JSONEventsItem item = new JSONEventsItem();
            item.setEventName(AdminArrayObject.getString("eventName"));

            this.EventsList.add(item);

            Log.e("Event Name", AdminArrayObject.getString("eventName"));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
  }
}
这是myRecycleServiceAdapterEvents.java的代码

public class MainActivity extends BaseActivity {

private ViewPager mPager;
private SlidingTabLayout mTabs;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // To track statistics around application
    ParseAnalytics.trackAppOpened(getIntent());

    // inform the Parse Cloud that it is ready for notifications
    ParseInstallation.getCurrentInstallation().saveInBackground();

    //Calling Activate Toolbar method
    activateToolBar();

    mPager = (ViewPager) findViewById(R.id.pager);
    //Setting the Adapter on the view pager first. Passing the fragment manager through as an argument
    mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    mTabs = (SlidingTabLayout) findViewById(R.id.tabs);

    //Setting the custom Tab View as the Sliding Tabs Layout
    mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabText);

    mTabs.setDistributeEvenly(true);

    //mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.tabIndicatorColour));

    mTabs.setBackgroundColor(getResources().getColor(R.color.basePrimaryBackgroundColour));

    //Setting the ViewPager as the tabs
    mTabs.setViewPager(mPager);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.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);
}

class MyPagerAdapter extends FragmentPagerAdapter {


    String[] tabs;

    public  MyPagerAdapter(FragmentManager fm) {
        super(fm);

        //Initialising the strings array of the tabs
        tabs = getResources().getStringArray(R.array.tabs);

    }

    /*
    //Setting up integer array of icons
    int icons[] = {R.drawable.about_us, R.drawable.campus, R.drawable.events, R.drawable.learning, R.drawable.sewa};

    //Defined from strings.xml
    String[] tabText = getResources().getStringArray(R.array.tabs);

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        //Initialising the strings array of tabs
        tabText = getResources().getStringArray(R.array.tabs);

    }
    */

    @Override
    public Fragment getItem(int position) {

        if (position == 0) // if the position is 0 we are returning the First tab
        {
            Tab1 tab1 = new Tab1();
            return tab1;

        } else if (position == 1)
        {
            Tab2 tab2 = new Tab2();
            return tab2;

        } else if (position == 2)
        {
            Tab3 tab3 = new Tab3();
            return tab3;

        } else if (position == 3)
        {
            Tab4 tab4 = new Tab4();
            return tab4;

        } else
        {
            Tab5 tab5 = new Tab5();
            return tab5;
        }
    }


    @Override
    public CharSequence getPageTitle(int position) {

        //Return the text of the position clicked and display this as the title for the tab
        return tabs[position];
    }

    @Override
    public int getCount() {
        return 5;
    }
  }
}
public class RecyclerViewAdapterEvents extends RecyclerView.Adapter<RecyclerViewAdapterEvents.MyViewHolder> {

private LayoutInflater inflater;

//private EventsActivity activity;

private List<JSONEventsItem> data = Collections.emptyList();

private Context mContext;

//Variable for the on click Listener
private ClickListener clickListener;

//Passing in the array list argument
public RecyclerViewAdapterEvents(Context context, List<JSONEventsItem> data) {

    this.mContext = context;
    //this.activity = activity;

    inflater = LayoutInflater.from(context);

    //Setting the array list data to the argument passed in
    this.data = data;

}

@Override
public RecyclerViewAdapterEvents.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    //Inflating the row and getting the root of view of the custom row (Linear Layout)
    View view = inflater.inflate(R.layout.custom_row, parent, false);

    //Passing the root view through as an argument
    MyViewHolder holder = new MyViewHolder(view);

    //Returning the view holder
    return holder;
}

@Override
public void onBindViewHolder(RecyclerViewAdapterEvents.MyViewHolder holder, int position) {

    //This will get the current position of the JSONEventItem object from the array
    JSONEventsItem eventsItem = data.get(position);

    //Setting the event name to the name of the event retrieved from the Database (converting from JSON)
    holder.eventName.setText(Html.fromHtml(eventsItem.getEventName()));

}

@Override
public int getItemCount() {

    return (null != data ? data.size() : 0);
}

public void setClickListener(ClickListener clicklistener) {
    this.clickListener = clicklistener;
}

public interface ClickListener {
}

class MyViewHolder extends RecyclerView.ViewHolder {

    TextView eventName;

    public MyViewHolder(View itemView) {
        super(itemView);

        //Here setting the id of the textview in the recycler view holder to be the list view from the custom_row xml
        eventName = (TextView) itemView.
                findViewById(R.id.listText);
    }
  }
}
public class Tab3 extends Fragment implements RecyclerViewAdapterEvents.ClickListener{

private RecyclerView mRecyclerView;

//Creating an instance of the adapter object
private RecyclerViewAdapterEvents adapter;

private List<JSONEventsItem> EventsList;

private String jsonString = "";


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

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

    //Instantiating the recycler view as defined in tab_1
    mRecyclerView = (RecyclerView) v.findViewById(R.id.about_us_recycler_view);

    //Adding item decoration. Recycler view divider
    mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

    //Initialising the adapter - Passing in the activity and the getData method
    adapter = new RecyclerViewAdapterEvents(getActivity(), EventsList);

    //Here passing in the click listener into the Adapter. 'this' signifies that it is the fragment that handles the click listener.
    //This is possible as the on Click Listener interface is being implemented.
    adapter.setClickListener(this);

    //Setting the adapter
    mRecyclerView.setAdapter(adapter);

    //Setting the Layout
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    //Downloading data from below url (Universal Resource Locator) to obtain data from the Admin database
    final String url = "http://dbchudasama.webfactional.com/jsonscript.php";
    new AsyncHTTPTask().execute(url);

    return v;

    }

public class AsyncHTTPTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP OK
            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                jsonString = response.toString();
                parseResult();
                result = 1; // Successful
            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            Log.d("Exception Caught", e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {

        super.onPostExecute(result);

        //adapter.getItemCount();

        if (result == 1) {
            //Intent intent = getIntent();
            //intent.getSerializableExtra("JSON Admin");
            //Initialising the adapter - Passing in the activity and the parsed Admin Team List
            adapter = new RecyclerViewAdapterEvents(getActivity(), EventsList);
            //Setting the adapter
            mRecyclerView.setAdapter(adapter);
        } else {
            Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
        }
    }
}

//This method will parse the RAW data downloaded from the server
private void parseResult() {

    try {

        JSONArray AdminArrays = new JSONArray(jsonString);
        EventsList = new ArrayList<>();

        for (int i = 0; i < AdminArrays.length(); i++) {
            JSONObject AdminArrayObject = AdminArrays.getJSONObject(i);
            JSONEventsItem item = new JSONEventsItem();
            item.setEventName(AdminArrayObject.getString("eventName"));

            this.EventsList.add(item);

            Log.e("Event Name", AdminArrayObject.getString("eventName"));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
  }
}
我哪里做错了?任何指导都将非常有用:)


谢谢

请显示崩溃日志我看到的一个问题是在fragmnet内部,您必须添加@Override public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);},但是如果您提供logcat@ρσρK和Omid Aminiva会更容易谢谢!请参阅我上面修改的帖子-我提供了Logcat的崩溃日志:)我解决了这个问题。Noob错误。代码在片段中非常好。在正确阅读了碰撞日志后,我意识到我忘记在我正在膨胀的布局中定义回收器视图。在布局中添加此选项修复了以下问题:)。