Android 未显示片段的UI

Android 未显示片段的UI,android,android-fragments,Android,Android Fragments,我想从我的活动中调用一个片段。正在调用onCreate和onCreateView方法。但是,没有显示片段的UI。我在logcat中也没有看到任何错误 基本上这就是我想做的。单击activity.xml中的imagebutton后,我调用fetchNotifications()方法,该方法依次调用asynctask来执行一些工作,然后调用我的片段。在我的片段中,我创建了一个包含多个文本视图的动态listview 这是我的密码: activity_home_screen.xml(我的活动布局):

我想从我的活动中调用一个片段。正在调用onCreate和onCreateView方法。但是,没有显示片段的UI。我在logcat中也没有看到任何错误

基本上这就是我想做的。单击activity.xml中的imagebutton后,我调用fetchNotifications()方法,该方法依次调用asynctask来执行一些工作,然后调用我的片段。在我的片段中,我创建了一个包含多个文本视图的动态listview

这是我的密码:

activity_home_screen.xml(我的活动布局):


HomeScreen.java(我的活动类):

公共类主屏幕扩展了碎片活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u主屏幕);
}
//从按钮onClick调用的方法
公共无效获取通知(查看){
新建FetchNotifications()。执行(“http://x.x.x.x:9000/Android/homescreen/ruby");        
}
私有类GetNotifications扩展了AsyncTask{//此处的一些代码}
私有类FetchNotifications扩展异步任务{
碎片管理器fm;
@凌驾
受保护的字符串doInBackground(字符串…参数){
试一试{
URL通知=新URL(参数[0]);
//JSONObject notificationsJSON=新的JSONObject(getResponse(notifications).toString());
JSONObject notificationsJSON=新的JSONObject(globals.JSONS.NOTIFICATIONS);
if(notificationsJSON!=null){
Globals Globals=Globals.getInstance();
globals.setReplyString(notificationsJSON.getJSONArray(“通知”).toString());
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.add(新的显示通知(),“通知”);
ft.commit();
}
}捕获(格式错误){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回null;
}
}
公共StringBuilder getResponse(URL){//some code here}
}
activity_display_notifications.xml(我的片段布局):


single_notification.xml(包含将添加到listview的textview):


最后是我的片段类(DisplayNotifications.java):

package com.example.projectswipe;
导入全局。全局;
导入java.util.ArrayList;
导入org.json.JSONArray;
导入org.json.JSONException;
导入android.content.Context;
导入android.os.Bundle;
导入android.support.v4.app.Fragment;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ArrayAdapter;
导入android.widget.ListView;
导入android.widget.TextView;
公共类DisplayNotifications扩展片段{
全球的;
JSONArray notificationsArray;
ArrayList通知=新建ArrayList();
列表视图l;
公共显示通知(){
//必需的空公共构造函数
}
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
Log.d(“测试”,“onCreate>>>>>”;
super.onCreate(savedInstanceState);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图=充气机。充气(R.layout.activity\u display\u通知,容器,false);
Log.d(“测试”,“onCreateView>>>>”;
返回视图;
}
@凌驾
已创建ActivityState上的公共无效(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
试一试{
global=Globals.getInstance();
notificationsArray=newjsonarray(global.getReplyString());
System.out.println(“>>>>>>>>”+通知数组);

对于(int i=0;i首先,您的主布局不包括片段的容器(通常是FrameLayout),并且您的FragmentTransaction没有指定必须附加片段视图的位置
不使用ContainerWebID作为参数的方法是为没有用户界面的片段保留的,这就是为什么您看不到任何东西

其次,您不能像这里这样从后台线程调用FragmentManager。它必须始终在UI线程上完成。如果使用AsyncTask,则意味着FragmentTransaction必须在
onPostExecute()
中完成,而不是在
doInBackground()中完成
。但是,在尝试提交片段事务之前,请确保您的活动已启动,否则您将获得非法状态异常。执行此操作的常用方法是取消
onStop()
中的异步任务,这样
onPostExecute()
将不会在
onStop()
之后调用

代码中的其他潜在问题:

  • 切勿将ListView的高度设置为包装内容。这可能会导致故障和性能问题。请改用匹配父级、固定高度或权重
  • 传递片段将在其Arguments Bundle中显示的数据,或使片段在显示时加载其自己的数据,而不是将数据加载到片段稍后将访问的某个全局变量中。片段不能依赖这样一个事实,即全局变量在启动时将被正确设置,因为系统可能会终止当应用程序不可见时,请随时将其恢复。当应用程序恢复时,活动、片段及其参数包也将恢复,但全局变量不会恢复<
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="46dp"
            android:src="@drawable/read_msg"
            android:onClick="fetchNotifications"/>
    
    </RelativeLayout>
    
    public class HomeScreen extends FragmentActivity{
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home_screen);
        }
    
        //Method called from button onClick
        public void fetchNotifications(View view){
            new FetchNotifications().execute("http://x.x.x.x:9000/Android/homescreen/ruby");        
        }
    
        private class GetNotifications extends AsyncTask<String, String, String>{//some code here}
    
        private class FetchNotifications extends AsyncTask<String, String, String>{
    
            FragmentManager fm;
    
            @Override
            protected String doInBackground(String... params) {
                try {
                    URL notifications = new URL(params[0]);
                    //JSONObject notificationsJSON = new JSONObject(getResponse(notifications).toString());
                    JSONObject notificationsJSON = new JSONObject(globals.JSONS.NOTIFICATIONS);
    
                    if(notificationsJSON!=null){
                        Globals globals = Globals.getInstance();
                        globals.setReplyString(notificationsJSON.getJSONArray("notification").toString());
                        FragmentManager fm = getSupportFragmentManager();
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        ft.add(new DisplayNotifications(), "Notification");
                        ft.commit();
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
        }
    
        public StringBuilder getResponse(URL url){//some code here}
    
    
    }
    
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.buildingcustomadapter.MainActivity"
        tools:ignore="MergeRootFrame">
    
        <ListView
            android:id="@+id/notifications_listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    
    </FrameLayout>
    
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <TextView
            android:id="@+id/notification_TextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="Small Text"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    
    </RelativeLayout>
    
    package com.example.projectswipe;
    
    import globals.Globals;
    
    import java.util.ArrayList;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    
    import android.content.Context;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
    
    public class DisplayNotifications extends Fragment {
    
        Globals global;
        JSONArray notificationsArray;
        ArrayList<String> notification = new ArrayList<String>();
        ListView l;
    
        public DisplayNotifications() {
            // Required empty public constructor
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            Log.d("Test", "onCreate >>>>>>>>");
            super.onCreate(savedInstanceState);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.activity_display_notifications, container, false);
            Log.d("Test", "onCreateView >>>>>>>>");
            return view;
        }
    
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            try {
                global = Globals.getInstance();
                notificationsArray = new JSONArray(global.getReplyString());
                System.out.println(">>>>>>>>>>"+notificationsArray);
    
                for(int i=0; i<notificationsArray.length(); i++){
                    notification.add(notificationsArray.getJSONObject(i).getString("msg"));             
                }
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
            l = (ListView) getView().findViewById(R.id.notifications_listView);     
            NotificationsAdapter adapter = new NotificationsAdapter(getActivity(), notification);
            Log.d("Test", "onActivityCreated >>>>>>>>");
            l.setAdapter(adapter);
            //l.setOnItemClickListener(this);
            //l.setEmptyView(getActivity().findViewById(R.id.emptyProductDeals));
        }
    
    }
    
    class NotificationsAdapter extends ArrayAdapter<String>{
    
        Context contex;
        ArrayList<String> notifications;
    
        /*
         * Create a constructor which calls super(). In super(), we pass context, the singlerow.xml file, and the datasource
         */
        NotificationsAdapter(Context c, ArrayList<String> notifications){
            super(c, R.layout.single_notification, notifications);
            this.contex = c;
            this.notifications = notifications;
        }
    
        class MyViewHolder{
            TextView notification;
    
            MyViewHolder(View v){
                notification = (TextView) v.findViewById(R.id.notification_TextView);
            }
    
        }
    
        public View getView(int position, View convertView, ViewGroup parent){
    
            View root = convertView;
            MyViewHolder holder = null;
    
            if(root==null)
            {
                LayoutInflater inflater = (LayoutInflater) contex.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                root = inflater.inflate(R.layout.single_notification, parent, false);
                holder = new MyViewHolder(root);
                root.setTag(holder);
            }
            else{
                holder = (MyViewHolder) root.getTag();
            }
    
            holder.notification.setText(notifications.get(position));
    
            return root;
    
        }
    
    }