2014-01-06 3 views
0

Итак, я создаю приложение, которое берет данные с этой страницы: http://api.androidhive.info/contacts/ и помещает их в список в этом фрагменте. Я использую ListFragment. Мне было сложнее всего собрать все, особенно с возвратом представления в oncreateview(). Я получаю эту ошибку: enter image description hereне удалось создать экземпляр ActivityInfo в моем скользящем меню listfragment

вот мой MainActivity:

public class MainActivity extends Activity { 

// Within which the entire activity is enclosed 
DrawerLayout mDrawerLayout; 

// ListView represents Navigation Drawer 
ListView mDrawerList; 

// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar 
ActionBarDrawerToggle mDrawerToggle; 

// Title of the action bar 
String mTitle=""; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mTitle = (String) getTitle(); 

    // Getting reference to the DrawerLayout 
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 

    mDrawerList = (ListView) findViewById(R.id.drawer_list); 

    // Getting reference to the ActionBarDrawerToggle 
    mDrawerToggle = new ActionBarDrawerToggle(this, 
     mDrawerLayout, 
     R.drawable.ic_drawer, 
     R.string.drawer_open, 
     R.string.drawer_close){ 

      /** Called when drawer is closed */ 
      public void onDrawerClosed(View view) { 
       getActionBar().setTitle(mTitle); 
       invalidateOptionsMenu(); 
      } 

      /** Called when a drawer is opened */ 
      public void onDrawerOpened(View drawerView) { 
       getActionBar().setTitle("Select Option"); 
       invalidateOptionsMenu(); 
      } 
    }; 

    // Setting DrawerToggle on DrawerLayout 
    mDrawerLayout.setDrawerListener(mDrawerToggle); 

    // Creating an ArrayAdapter to add items to the listview mDrawerList 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
     getBaseContext(), 
     R.layout.drawer_list_item , 
     getResources().getStringArray(R.array.options) 
    ); 

    // Setting the adapter on mDrawerList 
    mDrawerList.setAdapter(adapter); 

    // Enabling Home button 
    getActionBar().setHomeButtonEnabled(true); 

    // Enabling Up navigation 
    getActionBar().setDisplayHomeAsUpEnabled(true); 

    // Setting item click listener for the listview mDrawerList 
    mDrawerList.setOnItemClickListener(new OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

       // Getting an array of options 
       String[] options = getResources().getStringArray(R.array.options); 

       //Currently selected option 
       mTitle = options[position]; 

       if(mTitle.equalsIgnoreCase("Home")){ 
        // Creating a fragment object 
        Fragment fragment = new AppMain(); 

        // Creating a Bundle object 
        Bundle data = new Bundle(); 

        // Setting the index of the currently selected item of mDrawerList 
        data.putInt("position", position); 

        // Setting the position to the fragment 
        fragment.setArguments(data); 

        // Getting reference to the FragmentManager 
        FragmentManager fragmentManager = getFragmentManager(); 

        // Creating a fragment transaction 
        FragmentTransaction ft = fragmentManager.beginTransaction(); 

        // Adding a fragment to the fragment transaction 
        ft.replace(R.id.content_frame, fragment); 

        // Committing the transaction 
        ft.commit(); 

        // Closing the drawer 
        mDrawerLayout.closeDrawer(mDrawerList); 

       } 

       else if(mTitle.equalsIgnoreCase("Map")){ 
        // Creating a fragment object 
        Fragment fragment = new MapFragment(); 

        // Creating a Bundle object 
        Bundle data = new Bundle(); 

        // Setting the index of the currently selected item of mDrawerList 
        data.putInt("position", position); 

        // Setting the position to the fragment 
        fragment.setArguments(data); 

        // Getting reference to the FragmentManager 
        FragmentManager fragmentManager = getFragmentManager(); 

        // Creating a fragment transaction 
        FragmentTransaction ft = fragmentManager.beginTransaction(); 

        // Adding a fragment to the fragment transaction 
        ft.replace(R.id.content_frame, fragment); 

        // Committing the transaction 
        ft.commit(); 

        // Closing the drawer 
        mDrawerLayout.closeDrawer(mDrawerList); 

       } 
       //its possible to create a series of these and then 
       //initialize objects within the fragments programmably. 

       //DrawerOptions need to be removed to make things work 
       else if(mTitle.equalsIgnoreCase("ATO")){ 

       // Creating a fragment object 
        Fragment fragment = new ATO(); 

        // Creating a Bundle object 
        Bundle data = new Bundle(); 

        // Setting the index of the currently selected item of mDrawerList 
        data.putInt("position", position); 

        // Setting the position to the fragment 
        fragment.setArguments(data); 

        // Getting reference to the FragmentManager 
        FragmentManager fragmentManager = getFragmentManager(); 

        // Creating a fragment transaction 
        FragmentTransaction ft = fragmentManager.beginTransaction(); 

        // Adding a fragment to the fragment transaction 
        ft.replace(R.id.content_frame, fragment); 

        // Committing the transaction 
        ft.commit(); 

       // Closing the drawer 
       mDrawerLayout.closeDrawer(mDrawerList); 

       // Closing the drawer 
       mDrawerLayout.closeDrawer(mDrawerList); 
     } 
       else{ 

       } 
     } 
    }); 
} 

    @Override 
protected void onPostCreate(Bundle savedInstanceState) { 
    super.onPostCreate(savedInstanceState); 
    mDrawerToggle.syncState(); 
} 

/** Handling the touch event of app icon */ 
@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    if (mDrawerToggle.onOptionsItemSelected(item)) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

/* 
* I commented out this section below because I don't see us using it. 
* It does nothing more than show a little button which says "settings" 
* in the top right corner of the bar. If you want to enable it, de-comment 
* and then look at the main.xml within the menu folder and de-commnent there. 
* Also have to go to the Strings.xml file under values and de-comment. 
*/ 

/** Called whenever we call invalidateOptionsMenu() */ 
    @Override 
// public boolean onPrepareOptionsMenu(Menu menu) { 
//  // If the drawer is open, hide action items related to the content view 
//  boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
// 
//  menu.findItem(R.id.action_settings).setVisible(!drawerOpen); 
//  return super.onPrepareOptionsMenu(menu); 
// } 
// 

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

И это мой ATO класс, который им, имеющие много неприятностей с:

public class ATO extends ListFragment { 

    private ProgressDialog pDialog; 

    // URL to get contacts JSON 
    private static String url = "http://api.androidhive.info/contacts/"; 

    // JSON Node names 
    private static final String TAG_CONTACTS = "contacts"; 
private static final String TAG_ID = "id"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_EMAIL = "email"; 
private static final String TAG_ADDRESS = "address"; 
private static final String TAG_GENDER = "gender"; 
private static final String TAG_PHONE = "phone"; 
private static final String TAG_PHONE_MOBILE = "mobile"; 
private static final String TAG_PHONE_HOME = "home"; 
private static final String TAG_PHONE_OFFICE = "office"; 

// contacts JSONArray 
JSONArray contacts = null; 

// Hashmap for ListView 
ArrayList<HashMap<String, String>> contactList; 

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

    // Retrieving the currently selected item number 
    int position = getArguments().getInt("position"); 

    // List of options 
    String[] options = getResources().getStringArray(R.array.options); 

    // Creating view correspoding to the fragment 
    View v = inflater.inflate(R.layout.ato, container, false); 

    // Getting reference to the TextView of the Fragment 
    TextView tv = (TextView) v.findViewById(R.id.textView1); 

    String words = "Home of the app"; 
    // Setting currently selected river name in the TextView 
    tv.setText(words); 

    // Updating the action bar title 
    getActivity().getActionBar().setTitle(options[position]); 

    // Calling async task to get json 
    new GetContacts().execute(); 

    return v; 
} 

/** 
* Async task class to get json by making HTTP call 
* */ 
private class GetContacts extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(getActivity()); 
     // 
     pDialog.setMessage("Please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     // Creating service handler class instance 
     ServiceHandler sh = new ServiceHandler(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

     if (jsonStr != null) { 
      try { 
       JSONObject jsonObj = new JSONObject(jsonStr); 

       // Getting JSON Array node 
       contacts = jsonObj.getJSONArray(TAG_CONTACTS); 

       // looping through All Contacts 
       for (int i = 0; i < contacts.length(); i++) { 
        JSONObject c = contacts.getJSONObject(i); 

        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_NAME); 
        String email = c.getString(TAG_EMAIL); 
        String address = c.getString(TAG_ADDRESS); 
        String gender = c.getString(TAG_GENDER); 

        // Phone node is JSON Object 
        JSONObject phone = c.getJSONObject(TAG_PHONE); 
        String mobile = phone.getString(TAG_PHONE_MOBILE); 
        String home = phone.getString(TAG_PHONE_HOME); 
        String office = phone.getString(TAG_PHONE_OFFICE); 

        // tmp hashmap for single contact 
        HashMap<String, String> contact = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        contact.put(TAG_ID, id); 
        contact.put(TAG_NAME, name); 
        contact.put(TAG_EMAIL, email); 
        contact.put(TAG_PHONE_MOBILE, mobile); 

        // adding contact to contact list 
        contactList.add(contact); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     SimpleAdapter adapter = new SimpleAdapter(getActivity(), contactList, 
       R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL, 
         TAG_PHONE_MOBILE }, new int[] { R.id.name, 
         R.id.email, R.id.mobile }); 

     setListAdapter(adapter); 
    } 

} 

/* 
* { 
"contacts": [ 
    { 
      "id": "c200", 
      "name": "Ravi Tamada", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c201", 
      "name": "Johnny Depp", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c202", 
      "name": "Leonardo Dicaprio", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c203", 
      "name": "John Wayne", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c204", 
      "name": "Angelina Jolie", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "female", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c205", 
      "name": "Dido", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "female", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c206", 
      "name": "Adele", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "female", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c207", 
      "name": "Hugh Jackman", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c208", 
      "name": "Will Smith", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c209", 
      "name": "Clint Eastwood", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c2010", 
      "name": "Barack Obama", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c2011", 
      "name": "Kate Winslet", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "female", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    }, 
    { 
      "id": "c2012", 
      "name": "Eminem", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    } 
] 
} 
    */ 

} 

Любых и вся помощь действительно оценили!

+0

Я только что понял, что я случайно оставил оператор if, чтобы перейти на страницу ATO в качестве намерения, я изменил его на фрагмент, но все равно по ошибке – booky99

ответ

0

Вы обрабатываете ATO как действие, когда оно фактически является списком. Линия:

Intent intent = new Intent(MainActivity.this, ATO.class); 

Невозможно использовать для запуска списка. ListFragments, как и любой другой фрагмент, должен быть прикреплен к существующей Деятельности.

Вы можете найти информацию о том, как это сделать в documentation.

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