2015-09-07 184 views
0

我需要從Second_frag啓動List_activity,但出現錯誤。 這裏是我的代碼將數據從一個片段發送到另一個片段

public class Second_frag extends android.support.v4.app.Fragment { 

String RSSFEEDURL = "http://feeds.feedburner.com/TwitterRssFeedXML?format=xml"; 
RSSFeed feed; 
String fileName; 

View myView; 

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


    fileName = "TDRSSFeed.td"; 

    File feedFile = getActivity().getBaseContext().getFileStreamPath(fileName); 

    ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (conMgr.getActiveNetworkInfo() == null) { 

     // No connectivity. Check if feed File exists 
     if (!feedFile.exists()) { 

      // No connectivity & Feed file doesn't exist: Show alert to exit 
      // & check for connectivity 
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
      builder.setMessage(
        "Unable to reach server, \nPlease check your connectivity.") 
        .setTitle("TD RSS Reader") 
        .setCancelable(false) 
        .setPositiveButton("Exit", 
          new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, 
                int id) { 
            getActivity().finish(); 
           } 
          }); 

      AlertDialog alert = builder.create(); 
      alert.show(); 
     } else { 

      // No connectivty and file exists: Read feed from the File 
      Toast.makeText(Second_frag.this.getActivity(), "No connectivity. Reading last update", Toast.LENGTH_LONG).show(); 
      feed = ReadFeed(fileName); 
      startLisActivity(feed); 
     } 

    } else { 

     // Connected - Start parsing 
     new AsyncLoadXMLFeed().execute(); 

    } 
    return myView; 


} 

private void startLisActivity(RSSFeed feed) { 

    Bundle bundle = new Bundle(); 
    bundle.putSerializable("feed", feed); 

    // launch List activity 
    Intent intent = new Intent(getActivity(), List_Activity.class); 

    intent.putExtras(bundle); 
    startActivity(intent); 

    // kill this activity 
    getActivity().finish(); 

} 

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

    @Override 
    protected Void doInBackground(Void... params) { 

     // Obtain feed 
     DOMParser myParser = new DOMParser(); 
     feed = myParser.parseXml(RSSFEEDURL); 
     if (feed != null && feed.getItemCount() > 0) 
      WriteFeed(feed); 
     return null; 

    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 

     startLisActivity(feed); 
    } 

} 

// Method to write the feed to the File 
private void WriteFeed(RSSFeed data) { 

    FileOutputStream fOut = null; 
    ObjectOutputStream osw = null; 

    try { 
     fOut = getActivity().openFileOutput(fileName, Context.MODE_PRIVATE); 
     osw = new ObjectOutputStream(fOut); 
     osw.writeObject(data); 
     osw.flush(); 
    } 

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

    finally { 
     try { 
      fOut.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

// Method to read the feed from the File 
private RSSFeed ReadFeed(String fName) { 

    FileInputStream fIn = null; 
    ObjectInputStream isr = null; 

    RSSFeed _feed = null; 
    File feedFile = getActivity().getBaseContext().getFileStreamPath(fileName); 
    if (!feedFile.exists()) 
     return null; 

    try { 
     fIn = getActivity().openFileInput(fName); 
     isr = new ObjectInputStream(fIn); 

     _feed = (RSSFeed) isr.readObject(); 
    } 

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

    finally { 
     try { 
      fIn.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    return _feed; 

} 



} 

list_activity

public class List_Activity extends Fragment { 

Application myApp; 
RSSFeed feed; 
ListView lv; 
CustomListAdapter adapter; 

View myView; 

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


    myApp = getActivity().getApplication(); 

// Get feed form the file 
    feed = (RSSFeed) getActivity().getIntent().getExtras().get("feed"); 

// Initialize the variables: 
    lv = (ListView) getView().findViewById(R.id.listView); 
    lv.setVerticalFadingEdgeEnabled(true); 

// Set an Adapter to the ListView 
    adapter = new CustomListAdapter(this); 
    lv.setAdapter(adapter); 

// Set on item click listener to the ListView 
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView arg0, View arg1, int arg2, 
           long arg3) { 
// actions to be performed when a list item clicked 
      int pos = arg2; 

      Bundle bundle = new Bundle(); 
      bundle.putSerializable("feed", feed); 
      Intent intent = new Intent(getActivity(), 
        DetailActivity.class); 
      intent.putExtras(bundle); 
      intent.putExtra("pos", pos); 
      startActivity(intent); 

     } 
    }); 
    return myView; 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    adapter.imageLoader.clearCache(); 
    adapter.notifyDataSetChanged(); 
} 

class CustomListAdapter extends BaseAdapter { 

    private LayoutInflater layoutInflater; 
    public ImageLoader imageLoader; 

    public CustomListAdapter(List_Activity activity) { 

     layoutInflater = (LayoutInflater) activity 
       .getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     imageLoader = new ImageLoader(activity.getActivity()); 
    } 

    @Override 
    public int getCount() { 

// Set the total list item count 
     return feed.getItemCount(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return position; 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

// Inflate the item layout and set the views 
     View listItem = convertView; 
     int pos = position; 
     if (listItem == null) { 
      listItem = layoutInflater.inflate(R.layout.list_item, null); 
     } 

    // Initialize the views in the layout 
     ImageView iv = (ImageView) listItem.findViewById(R.id.thumb); 
     TextView tvTitle = (TextView) listItem.findViewById(R.id.title); 
     TextView tvDate = (TextView) listItem.findViewById(R.id.date); 

// Set the views in the layout 
     imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv); 
     tvTitle.setText(feed.getItem(pos).getTitle()); 
     tvDate.setText(feed.getItem(pos).getDate()); 

     return listItem; 
    } 
} 
} 

logcat的

09-07 10:38:30.836 24588-24588/com.example.samsung.drawer E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: com.example.samsung.drawer, PID: 24588 
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.samsung.drawer/com.example.samsung.drawer.List_Activity}: java.lang.ClassCastException: com.example.samsung.drawer.List_Activity cannot be cast to android.app.Activity 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225) 
      at  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) 
      at android.app.ActivityThread.access$800(ActivityThread.java:139) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:149) 
      at android.app.ActivityThread.main(ActivityThread.java:5257) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:515) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
      at dalvik.system.NativeStart.main(Native Method) 
     Caused by: java.lang.ClassCastException: com.example.samsung.drawer.List_Activity cannot be cast to android.app.Activity 
      at android.app.Instrumentation.newActivity(Instrumentation.java:1061) 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216) 
            at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) 
            at android.app.ActivityThread.access$800(ActivityThread.java:139) 
            at  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 
            at android.os.Handler.dispatchMessage(Handler.java:102) 
            at android.os.Looper.loop(Looper.java:149) 
            at android.app.ActivityThread.main(ActivityThread.java:5257) 
            at java.lang.reflect.Method.invokeNative(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:515) 
            at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
            at dalvik.system.NativeStart.main(Native Method) 

RSSFeed.Java

import java.io.Serializable; 
import java.util.List; 
import java.util.Vector; 

public class RSSFeed implements Serializable { 

    private static final long serialVersionUID = 1L; 
    private int _itemcount = 0; 
    private List<RSSItem> _itemlist; 

    RSSFeed() { 
     _itemlist = new Vector<RSSItem>(0); 
    } 

    void addItem(RSSItem item) { 
     _itemlist.add(item); 
     _itemcount++; 
    } 

    public RSSItem getItem(int location) { 
     return _itemlist.get(location); 
    } 

    public int getItemCount() { 
     return _itemcount; 
    } 

} 

RSSItem.Java

package com.example.samsung.drawer; 

import java.io.Serializable; 

public class RSSItem implements Serializable { 

    private static final long serialVersionUID = 1L; 
    private String _title = null; 
    private String _description = null; 
    private String _date = null; 
    private String _image = null; 

    void setTitle(String title) { 
     _title = title; 
    } 

    void setDescription(String description) { 
     _description = description; 
    } 

    void setDate(String pubdate) { 
     _date = pubdate; 
    } 

    void setImage(String image) { 
     _image = image; 
    } 

    public String getTitle() { 
     return _title; 
    } 

    public String getDescription() { 
     return _description; 
    } 

    public String getDate() { 
     return _date; 
    } 

    public String getImage() { 
     return _image; 
    } 

} 

任何人都可以告訴我如何解決這個問題?

+0

您正在嘗試將片段投射到活動中......您無法這樣做。 –

+0

也使用一個視圖模式 – Raghunandan

回答

1

嘗試此方法

private void startLisActivity(RSSFeed feed) { 
    Bundle bundle = new Bundle(); 
    bundle.putSerializable("feed", feed); 
    List_Activity fragment = new List_Activity(); 
    fragment.setArguments(bundle); 
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
    FragmentTransaction transaction = fragmentManager.beginTransaction(); 
    transaction.replace(R.id.frame_container, fragment).commit(); 
    getActivity().finish(); 
} 

哪裏frame_container是你FrameLayout中要更換Fragment的ID。 我希望它有幫助!

+0

我在'feed =(RSSFeed)getActivity()。getIntent()。getExtras()。get(「feed」);'in'List_activity'處得到一個nullpointerexception錯誤... – NewGuy117

+0

什麼是RSSFeed? – Rajesh

+0

這是一個類,它包含所有已解析的項目 – NewGuy117

0

List_Activity是FragmentActivity,如果要替換當前片段你不能startActivity

啓動它,使用FragmentManager

3

List_Activity是一個片段。您不能使用

Intent intent = new Intent(getActivity(), List_Activity.class); 

intent.putExtras(bundle); 
startActivity(intent); 

您可以使用接口作爲託管活動的回調。然後將數據從活動傳遞給List_Activity Fragment。

而且你可能會想上下文傳遞給適配器custructor

http://developer.android.com/training/basics/fragments/communicating.html

+0

但是OP也可以使用'set setArguments(bundle)'方法傳遞數據,OP也需要使用FragmentManager將Activity添加到Activity,而不是以活動 –

+0

@ρяσѕρєяK開始。但它的碎片片段溝通,我建議可以與託管活動完成。 – Raghunandan

+0

我忘了提及片段需要附加到活動。 – Raghunandan

0

如果這兩個片段連接在一個活動,你可以在兩個片段之間通過活動communitcate。在每個片段中,您使用onActivityCreated函數來調用定義要轉移到其他片段的動作的Activity函數。 請參閱這裏[Replacing a fragment with another fragment inside activity group

+0

嘗試了這一點,但我得到一個錯誤logcat說'沒有找到id爲0x7f0e0073(com.example.samsung。抽屜:id/feed_list)的片段List_Activity {21f7eb38#2 id = 0x7f0e0073}' – NewGuy117

+0

我不清楚你的錯誤,但你可以用同樣的錯誤在Stackoverflow上搜索。請在提出問題之前嘗試搜索。 – MinhDev

+0

我搜索:[http://stackoverflow.com/questions/7508044/android-fragment-no-view-found-for-id] – MinhDev

-1

這不是直接在片段之間進行通信的良好做法,只能通過使用接口設計模式的活動在它們之間進行通信。以下是我之前撰寫的一篇文章,內容是link,其中介紹瞭如何實現它。

+1

誰已經投下了這個輝煌的答案?只是投票沒有意義,你必須給出一個理由! –

相關問題