2014-04-05 106 views
0

我是Android新手,所以我需要一點幫助:)Android FragmentActivity與Json數據列表視圖

我使用Eclips創建了一個應用程序。該應用程序使用片段。

enter image description here

現在我想用JSON數據列表視圖中的第一個片段。我遵循這個例子,並改變了一些代碼,但是當我啓動模擬器時,它給出了應用程序停止的錯誤。 http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

這裏是我的代碼:

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Locale; 

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

import android.app.ActionBar; 
import android.app.FragmentTransaction; 
import android.app.ProgressDialog; 
import android.graphics.Color; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

public class MainActivity extends FragmentActivity implements 
    ActionBar.TabListener { 
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 
static ArrayList<HashMap<String, String>> contactList; 

/** 
* The {@link android.support.v4.view.PagerAdapter} that will provide 
* fragments for each of the sections. We use a 
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which 
* will keep every loaded fragment in memory. If this becomes too memory 
* intensive, it may be best to switch to a 
* {@link android.support.v4.app.FragmentStatePagerAdapter}. 
*/ 
SectionsPagerAdapter mSectionsPagerAdapter; 

/** 
* The {@link ViewPager} that will host the section contents. 
*/ 
ViewPager mViewPager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    new GetContacts().execute(); 
    contactList = new ArrayList<HashMap<String, String>>(); 

    // Set up the action bar. 
    final ActionBar actionBar = getActionBar(); 
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the app. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(
      getSupportFragmentManager()); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    // When swiping between different sections, select the corresponding 
    // tab. We can also use ActionBar.Tab#select() to do this if we have 
    // a reference to the Tab. 
    mViewPager 
      .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
       @Override 
       public void onPageSelected(int position) { 
        actionBar.setSelectedNavigationItem(position); 
       } 
      }); 

    // For each of the sections in the app, add a tab to the action bar. 
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
     // Create a tab with text corresponding to the page title defined by 
     // the adapter. Also specify this Activity object, which implements 
     // the TabListener interface, as the callback (listener) for when 
     // this tab is selected. 
     actionBar.addTab(actionBar.newTab() 
       .setText(mSectionsPagerAdapter.getPageTitle(i)) 
       .setTabListener(this)); 
    } 
} 

@Override 
public void onTabSelected(ActionBar.Tab tab, 
     FragmentTransaction fragmentTransaction) { 
    // When the given tab is selected, switch to the corresponding page in 
    // the ViewPager. 
    mViewPager.setCurrentItem(tab.getPosition()); 
} 

@Override 
public void onTabUnselected(ActionBar.Tab tab, 
     FragmentTransaction fragmentTransaction) { 
} 

@Override 
public void onTabReselected(ActionBar.Tab tab, 
     FragmentTransaction fragmentTransaction) { 
} 

/** 
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
* one of the sections/tabs/pages. 
*/ 
public class SectionsPagerAdapter extends FragmentPagerAdapter { 

    public SectionsPagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a DummySectionFragment (defined as a static inner class 
     // below) with the page number as its lone argument. 
     if (position == 0) 
     { 
      Fragment fragment = new FirstSectionFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(FirstSectionFragment.ARG_SECTION_NUMBER, position + 1); 
      fragment.setArguments(args); 
      return fragment; 
     } 
     else if (position == 1) 
     { 
      Fragment fragment = new SecondSectionFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(SecondSectionFragment.ARG_SECTION_NUMBER, position + 1); 
      fragment.setArguments(args); 
      return fragment; 
     } 
     else 
     { 
      Fragment fragment = new ThirdSectionFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(ThirdSectionFragment.ARG_SECTION_NUMBER, position + 1); 
      fragment.setArguments(args); 
      return fragment; 
     } 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     Locale l = Locale.getDefault(); 
     switch (position) { 
     case 0: 
      return getString(R.string.title_section1).toUpperCase(l); 
     case 1: 
      return getString(R.string.title_section2).toUpperCase(l); 
     case 2: 
      return getString(R.string.title_section3).toUpperCase(l); 
     } 
     return null; 
    } 
} 

public static class FirstSectionFragment extends Fragment { 

    public static final String ARG_SECTION_NUMBER = "section_number"; 

    public FirstSectionFragment() { 
    } 

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

     View rootView = inflater.inflate(R.layout.fragment_main_dummy, 
       container, false); 

     ListView dummyView = (ListView) rootView 
       .findViewById(R.id.listViewFirstFragment);   

     ListAdapter adapter = new SimpleAdapter(
       this.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 }); 

     dummyView.setAdapter(adapter); 

     return rootView; 
    } 
} 

private class GetContacts extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(MainActivity.this); 
     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; 
    } 

} 


public static class SecondSectionFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    public static final String ARG_SECTION_NUMBER = "section_number"; 

    public SecondSectionFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main_dummy, 
       container, false); 
     TextView dummyTextView = (TextView) rootView 
       .findViewById(R.id.section_label); 
     dummyTextView.setTextColor(Color.RED); 
     dummyTextView.setText("filter"); 
     return rootView; 
    } 
} 
public static class ThirdSectionFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    public static final String ARG_SECTION_NUMBER = "section_number"; 

    public ThirdSectionFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main_dummy, 
       container, false); 
     TextView dummyTextView = (TextView) rootView 
       .findViewById(R.id.section_label); 
     dummyTextView.setText("informatie"); 
     dummyTextView.setTextColor(Color.YELLOW); 
     return rootView; 
    } 
} 

} 

請告訴我,我怎麼能做到這一點的正確方法。

+2

請張貼錯誤日誌 –

+0

1.Failed轉換ECJ解析樹龍目文件 2.Keybinding發生了衝突放在裏面這一點。它們可能會干擾正常的加速器操作。 3.運行時沒有命令輸出:'am start -n com.companyName.appName/com.companyName.appName.MainActivity -a android.intent.action.MAIN -c – Maurice

+0

這是一個抱怨,2個「同胞」上下文具有相同的鍵綁定(不一定是問題),但同時都是活動的(這會產生衝突)。我檢查了教程,它看起來很好,所以我猜你已經在你的實現中添加了重複的上下文。 –

回答

2

得到它的工作:)改變了一些代碼。

public static class FirstSectionFragment extends Fragment { 

public static final String ARG_SECTION_NUMBER = "section_number"; 

public FirstSectionFragment() { 
} 

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

     View rootView = inflater.inflate(R.layout.fragment_main_dummy, 
       container, false); 

     return rootView; 
    } 
} 

的GetContacts類

@Override 
protected void onPostExecute(Void result) { 
    super.onPostExecute(result); 
    // Dismiss the progress dialog 
    if (pDialog.isShowing()) 
     pDialog.dismiss(); 
    /** 
    * Updating parsed JSON data into ListView 
    * */ 
    ListAdapter adapter = new SimpleAdapter(
      MainActivity.this, 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 }); 

    ListView dummyView = (ListView) 
      findViewById(R.id.list);  
    dummyView.setAdapter(adapter); 
}