2017-05-04 109 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

相关问题