在navigationmenu片段中设置列表视图

时间:2014-11-19 07:45:30

标签: android android-studio android-listfragment listadapter

嘿,我在设置列表视图时遇到问题... 该应用程序有一个导航绘图菜单,该菜单的第一个片段显示我的json数组列表...

查询工作但现在:我如何显示结果......

MyTickets.java     包de.hoell.jobcontrol;

/**
 * Created by Hoell on 16.10.2014.
 */


import android.app.ListFragment;
import android.app.ProgressDialog;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;


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

import java.util.ArrayList;

import java.util.HashMap;

import de.hoell.jobcontrol.query.Functions;

public class MyTickets extends ListFragment {
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_FIRMA = "Firma";
    public MyTickets(){};
    ArrayList<HashMap<String, String>> TheTickets = new ArrayList<HashMap<String, String>>();




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }




    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        new JSONMyTickets().execute();

       //TODO:FIND OUT HOW TO SET UP A LISTVIEW :'D

    }



    private class JSONMyTickets extends AsyncTask<String, String, JSONObject> {


        JSONArray Ticketliste = null;


        @Override
        protected JSONObject doInBackground(String... args) {
            String user;

            user = de.hoell.jobcontrol.Start.user;

            Functions Function = new Functions();
            JSONObject json = Function.MyTickets(user);

            // check for login response
            // check log cat fro response
            Log.d("Create Response", json.toString());
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {

            try {

                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    Ticketliste = json.getJSONArray("tickets");
                    for (int i = 0; i < Ticketliste.length(); i++) {
                        JSONObject c = Ticketliste.getJSONObject(i);
                        String Firma = c.getString("Firma");
                        String Ort = c.getString("Ort");
                        String Status = c.getString("Status");

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("Firma", Firma);
                        map.put("Ort", Ort);
                        map.put("Status", Status);

                        TheTickets.add(map);

                        System.out.println("Abfrage" + TheTickets);

                    }
                }
                else{

                    }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

幻灯片菜单

MainActivity.java             包de.hoell.jobcontrol;

    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentManager;
    import android.content.res.Configuration;
    import android.content.res.TypedArray;
    import android.os.Bundle;
    import android.support.v4.app.ActionBarDrawerToggle;
    import android.support.v4.widget.DrawerLayout;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.Toast;

    import java.util.ArrayList;

    import de.hoell.jobcontrol.adapter.NavDrawerListAdapter;
    import de.hoell.jobcontrol.model.NavDrawerItem;

    public class
            MainActivity extends Activity {
        private DrawerLayout mDrawerLayout;
        private ListView mDrawerList;
        private ActionBarDrawerToggle mDrawerToggle;

        // nav drawer title
        private CharSequence mDrawerTitle;

        // used to store app title
        private CharSequence mTitle;

        // slide menu items
        private String[] navMenuTitles;
        private TypedArray navMenuIcons;

        private ArrayList<NavDrawerItem> navDrawerItems;
        private NavDrawerListAdapter adapter;

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

            mTitle = mDrawerTitle = getTitle();

            // load slide menu items
            navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

            // nav drawer icons from resources
            navMenuIcons = getResources()
                    .obtainTypedArray(R.array.nav_drawer_icons);

            mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

            navDrawerItems = new ArrayList<NavDrawerItem>();

            // adding nav drawer items to array
            // MyTickets
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
            // Kalender
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
            // NewTickets
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));




            // Recycle the typed array
            navMenuIcons.recycle();

            mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

            // setting the nav drawer list adapter
            adapter = new NavDrawerListAdapter(getApplicationContext(),
                    navDrawerItems);
            mDrawerList.setAdapter(adapter);

            // enabling action bar app icon and behaving it as toggle button
            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setHomeButtonEnabled(true);

            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                    R.drawable.ic_drawer, //nav menu toggle icon
                    R.string.title_activity_slidermenu, // nav drawer open - description for accessibility
                    R.string.title_activity_slidermenu // nav drawer close - description for accessibility
            ) {
                public void onDrawerClosed(View view) {
                    getActionBar().setTitle(mTitle);
                    // calling onPrepareOptionsMenu() to show action bar icons
                    invalidateOptionsMenu();
                }

                public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle(mDrawerTitle);
                    // calling onPrepareOptionsMenu() to hide action bar icons
                    invalidateOptionsMenu();
                }
            };
            mDrawerLayout.setDrawerListener(mDrawerToggle);

            if (savedInstanceState == null) {
                // on first time display view for first nav item
                displayView(0);
            }
        }

        /**
         * Slide menu item click listener
         * */
        private class SlideMenuClickListener implements
                ListView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                // display view for selected nav drawer item
                displayView(position);
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // toggle nav drawer on selecting action bar app icon/title
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
            // Handle action bar actions click
            switch (item.getItemId()) {
                case R.id.action_info:
                    Toast.makeText(getApplicationContext(), "Version 0.0.6", Toast.LENGTH_SHORT).show();
                    return true;


                case R.id.action_search:
                    Toast.makeText(getApplicationContext(), "Searching...", Toast.LENGTH_SHORT).show();
                    return true;


                case R.id.action_refresh:
                    Toast.makeText(getApplicationContext(), "Refresh...", Toast.LENGTH_SHORT).show();
                    return true;
                default:

                    return super.onOptionsItemSelected(item);
            }
        }

        /***
         * Called when invalidateOptionsMenu() is triggered
         */
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            // if nav drawer is opened, hide the action items
            boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
            menu.findItem(R.id.action_search).setVisible(!drawerOpen);
            menu.findItem(R.id.action_refresh).setVisible(!drawerOpen);
            return super.onPrepareOptionsMenu(menu);
        }

        /**
         * Diplaying fragment view for selected nav drawer list item
         * */
        private void displayView(int position) {
            // update the main content by replacing fragments
            Fragment fragment = null;
            switch (position) {
                case 0:
                    fragment = new MyTickets();
                    break;
                case 1:
                    fragment = new Kalender();
                    break;
                case 2:
                    fragment = new NewTickets();
                    break;

                default:
                    break;
            }

            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit();

                // update selected item and title, then close the drawer
                mDrawerList.setItemChecked(position, true);
                mDrawerList.setSelection(position);
                setTitle(navMenuTitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                // error in creating fragment
                Log.e("MainActivity", "Error in creating fragment");
            }
        }

        @Override
        public void setTitle(CharSequence title) {
            mTitle = title;
            getActionBar().setTitle(mTitle);
        }

        /**
         * When using the ActionBarDrawerToggle, you must call it during
         * onPostCreate() and onConfigurationChanged()...
         */

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            // Sync the toggle state after onRestoreInstanceState has occurred.
            mDrawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            // Pass any configuration change to the drawer toggls
            mDrawerToggle.onConfigurationChanged(newConfig);
        }

    }

我的英语不好:/

2 个答案:

答案 0 :(得分:0)

简单列表的一些示例代码,简单的ArrayAdapter:

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);

String[] myResArray = getResources().getStringArray(R.array.nav_draw_entries); 
List<String> mArrayList = Arrays.asList(myResArray);

ListView listView = (ListView) findViewById(R.id.navView);
listView.setOnItemClickListener(this);

listView.setAdapter(new ArrayAdapter<String>(this,
        R.layout.drawer_nav_item, mArrayList));

其中'drawer_nav_item'是字符串条目的TextView布局类型。

其中R.id.navView是主布局中的listView,包括navBar的支持类

其中R.array.nav_draw_entries是strings.xml中定义的字符串的静态数组

答案 1 :(得分:0)

这里我删除整个片段并从表单开始:

这是工作结果:))))

<强> TicketFragment.java

package de.hoell.jobcontrol;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

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



import de.hoell.jobcontrol.query.Functions;
import de.hoell.jobcontrol.ticketlist.Tickets;

/**
 * A fragment representing a list of Items.
 * <p/>
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnTicketInteractionListener}
 * interface.
 */
public class TicketFragment extends ListFragment {

    // 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 static final String TAG_SUCCESS = "success";
    private static final String TAG_FIRMA = "Firma";

    ArrayList<HashMap<String, String>> TheTickets = new ArrayList<HashMap<String, String>>();
    List<Tickets> ticketsList = new ArrayList<Tickets>();
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnTicketInteractionListener mListener;

    // TODO: Rename and change types of parameters
    public static TicketFragment newInstance(String param1, String param2) {
        TicketFragment fragment = new TicketFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public TicketFragment() {
    }

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

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        new JSONMyTickets().execute();
    }


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

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


    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.

        }
    }

    /**
     * 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 OnTicketInteractionListener {
        // TODO: Update argument type and name
        public void onTicketInteraction(String id);
    }










    public class JSONMyTickets extends AsyncTask<String, String, JSONObject> {


        JSONArray Ticketliste = null;


        @Override
        protected JSONObject doInBackground(String... args) {
            String user;

            user = de.hoell.jobcontrol.Start.user;

            Functions Function = new Functions();
            JSONObject json = Function.MyTickets(user);

            // check for login response
            // check log cat fro response
            Log.d("Create Response", json.toString());
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {

            try {

                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    Ticketliste = json.getJSONArray("tickets");
                    for (int i = 0; i < Ticketliste.length(); i++) {
                        JSONObject c = Ticketliste.getJSONObject(i);
                        String Firma = c.getString("Firma");
                        String Ort = c.getString("Ort");
                        String Status = c.getString("Status");


                        ticketsList.add(new Tickets(Firma+ ", "+ Ort + ", "+ Status));


                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("Firma", Firma);
                        map.put("Ort", Ort);
                        map.put("Status", Status);

                        TheTickets.add(map);



                    }System.out.println("Abfrage" + TheTickets);

                }
                else{


                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            setListAdapter(new ArrayAdapter<Tickets>(getActivity(),
                    android.R.layout.simple_list_item_1, android.R.id.text1, ticketsList));
        }
    }




}

<强> Tickets.java

package de.hoell.jobcontrol.ticketlist;



/**
 * Created by Hoell on 20.11.2014.
 */
public class Tickets {

    private String id;
    private String content;

    public Tickets(String id) {
    this.id = id;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString(){

        return id;

    }




}