2017-04-15 29 views
2

我不知道如何在從另一個片段接收到值時在第二個片段的textview中設置。我在第二個片段中收到的數據是StringList的「值」對象,但我現在不知道如何爲它設置數據。如何設置從另一個片段接收到的片段的textview值?

的StringList類:

public class StringList { 

    public String authorName; 
    public String headline; 
    public String publishedTime; 
    public String newsDetail; 

} 

MainActivity:

//only useful code pasted below for tranfering thre value from fragment to another fragment and i have implemented the TransferValue to the mainActivity 

     public void sendValue(StringList value, int positionValue) { 

      FragmentTransaction transaction = frag.beginTransaction(); 
      BusinessDetail businessDetail = new BusinessDetail(); 
      businessDetail.receiveValue(value, positionValue); 
      transaction.replace(R.id.content_frame, businessDetail); 
      transaction.commit(); 

     } 

片段1:

public class Business extends Fragment { 

     public List<StringList> businessNews = new ArrayList<>(); 

     TransferValue SendData;//here 

     private RecyclerView recyclerView; 
     public Business() { 

     } 

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

      View view = inflater.inflate(R.layout.fragment_business, container, false); 
      recyclerView = (RecyclerView) view.findViewById(R.id.business_recycler_view); 

      FetchLists f = new FetchLists(); 
      f.execute(10, 0); 
      return view; 
     } 

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

     @Override 
     public void onAttach(Context context) { 
      super.onAttach(context); 
    //here 
      try { 
       SendData = (TransferValue) context; 
      } catch (ClassCastException e) { 
       Log.d("ashu", "implement the methods"); 
       throw new ClassCastException("implemented the methods"); 
      } 
     } 

//here 
     public interface TransferValue { 

      public void sendValue(StringList value, int positionValue); 

     } 

     public class FetchLists extends AsyncTask<Integer, Void, List<StringList>> { 

      @Override 
      protected List<StringList> doInBackground(Integer... params) { 

       int count = params[0]; 
       int offset = params[1]; 
    //api key changed 
       String urlString = "https://newspi.og/v1/article?source=bloomerg&sortBy=tp&apiKey=5fdfd54f4aba5a5fdfvdf476ff528a8"; 
       urlString = urlString + "&count=" + count + "&offset=" + offset; 

       try { 
        URL url = new URL(urlString); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
        connection.setRequestMethod("GET"); 
        InputStream stream = connection.getInputStream(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 
        String line = reader.readLine(); 
        String response = ""; 
        while (line != null) { 
         response += line; 
         line = reader.readLine(); 
        } 

        JSONObject object = new JSONObject(response); 
        JSONArray emailLists = object.getJSONArray("articles"); 

        for (int i = 0; i < emailLists.length(); i++) { 
         JSONObject listData = (JSONObject) emailLists.get(i); 

         StringList stringList = new StringList(); 
         stringList.authorName = listData.getString("author"); 
         stringList.headline = listData.getString("title"); 
         stringList.publishedTime = listData.getString("publishedAt"); 
         stringList.newsDetail = listData.getString("description"); 

         businessNews.add(stringList); 
        } 

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       return businessNews; 
      } 

      @Override 
      protected void onPostExecute(List<StringList> result) { 
       super.onPostExecute(result); 

       recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 
       BusinessAdapter adapter = new BusinessAdapter(Business.this, result); 
       recyclerView.setAdapter(adapter); 

      } 
     } 

     public class BusinessAdapter extends RecyclerView.Adapter<BusinessHolder> { 

      int prevposition = 0; 
      private List<StringList> c; 

      public BusinessAdapter(Business context, List<StringList> result) { 
       c = context.businessNews; 

      } 

      @Override 
      public BusinessHolder onCreateViewHolder(ViewGroup parent, int viewType) { 

       Context context = parent.getContext(); 
       LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       View view = inflater.inflate(R.layout.layout_news, parent, false); 

       return new BusinessHolder(view); 
      } 

      @Override 
      public void onBindViewHolder(BusinessHolder holder, int position) { 

       StringList m = c.get(position); 
       holder.bindListName(m, position); 

      @Override 
      public int getItemCount() { 
       return c.size(); 
      } 
     } 

     public class BusinessHolder extends RecyclerView.ViewHolder { 

      public TextView headlineTextview; 
      public TextView authorTextview; 
      public TextView timeTextview; 

      public BusinessHolder(View itemView) { 
       super(itemView); 

       headlineTextview = (TextView) itemView.findViewById(R.id.id_headline); 
       authorTextview = (TextView) itemView.findViewById(R.id.id_author); 
       timeTextview = (TextView) itemView.findViewById(R.id.id_time); 

      } 

      public void bindListName(final StringList stringList, final int position) { 

       headlineTextview.setText(stringList.headline); 
       authorTextview.setText(stringList.authorName); 
       timeTextview.setText(stringList.publishedTime); 

       itemView.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View view) { 

         BusinessDetail s = new BusinessDetail(); 
         FragmentTransaction transaction = getFragmentManager().beginTransaction(); 
         transaction.replace(R.id.content_frame, s); 
         transaction.addToBackStack(null); 
         transaction.commit(); 
        } });}}}} 

片段2:

public class BusinessDetail extends Fragment { 

    Bundle bundle; 
    private TextView headlineSecond; 
    private TextView authorSecond; 
    private TextView detailsSecond; 
    private List<StringList> s; 

    public BusinessDetail() { 
    } 

    public void receiveValue(StringList value, int positionValue) { 

     bundle = new Bundle(); 
     bundle.putString("news", value.authorName); 
     } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_business_detail, container, false); 

     headlineSecond = (TextView) view.findViewById(R.id.id_headline_second); 
     authorSecond = (TextView) view.findViewById(R.id.id_author_second); 
     detailsSecond = (TextView) view.findViewById(R.id.id_details_second); 

// I want to set the values received to the textview here 

     return view;}} 

回答

2

可以使用Parcelable FR發送任何自定義類數據的ArrayList om一個活動/片段到下一個活動/片段。

在之前的片段中,使用putParcelableArrayList方法在數據包中添加數據。例如,

bundle.putParcelableArrayList("KEY_NAME",arrayName); 

在下一個frgament中使用getParcelableArrayList方法獲取onCreate中的數據。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if (getArguments() != null) { 
     ArrayList<Item> itemArray = getArguments().getParcelableArrayList("KEY_NAME"); 
    } 
} 

而最主要的是將您的StringList類更改爲Parcelable。對於Parcelable類例如點擊以下鏈接..

Parcelable Class

+0

謝謝!但我不想這樣做,因爲我通過改變一些代碼重新開始...... plz根據上述條件給出答案。再次感謝! –

+0

@avadra_kedra對於上述情況,parcelable對pojo(自定義類)的數據列表來說是完美的。並且對於單個對象附加,所有值都是單獨的,並在另一個片段中獲得。我希望這會幫助你.. –

3

在實例化片段之後,請考慮使用newInstance方法將值傳遞給片段,因爲調用receiveValue方法不是一種好的做法。您應該將您的對象定義爲Parcelable並通過newInstance方法將其傳遞給新片段。

但是,如果您通過調用方法receiveValue收到值,則不需要使用Bundle。當您要將FragmentActivity的值傳遞給另一個Fragment時,使用Bundle。爲了保存數值,您可以定義全球像您一樣使用TextView s的變量。例如:

Bundle bundle; 
StringList mStringList; 
private TextView headlineSecond; 
private TextView authorSecond; 
private TextView detailsSecond; 
private List<StringList> s; 

public BusinessDetail() { 
} 

public void receiveValue(StringList value, int positionValue) { 
    mStringList = value; 
} 

P.S:但是,以供將來參考,您可以通過調用getString(String key)檢索字符串從Bundle值。在你的情況下,它會像:

String value = bundle.getString("news"); 
yourTextView.setText(value); 

也可以刪除這些行,他們不會在你目前的片段做任何事情,除非你想開始一個新的Fragment

BusinessDetail detail = new BusinessDetail(); 
detail.setArguments(bundle); 

爲了詳細說明片段與例子和代碼片斷通信可點擊這裏查看: http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html

+0

是的!當然,我已經將片段的值傳遞給了其中我正在獲取值對象的其他片段......但是,如何將此值設置爲textview字段?感謝您的考慮 –

+0

我沒有看到任何與傳遞值或啓動片段相關的代碼。我更新我的答案以包含有關此問題的更多詳細信息。 –

+0

我得到一個空指針異常「String value = bundle.getString(」news「);」 ? –

相關問題