如何从主Activity {NPE}中的viewpager检索TextView []的文本

时间:2014-08-14 03:01:44

标签: java android android-fragments android-viewpager

我在片段中有TextView[]个对象和String[]字段。我总共有5个片段,全部由ViewPager处理。我想通过点击父活动的菜单来检索每个片段中显示的几乎所有字符串(并在以后将其保存到文本文件中)。

无论如何,这里有一些代码:

这是在主Activity中(仅用于从第一个片段检索数据):

private Intent createShareIntent() {

    DisplayFragment displayFragment = (DisplayFragment) mAdapter.getItem(2);

    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    // Add data to the intent, the receiving app will decide what to do
    // with it.
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Display Info");
    shareIntent.putExtra(Intent.EXTRA_TEXT, displayFragment.retrieveContent());

    return shareIntent;
}

NullPointerException来自DisplayFragment中的此方法:

public class DisplayFragment extends Fragment {
static String devDensity, devDensityCategory, devDpi, devXDpi, devYDpi,
        devPxWidth, devPxHeight, devRefreshRate, devOrientation;
static TextView tvDispDensity, tvDensityCategory, tvDispDpi, tvDispXDpi,
        tvDispYDpi, tvDispPxWidth, tvDispPxHeight, tvDispRefreshRate,
        tvOrientation;

DisplayMetrics metrics;

// For sharing information via e-mail/SMS
/**
 * Final Content of display info
 */
String displayInfoContent;

/**
 * All textviews used in for-loop to getText()
 */
private TextView[] textViews;

private String[] strings;

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

    View rootView = inflater.inflate(R.layout.display, container, false);

    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    metrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay()
            .getMetrics(metrics);

    devDensity = String.valueOf(metrics.density);
    devDpi = String.valueOf(metrics.densityDpi);
    devXDpi = String.valueOf(metrics.xdpi);
    devYDpi = String.valueOf(metrics.ydpi);
    devPxWidth = String.valueOf(metrics.widthPixels);
    devPxHeight = String.valueOf(metrics.heightPixels);
    devRefreshRate = String.valueOf(getActivity().getWindowManager()
            .getDefaultDisplay().getRefreshRate());

    translate();

    // Displays
    tvDispDensity = (TextView) getView()
            .findViewById(R.id.tvDisplayDensity);
    tvDispDensity.setText(devDensity);

    tvDensityCategory = (TextView) getView().findViewById(
            R.id.tvDensityCategory);
    tvDensityCategory.setText(devDensityCategory);

    tvDispDpi = (TextView) getView().findViewById(R.id.tvDisplayDpi);
    tvDispDpi.setText(devDpi);

    tvDispXDpi = (TextView) getView().findViewById(R.id.tvDisplayXDpi);
    tvDispXDpi.setText(devXDpi);

    tvDispYDpi = (TextView) getView().findViewById(R.id.tvDisplayYDpi);
    tvDispYDpi.setText(devYDpi);

    tvDispPxWidth = (TextView) getView()
            .findViewById(R.id.tvDisplayWidthPx);
    tvDispPxWidth.setText(devPxWidth + " px");

    tvDispPxHeight = (TextView) getView().findViewById(
            R.id.tvDisplayHeightPx);
    tvDispPxHeight.setText(devPxHeight + " px");

    tvDispRefreshRate = (TextView) getView().findViewById(
            R.id.tvDisplayRefreshRate);
    tvDispRefreshRate.setText(devRefreshRate + " Hz");

    tvOrientation = (TextView) getView().findViewById(
            R.id.tvDisplayOrientation);
    tvOrientation.setText(devOrientation);
    //
    // #################################
    textViews = new TextView[]{tvDispDensity, tvDensityCategory, tvDispDpi, tvDispXDpi,
            tvDispYDpi, tvDispPxWidth, tvDispPxHeight, tvDispRefreshRate,
            tvOrientation};

    strings = new String[]{devDensity, devDensityCategory, devDpi, devXDpi, devYDpi,
            devPxWidth, devPxHeight, devRefreshRate, devOrientation};
}

private void translate() {
    switch (metrics.densityDpi) {
        case DisplayMetrics.DENSITY_LOW:
            devDensityCategory = "Low (120 dpi)";
            break;
        case DisplayMetrics.DENSITY_MEDIUM:
            devDensityCategory = "Medium (160 dpi)";
            break;
        case DisplayMetrics.DENSITY_HIGH:
            devDensityCategory = "High (240 dpi)";
            break;
        case DisplayMetrics.DENSITY_XHIGH:
            devDensityCategory = "XHigh (320 dpi)";
            break;
        case DisplayMetrics.DENSITY_XXHIGH:
            devDensityCategory = "XXHigh (480 dpi)";
            break;
        case DisplayMetrics.DENSITY_XXXHIGH:
            devDensityCategory = "XXXHigh (640 dpi)";
            break;
        case DisplayMetrics.DENSITY_TV:
            devDensityCategory = "TV (213 dpi)";
            break;
        case DisplayMetrics.DENSITY_400:
            devDensityCategory = "Intermediate (400 dpi)";
            break;

        default:
            devDensityCategory = "Unknown";
            break;
    }

    switch (getActivity().getWindowManager().getDefaultDisplay()
            .getRotation()) {
        case Surface.ROTATION_0:
            devOrientation = "0°";
            break;

        case Surface.ROTATION_90:
            devOrientation = "90°";
            break;

        case Surface.ROTATION_180:
            devOrientation = "180°";
            break;

        case Surface.ROTATION_270:
            devOrientation = "270°";
            break;

        default:
            devOrientation = "Unknown";
            break;
    }

}

public String retrieveContent() {
    String content = "";
    for (int i = 0; i < textViews.length; i++) {
        content += (textViews[i].getText() + " = " + strings[i] + "\n");
    }
    return content;
}

片段在屏幕外时是否初始化了数组?如果没有,我怎么能把它拉掉呢?

logcat的:

java.lang.NullPointerException
        at my.package.name.fragments.DisplayFragment.retrieveContent(DisplayFragment.java:170)

这是我for循环中的content += (textViews[i].getText() + " = " + strings[i] + "\n");

非常感谢任何见解,感谢您阅读。

此致 马特

2 个答案:

答案 0 :(得分:0)

  

片段在屏幕外时是否初始化了数组?如果没有,我怎么能把它拉掉呢?

问题是当片段在屏幕外时,片段本身可能根本就没有创建。默认情况下,视图寻呼机仅初始化当前页面的上一页和下一页。例如,如果您在第1页上处于活动状态,则默认情况下仅初始化第2页。如果您在第三页,则只创建第2页,第3页和第4页。

除此之外呢?你可以简单地将屏幕外页面限制设置为4,这样就可以确保它在当前页面的下一页或上一页保留4页(在你的情况下,所有5个片段将一次创建)

urViewPager.setOffscreenPageLimit(4);
在urViewPager初始化之后,将该代码放在活动的OnCreate中。 希望这会有所帮助,欢呼。

答案 1 :(得分:0)

我找到了罪魁祸首。显然TextView []没有正确初始化。考虑到在OnActivityCreated()中使用它,我直接在fragment的retrieveInfo()方法中初始化了TextView []和String []。还将textview字段设为静态变量,并且像魅力一样工作

public String retrieveContent() {
textViews = new TextView[]{tvDispDensity, tvDensityCategory, tvDispDpi, tvDispXDpi,
        tvDispYDpi, tvDispPxWidth, tvDispPxHeight, tvDispRefreshRate,
        tvOrientation};

strings = new String[]{devDensity, devDensityCategory, devDpi, devXDpi, devYDpi,
        devPxWidth, devPxHeight, devRefreshRate, devOrientation};

String content = "";
for (int i = 0; i < textViews.length; i++) {
    content += (textViews[i].getText() + " = " + strings[i] + "\n");
}
return content;
}

现在工作得很好:)。