【问题标题】:StackoverflowError while inflating Fragment膨胀片段时出现StackoverflowError
【发布时间】:2016-05-08 16:54:08
【问题描述】:

我在我使用的 Fragment 的 onCreateView() 方法中抛出了一些奇怪的 Stackoverflowerror。

正如您在这张图片中看到的,这就是它破坏的方法。第一个 TODO 应该是错误的来源。

我不知道那行有什么问题:

  view = inflater.inflate(R.layout.activity_chat, container, false); //it breaks here

我很高兴听到任何人的任何提示。

编辑:这是我在初始错误之后得到的另一个奇怪的错误报告:

编辑:Activity_chat.xml 的内容

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_bright"
    android:orientation="vertical">

    <fragment
        android:id="@+id/msg_list"
        android:name="com.example.f00.mobileapp.listener.TabFragment2"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        tools:layout="@layout/tab_fragment_2" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_green_dark">

        <Button
            android:id="@+id/send_btn"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="Send" />

        <EditText
            android:id="@+id/msg_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/send_btn"
            android:layout_toLeftOf="@+id/send_btn"/>
    </RelativeLayout>

</LinearLayout>

编辑:TabFragment2.java:

package com.example.f00.mobileapp.listener;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.f00.mobileapp.R;
import com.example.f00.mobileapp.activities.MainActivity;
import com.example.f00.mobileapp.application.Common;
import com.example.f00.mobileapp.fragments.EditContactDialog;
import com.example.f00.mobileapp.fragments.MessagesFragment;
import com.example.f00.mobileapp.utils.AsyncResponse;
import com.example.f00.mobileapp.utils.DataProvider;
import com.example.f00.mobileapp.utils.GcmUtil;
import com.example.f00.mobileapp.utils.Utils;

import java.io.IOException;
import java.util.Random;

// Chat chat real chat.

public class TabFragment2 extends Fragment implements MessagesFragment.OnFragmentInteractionListener,
    EditContactDialog.OnFragmentInteractionListener, View.OnClickListener {

    View view;

    private EditText msgEdit;
    private Button sendBtn;
    private String profileId;
    private String profileName;
    private String profileEmail;
    private GcmUtil gcmUtil;

    public Context context;

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

        view = inflater.inflate(R.layout.tab_fragment_2, container, false); //TODO this it where it breaks

//////////////
        profileId = getActivity().getIntent().getStringExtra(Common.PROFILE_ID);
        msgEdit = (EditText) getActivity().findViewById(R.id.msg_edit);
        sendBtn = (Button) getActivity().findViewById(R.id.send_btn);
        sendBtn.setOnClickListener(this);
        android.app.ActionBar actionBar =  getActivity().getActionBar(); //TODO
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);

        Cursor c = getActivity().getContentResolver().query(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), null, null, null, null);
        if (c.moveToFirst()) {
            profileName = c.getString(c.getColumnIndex(DataProvider.COL_NAME));
            profileEmail = c.getString(c.getColumnIndex(DataProvider.COL_EMAIL));
            actionBar.setTitle(profileName);
        }
        actionBar.setSubtitle("connecting ...");

        getActivity().registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
        gcmUtil = new GcmUtil(getActivity().getApplicationContext());

        ///////////
        return view;

    }

/*
    /**
     * The important piece of code is in onCreate() where we instantiate GcmUtil.
     * This triggers registration with GCM if it's not already done.
     * Recall that GcmUtil broadcasts the registration status which this activity
     * registers to listen.
     *
     * @param savedInstanceState
     */

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

        getActivity().setContentView(R.layout.activity_chat);


        getActivity().getIntent().getStringArrayExtra(Common.PROFILE_ID);
        profileId = getActivity().getIntent().getStringExtra(Common.PROFILE_ID);
        msgEdit = (EditText) getActivity().findViewById(R.id.msg_edit);
        sendBtn = (Button) getActivity().findViewById(R.id.send_btn);
        sendBtn.setOnClickListener(this);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);

        Cursor c = getContentResolver().query(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), null, null, null, null);
        if (c.moveToFirst()) {
            profileName = c.getString(c.getColumnIndex(DataProvider.COL_NAME));
            profileEmail = c.getString(c.getColumnIndex(DataProvider.COL_EMAIL));
            actionBar.setTitle(profileName);
        }
        actionBar.setSubtitle("connecting ...");

        registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
        gcmUtil = new GcmUtil(getApplicationContext());


    }*/

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.


        getActivity().getMenuInflater().inflate(R.menu.chat, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_edit:
                EditContactDialog dialog = new EditContactDialog();
                Bundle args = new Bundle();
                args.putString(Common.PROFILE_ID, profileId);
                args.putString(DataProvider.COL_NAME, profileName);
                dialog.setArguments(args);
                dialog.show(getActivity().getSupportFragmentManager(), "EditContactDialog");
                return true;

            case android.R.id.home:
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_btn:
                send(msgEdit.getText().toString());
                msgEdit.setText(null);
                break;
        }
    }

    @Override
    public void onEditContact(String name) {
        getActivity().getActionBar().setTitle(name); //TODO
    }

    @Override
    public String getProfileEmail() {
        return profileEmail;
    }

    /**
     * Finally to send a message we post the data to our server asynchronously.
     *
     * @param txt
     */
    private void send(final String txt) {

        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {

                    Utils sendMsg = new Utils(new AsyncResponse() {

                        @Override
                        public void asyncResponse(Object output, boolean status) {
                        }
                    });

                    //TODO
                    sendMsg.sendChatMessage(System.identityHashCode(new Random()), txt, getActivity().getApplicationContext());


      /*              ServerUtilities.send(txt, profileEmail);
                    ContentValues values = new ContentValues(2);
                    values.put(DataProvider.COL_TYPE, DataProvider.MessageType.OUTGOING.ordinal());
                    values.put(DataProvider.COL_MESSAGE, txt);
                    values.put(DataProvider.COL_RECEIVER_EMAIL, profileEmail);
                    values.put(DataProvider.COL_SENDER_EMAIL, Common.getPreferredEmail());
                    values.put(DataProvider.COL_ID, System.currentTimeMillis());
                    getContentResolver().insert(DataProvider.CONTENT_URI_MESSAGES, values);
*/
                } catch (IOException ex) {
                    msg = "Message could not be sent";
                }

                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                if (!TextUtils.isEmpty(msg)) {
                    Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                }
            }
        }.execute(null, null, null);
    }

    public void sendNewOrder(final String text) {
        //TODO
    }

    @Override
    public void onPause() {
        ContentValues values = new ContentValues(1);
        values.put(DataProvider.COL_COUNT, 0);
        getActivity().getContentResolver().update(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), values, null, null);
        super.onPause();
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(registrationStatusReceiver);
        gcmUtil.cleanup();
        super.onDestroy();
    }


    /**
     *
     */

    { }
    private BroadcastReceiver registrationStatusReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
                switch (intent.getIntExtra(Common.EXTRA_STATUS, 100)) {
                    case Common.STATUS_SUCCESS:
                       getActivity().getActionBar().setSubtitle("online");
                        break;

                    case Common.STATUS_FAILED:
                        getActivity().getActionBar().setSubtitle("offline");
                        break;
                }
            }
        }
    };

}

【问题讨论】:

  • 您可能应该添加代码而不是图像,以便其他人也可以尝试使用那段代码
  • activity_chat.xml的内容是什么?
  • 您是否尝试按 Sync project with gradle files 按钮?
  • TabFragment2 一遍又一遍地膨胀自己
  • com.example.f00.mobileapp.listener.TabFragment2 是否包含 activity_chat.xml 布局的实例?看起来你在布局和片段之间得到了循环依赖。

标签: java android android-fragments fragment


【解决方案1】:

我认为您在 onCreateView 中做了很多事情 - 我的建议是您将其余代码移动到 onActivityCreated(Bundle savedInstanceState) 中。把onCreateView改成:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {      
        View rootView = inflater.inflate(R.layout.activity_chat, container, false);     
        return rootView;
    }

然后您可以将其余代码移至onActivityCreated。该方法在创建宿主活动时在onCreateView() 方法之后调用。 已创建活动和片段实例以及活动的视图层次结构。此时可以通过findViewById()方法访问视图。

【讨论】:

  • 酷,我很高兴它有帮助。请接受答案,以便将您的问题标记为已回答。享受吧。
猜你喜欢
  • 1970-01-01
  • 2011-09-19
  • 2013-05-28
  • 2016-07-20
  • 1970-01-01
相关资源
最近更新 更多