Java 片段和片段列表不';t显示Android Studio

Java 片段和片段列表不';t显示Android Studio,java,android,android-fragments,android-studio,android-listfragment,Java,Android,Android Fragments,Android Studio,Android Listfragment,我想用FragmentActivity实现选项卡栏列表。我的目标是API 14(4.0)。我的应用程序工作正常,但选项卡栏列表不显示。。。我不知道我做错了什么。。。谢谢你的帮助 MainActivity.java: import android.app.ActionBar; import android.app.FragmentTransaction; import android.content.Intent; import android.annotation.TargetApi; impo

我想用FragmentActivity实现选项卡栏列表。我的目标是API 14(4.0)。我的应用程序工作正常,但选项卡栏列表不显示。。。我不知道我做错了什么。。。谢谢你的帮助

MainActivity.java:

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.annotation.TargetApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

import static android.location.Location.convert;


public class MainActivity extends ActionBarActivity implements
        ActionBar.TabListener {

    public static final String TAG = MainActivity.class.getSimpleName();

    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link android.support.v4.view.ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    private CurrentReportString mCurrentReportString;
    @InjectView(R.id.jsonText) TextView mJsonText;
    @InjectView(R.id.imageReport) ImageView mImageReport;
    @InjectView(R.id.imageReport2) ImageView mImageReport2;
    @InjectView(R.id.imageReport3) ImageView mImageReport3;
    @InjectView(R.id.adminText) TextView mAdminText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);


        mAdminText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });

        String urlWebSite = "http://www.bundoransurfco.com/surf-report/surf-report/?json=1";

        if (isNetworkAvailable()) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(urlWebSite)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String jsonData = response.body().string();
                        if (response.isSuccessful()) {
                            mCurrentReportString = getCurrentDetails(jsonData);
                            int numberOfPhotos = mCurrentReportString.getNumberOfPhotos();
                            if (numberOfPhotos == 1){
                            new DownloadImageTask(mImageReport)
                                    .execute(mCurrentReportString.getUrlImages());
                            }
                            if (numberOfPhotos == 2){
                                new DownloadImageTask(mImageReport)
                                        .execute(mCurrentReportString.getUrlImages());
                                new DownloadImageTask(mImageReport2)
                                        .execute(mCurrentReportString.getUrlImages2());
                            }
                            if (numberOfPhotos == 3){
                                new DownloadImageTask(mImageReport)
                                        .execute(mCurrentReportString.getUrlImages());
                                new DownloadImageTask(mImageReport2)
                                        .execute(mCurrentReportString.getUrlImages2());
                                new DownloadImageTask(mImageReport3)
                                        .execute(mCurrentReportString.getUrlImages3());
                            }
                            if (numberOfPhotos > 3){
                                new DownloadImageTask(mImageReport)
                                        .execute(mCurrentReportString.getUrlImages());
                                new DownloadImageTask(mImageReport2)
                                        .execute(mCurrentReportString.getUrlImages2());
                                new DownloadImageTask(mImageReport3)
                                        .execute(mCurrentReportString.getUrlImages3());
                            }

                            // Write in the main Thread.
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateReport();
                                }
                            });

                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                      catch (JSONException e){
                          Log.e(TAG, "Exception caught: ", e);
                      }
                }
            });
        }
        else {
            Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
        }

        Log.d(TAG, "Main UI code is running!");
    }

    @Override
    protected void onResume() {
        super.onResume();
        initUI();
    }

    private void updateReport() {
        mJsonText.setText(mCurrentReportString.getJsonContent());
        if (mCurrentReportString.imageBackground == Boolean.FALSE)
        {
            Log.i(TAG, "No Background1");
            mImageReport.setVisibility(View.INVISIBLE);
        }
        if (mCurrentReportString.imageBackground2 == Boolean.FALSE)
        {
            Log.i(TAG, "No Background2");
            mImageReport2.setVisibility(View.INVISIBLE);
        }
        if (mCurrentReportString.imageBackground3 == Boolean.FALSE)
        {
            Log.i(TAG, "No Background3");
            mImageReport3.setVisibility(View.INVISIBLE);
        }

    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private CurrentReportString getCurrentDetails(String jsonData) throws JSONException {
        JSONObject report = new JSONObject(jsonData);

        JSONObject postJson = report.getJSONObject("post");
        CurrentReportString currentReportString = new CurrentReportString();
        String contentString = postJson.getString("content");


        //Report String
        String contentWithoutWebcam = contentString.replace("CLICK HERE FOR LIVE PEAK WEBCAM", "");
        int lastCharacter = contentWithoutWebcam.indexOf("#gallery-1");
        String contentFirstPart = contentWithoutWebcam.substring(0, lastCharacter);
        String jsonText = stripHtml(contentFirstPart);
        currentReportString.setJsonContent(jsonText);

        //Images
        Document doc = Jsoup.parse(contentString);
        Elements relLinks = doc.select("a[rel]");
//Elements relLinks = doc.select("a[rel=prettyPhoto[gallery-113]]");//
        System.out.println("number of `rel`: "+relLinks.size());
        currentReportString.setNumberOfPhotos(relLinks.size());
        ArrayList<String> urls=new ArrayList<String>();
        for (Element el : relLinks){
         //   Log.i(TAG, el.attr("href"));
            urls.add(el.attr("href"));
        }
        if (relLinks.size() == 0){
            Log.i(TAG, "0 image");
            currentReportString.setImageBackground(Boolean.FALSE);
            currentReportString.setImageBackground2(Boolean.FALSE);
            currentReportString.setImageBackground3(Boolean.FALSE);
        }
        else if (relLinks.size() == 1) {
            // Log.i(TAG, String.valueOf(urls));
            currentReportString.setUrlImages(urls.get(0));
            Log.i(TAG, "first URL : " + currentReportString.getUrlImages());
            currentReportString.setImageBackground2(Boolean.FALSE);
            currentReportString.setImageBackground3(Boolean.FALSE);
/*            new DownloadImageTask(mImageReport)
                    .execute(mCurrentReportString.getUrlImages());*/
        }
        else if (relLinks.size() == 2){
            currentReportString.setUrlImages(urls.get(0));
            currentReportString.setUrlImages2(urls.get(1));
            currentReportString.setImageBackground3(Boolean.FALSE);
            Log.i(TAG, "first URL : "+currentReportString.getUrlImages());
            Log.i(TAG, "second URL : "+currentReportString.getUrlImages2());
/*            new DownloadImageTask(mImageReport)
                    .execute(mCurrentReportString.getUrlImages());
            new DownloadImageTask(mImageReport2)
                    .execute(mCurrentReportString.getUrlImages2());*/
        }
        else if (relLinks.size() == 3){
            currentReportString.setUrlImages(urls.get(0));
            currentReportString.setUrlImages2(urls.get(1));
            currentReportString.setUrlImages3(urls.get(2));
            Log.i(TAG, "first URL : "+currentReportString.getUrlImages());
            Log.i(TAG, "second URL : "+currentReportString.getUrlImages2());
            Log.i(TAG, "third URL : "+currentReportString.getUrlImages3());

/*            new DownloadImageTask(mImageReport2)
                    .execute(mCurrentReportString.getUrlImages2());
            new DownloadImageTask(mImageReport3)
                    .execute(mCurrentReportString.getUrlImages3());*/
        }
        else if (relLinks.size() > 3){
            currentReportString.setUrlImages(urls.get(0));
            currentReportString.setUrlImages2(urls.get(1));
            currentReportString.setUrlImages3(urls.get(2));
            Log.i(TAG, "first URL : "+currentReportString.getUrlImages());
            Log.i(TAG, "second URL : "+currentReportString.getUrlImages2());
            Log.i(TAG, "third URL : "+currentReportString.getUrlImages3());
/*            new DownloadImageTask(mImageReport)
                    .execute(mCurrentReportString.getUrlImages());
            new DownloadImageTask(mImageReport2)
                    .execute(mCurrentReportString.getUrlImages2());
            new DownloadImageTask(mImageReport3)
                    .execute(mCurrentReportString.getUrlImages3());*/
        }


        return currentReportString;
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            isAvailable = true;
        }

        return isAvailable;
    }
    //Delete HTML Markup
    public String stripHtml(String html) {
        return Html.fromHtml(html).toString();
    }

    private void alertUserAboutError() {
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(), "error_dialog");
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    //Change Image from ImageView in Asynch with URL.
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;
        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }
        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }


/*    @Override
    public void onTabSelected(android.support.v7.app.ActionBar.Tab tab,
                              FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(android.support.v7.app.ActionBar.Tab tab,
                                FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(android.support.v7.app.ActionBar.Tab tab,
                                FragmentTransaction fragmentTransaction) {
    }*/

    private void initUI(){
        final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(android.support.v7.app.ActionBar.NAVIGATION_MODE_TABS);

        mSectionsPagerAdapter = new SectionsPagerAdapter(this,
                getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
                    }
                });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener((android.support.v7.app.ActionBar.TabListener) this));
        }
    }

/*    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }*/
}
LoginFragment.java:

    import android.os.Bundle;
    import android.support.v4.app.ListFragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;

    public class LoginFragment extends ListFragment {

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

            return rootView;
        }
}
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends ListFragment {

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

        return rootView;
    }
}
activity_login.xml:

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:background="#FFFFFF"
                tools:context="jardelcompany.bundoransurfco.LoginFragment">
</RelativeLayout>
activity_main.xml:

<RelativeLayout 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"
    tools:context=".MainActivity"
    android:id="@+id/mainLayout"
    android:background="#FFFFFF"> />

    <view
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="android.support.v4.view.ViewPager"
        android:id="@+id/pager"/>
</RelativeLayout>
MainActivity中的
onResume(Bundle savedInstanceState)
方法由于参数错误而从未被调用,而且您也没有调用
super.onResume()
。正确的方法是:

@Override
protected void onResume() 
{
    super.onResume();
    initUI();
}

有关文档,请参见此处:

按如下方式更新代码

@Override    
protected void onResume() {
    super.onResume();
    initUI();
}


对于
ActionBarActivity
,您应该使用
getSupportFragmentManager()
getSupportActionBar()

请发布您的MainActivity.javacompletely@HeshanSandeepa编辑;)如果它崩溃了,发布日志please@HeshanSandeepa感谢您的帮助,使用logcatI编辑,使用此代码和我的应用程序崩溃测试:致命异常:主进程:jardelcompany.bundoransurfco,PID:1386 java.lang.RuntimeException:无法恢复活动{jardelcompany.bundoransurfco/jardelcompany.bundoransurfco.MainActivity}:java.lang.NullPointerException由:jardelcompany.bundoransurfco.MainActivity.InTui(MainActivity.java:342)处的jardelcompany.bundoransurfco.MainActivity.onResume(MainActivity.java:169)处的java.lang.NullPointerException引起如果不调用super method,它将不会调用。现在,您的initUI方法被执行,并且它会在线崩溃342@udduk是的,这行代码是:actionBar.setNavigationMode(actionBar.NAVIGATION\u MODE\u选项卡);所以getActionBar似乎返回null。尝试调用getSupportActionBar()谢谢回复人,我已经导入了android.support.v7.app.ActionBarActivity;导入android.support.v7.app.ActionBar;并输入:final android.support.v7.app.ActionBar ActionBar=getSupportActionBar()???但是下一行actionBar.setNavigationMode(actionBar.NAVIGATION\u MODE\u选项卡);不工作,并且.setTableListener(此));也是红色的…请看一下我上一次编辑,应用程序崩溃在一个新行:actionBar.addTab(actionBar.newTab()如错误所述,您的
main活动
没有
实现ActionBar。TabListener
哦,别担心,它看起来是由您的错误导入造成的。您应该从支持库中实现TabListener。很好,没问题!:)现在,最后一个错误:您的内容必须有一个id属性为“android.R.id.list”的ListView,我必须将ListView放在哪里?activity_main.xml?请最后查看我编辑的代码:我的应用程序在actionBar.addTab(actionBar.newTab()上崩溃将actionbar导入替换为导入android.support.v7.app.actionbar;而不是导入app.actionbar;你是对的!最后一个错误:你的内容必须有一个id属性为“android.R.id.list”的ListView…我需要在哪里放置ListView?在activity_main.xml中?你尝试在哪里放置ListView?我不知道,我没有ListView…可以吗我需要在我的XML中创建它?因为我使用的是自定义视图:所以也许我需要在no中实现?我真的很抱歉,我是初学者。。。
<RelativeLayout 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"
    tools:context=".MainActivity"
    android:id="@+id/mainLayout"
    android:background="#FFFFFF"> />

    <view
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="android.support.v4.view.ViewPager"
        android:id="@+id/pager"/>
</RelativeLayout>
FATAL EXCEPTION: main
    Process: jardelcompany.bundoransurfco, PID: 2250
    java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
@Override
protected void onResume() 
{
    super.onResume();
    initUI();
}
@Override    
protected void onResume() {
    super.onResume();
    initUI();
}