2017-05-04 142 views
0

我需要迭代數組並將每個數組項從活動傳遞到片段;但與我的代碼,我傳遞只從最後一項活動片段。問題將數據從活動傳遞到片段

我希望你能幫助我!

我向你展示我的代碼!

活動:

try { 
        JSONObject contacts = new JSONObject(jsonStr); 
        JSONArray jsonArray = contacts.getJSONArray("pdfs"); 
        // looping through All Contacts 
        for (int i = 0; i < jsonArray.length(); i++) { 
         JSONObject c = jsonArray.getJSONObject(i); 

         // title_array.add(c.getString("title").toString()); 
         url_pdf=c.getString("url_pdf"); 



         SixFragment fragment = new SixFragment(); 
         fragment.setName(url_pdf); 

         /* Bundle bundle = new Bundle(); 
         bundle.putString("user", url_pdf); 
         SixFragment fragmentt = new SixFragment(); 
         fragmentt.setArguments(bundle); 
         getSupportFragmentManager() 
           .beginTransaction() 
           .replace(R.id.ah, fragmentt) 
           .commit(); 
*/ 

        } 

        System.out.println("PDFSSSSSSS"+url_pdf); 

       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG).show(); 
         } 
        }); 

       } 

片斷:

public class SixFragment extends android.support.v4.app.Fragment { 
String url_pdf=""; 
    SimpleAdapter adapter; 
    ListView list; 
    ArrayList<HashMap<String, String>> pdfList; 
    HashMap<String, String> pdf; 
    String data=""; 
    String arg=""; 
    static String azzzz=""; 
    public SixFragment() { 
     // Required empty public constructor 
    } 
    public void setName(String string){ 
     azzzz = string; 
    } 

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




    } 

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


     View view = inflater.inflate(R.layout.fragment_six, container, false); 


     /*Bundle bundle=getArguments(); 

     String pala=bundle.getString("user");*/ 

     pdfList = new ArrayList<>(); 

     HashMap<String, String> pdf = new HashMap<>(); 

     // adding each child node to HashMap key => value 
     pdf.put("id", azzzz); 


     // adding contact to contact list 
     pdfList.add(pdf); 

     for (int i = 0; i < pdfList.size(); i++) { 
      System.out.println("CONTAT:"+pdfList.size()); 
     } 
     list = (ListView) view.findViewById(R.id.listView); 

     ListAdapter adapter = new SimpleAdapter(
       getContext(), pdfList, 
       R.layout.list_item, new String[]{"id"}, new int[]{R.id.name}); 



     list.setAdapter(adapter); 

     return view; 

    } 

SIX_FRAGMENT.XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/container_frame_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="info.androidhive.materialtabs.fragments.SixFragment"> 



    <fragment 
     android:id="@+id/ah" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1"/> 

    <ListView 
     android:layout_width="match_parent" 
     android:id="@+id/listView" 
     android:layout_height="wrap_content"/> 


</RelativeLayout> 
+1

你應該讓你的數據在一個數組,然後創建您的片段,並通過陣列中的片段參數,所以Fragment可以在創建時獲得它們。或者你創建你的Fragment,獲取數組中的數據(在Activity中),然後用數組更新Fragment(通過在你的Fragment上調用「update」方法) 但是你現在正在做的是創建您的「for」每個循環中的碎片! – Eselfar

+0

@Eselfar你能舉個例子嗎? – Markus

+0

我在下面添加了一個例子。 – Eselfar

回答

0

要設置url_pdf再次片段一遍又一遍,但url_pdf始終只是抱着1值。您應該創建一個數組或JsonObject並將其作爲Extra來傳遞。

活動;

try { 
       JSONObject contacts = new JSONObject(jsonStr); 
       JSONArray jsonArray = contacts.getJSONArray("pdfs"); 

       Bundle bundle = new Bundle(); 
       bundle.putString("user", list); 
       SixFragment fragmentt = new SixFragment(); 
       fragmentt.setArguments(bundle); 
       getSupportFragmentManager() 
          .beginTransaction() 
          .replace(R.id.ah, fragmentt) 
          .commit(); 


      } catch (final JSONException e) { 
       Log.e(TAG, "Json parsing error: " + e.getMessage()); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Json parsing error: " + e.getMessage(), 
           Toast.LENGTH_LONG).show(); 
        } 
       }); 

      } 

片段:

public class SixFragment extends android.support.v4.app.Fragment { 
    ArrayList<String> list; 

    ... 
    public SixFragment getInstance(JSONArray json) { 
     Bunble b = new Bundle(); 
     b.putExtra("JSON",json); 
     SixFragment f = new SixFragment(); 
     f.setArguments(b); 
     return f; 
    } 


    @Override 
    public void onCreate(@Nullable Bundle savedInstanceState) { 
     savedInstance = savedInstanceState != null; 
     super.onCreate(savedInstanceState); 
     JSONArray jsonArray = getArguments.get("JSON"); 
     // looping through All Contacts 
     for (int i = 0; i < jsonArray.length(); i++) { 
      JSONObject c = jsonArray.getJSONObject(i); 
      list.add(c.getString("url_pdf")); 
      System.out.println("PDFSSSSSSS"+url_pdf); 
     } 
} 
+0

應該使用處理後的數據設置片段,因爲在處理片段中的數據時沒有值。 – Eselfar

+0

你是對的,只是過程JSON和傳遞你的對象的片段 –

+0

@Eselfar你的答案不工作.... – Markus

0

注:您可以使用GSON,而不是手動解析JSON。

在活動

try { 
    // Instantiate a new ArrayList to store the urls 
    ArrayList<String> urls = new ArrayList<>(); 

    JSONObject contacts = new JSONObject(jsonStr); 
    JSONArray jsonArray = contacts.getJSONArray("pdfs"); 
    // looping through All Contacts 
    for (int i = 0; i < jsonArray.length(); i++) { 
     JSONObject c = jsonArray.getJSONObject(i); 
     String url_pdf = c.getString("url_pdf"); 

     // add the url to the array of 'url_pdf' 
     urls.add(url_pdf); 

     // Display each url retrieved (not necessary) 
     System.out.println("PDFSSSSSSS" + url_pdf); 
    } 

    SixFragment fragment = SixFragment.newInstance(urls); 
    getSupportFragmentManager().beginTransaction() 
      // Replace the current Fragment. Use the Fragment class name as tag (can 
      // be useful to find the fragment later) 
      .replace(R.id.ah, fragment, fragment.getClass().getSimpleName()) 
      .commit(); 

} catch (final JSONException e) { 
    Log.e(TAG, "Json parsing error: " + e.getMessage()); 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      Toast.makeText(getApplicationContext(), 
        "Json parsing error: " + e.getMessage(), 
        Toast.LENGTH_LONG).show(); 
     } 
    }); 
} 

在SixFragment

private static final String ARGS_URLS = "bundle_urls"; 
private ArrayList<String> mUrls; 
private ArrayAdapter<String> mAdapter; 

public SixFragment() { 
    // Required empty public constructor 
} 

/** 
* @param urls ArrayList of url_pdf 
* @return A new instance of the {@link SixFragment} 
*/ 
public static SixFragment newInstance(ArrayList<String> urls) { 

    Bundle args = new Bundle(); 
    // put the array into the fragment arguments bundle 
    args.putStringArrayList(ARGS_URLS, urls); 

    SixFragment fragment = new SixFragment(); 
    fragment.setArguments(args); 

    return fragment; 
} 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // Retrieve data from the Fragment's arguments 
    mUrls = getArguments().getStringArrayList(ARGS_URLS); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    View view = inflater.inflate(R.layout.fragment_six, container, false); 
    ListView listView = (ListView) view.findViewById(R.id.listView); 

    // Use an ArrayAdapter instead of the SimpleAdapter as it automatically manage a List 
    mAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, mUrls); 
    listView.setAdapter(mAdapter); 

    return view; 
} 
+0

我得到這個錯誤「java.lang.NullPointerException:嘗試調用虛擬方法'java.util.ArrayList android.os.Bundle.getStringArrayList(java.lang.String)'對空對象引用 at info.androidhive.materialtabs.fragments.SixFragment.onCreate(SixFragment.java:58)「 – Markus

+0

你能幫助我嗎? – Markus

+0

你忘了設置片段的參數,爲什麼你的bundle爲null。在我的例子中,在這個活動中,創建SixFragment:SixFragment fragment = SixFragment.newInstance(urls)。如果你閱讀newInstance(...)的代碼,我創建了一個包含url列表的Bundle,並將其設置爲Fragment的參數(fragment.setArguments(args))。 – Eselfar