标签片段不显示列表视图

时间:2014-12-25 16:06:50

标签: java android fragment tabbed

我尝试将tabbed片段与listview结合起来。我通过JSON获取数据并将其放在listview的片段中,但是当我启动应用程序片段时,不显示列表视图。

Actors.java `         公共类演员{

    private String name;
    private String description;
    private String dob;
    private String country;
    private String height;
    private String spouse;
    private String children;
    private String image;

    public Actors() {
        // TODO Auto-generated constructor stub
    }

    public Actors(String name, String description, String dob, String country,
            String height, String spouse, String children, String image) {
        super();
        this.name = name;
        this.description = description;
        this.dob = dob;
        this.country = country;
        this.height = height;
        this.spouse = spouse;
        this.children = children;
        //this.image = image;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

}

`

ActorAdapter.java `     import java.io.InputStream;     import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       // this.vi = LayoutInflater.from(context);
        this.Resource = resource;
        this.actorList = objects;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
        //  holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        //holder.imageview.setImageResource(R.drawable.ic_launcher);
        //new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("Pubblicato il: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Categoria: " + actorList.get(position).getHeight());
        return v;

    }

    static class ViewHolder {
        //public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;

    }

    /*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);
        }

    }*/
}

Main.java     import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;     import android.app.ActionBar;     import android.app.ActionBar.Tab;     import android.app.FragmentTransaction;     import android.os.Bundle;     import android.support.v4.app.FragmentActivity;     import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Top Rated", "Games", "Movies" };

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

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

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

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

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

}

TopRatedFragment.java     import android.app.ProgressDialog;     import android.content.Context;     import android.content.Intent;     import android.os.AsyncTask;     import android.os.Bundle;     import android.support.v4.app.Fragment;     import android.view.LayoutInflater;     import android.view.View;     import android.view.ViewGroup;     import android.widget.AdapterView;     import android.widget.ListView;     import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;

public class TopRatedFragment extends Fragment {
    ArrayList<Actors> actorsList;
    Context context=getActivity();
    ActorAdapter adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
        actorsList = new ArrayList<Actors>();
        new JSONAsyncTask().execute("http://www.technologici.it/api/get_recent_posts/");

        ListView listview = (ListView)rootView.findViewById(R.id.list);
        context = getActivity();
        listview.setAdapter(new ActorAdapter(getActivity(), R.layout.row, actorsList));
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long id) {
                // TODO Auto-generated method stub
                // Starting single contact activity
                Intent in = new Intent(getActivity(),
                        SingleContactActivity.class);
                in.putExtra("title", actorsList.get(position).getName());
                in.putExtra("author", actorsList.get(position).getCountry());
                in.putExtra("data", actorsList.get(position).getDob());
                in.putExtra("content", actorsList.get(position).getDescription());
                in.putExtra("category", actorsList.get(position).getHeight());
                //in.putExtra("image", actorsList.get(position).getImage());
                startActivity(in);
            }
        });
        setRetainInstance(true);
        return rootView;
    }




    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(getActivity());
            dialog.setMessage("Caricamento...");
            dialog.setTitle("Contattando il server...");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                //------------------>>
                HttpGet httppost = new HttpGet(urls[0]);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);


                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("posts");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Actors actor = new Actors();

                        actor.setName(object.getString("title"));
                        actor.setDescription(object.getString("content"));
                        actor.setDob(object.getString("date"));
                        JSONObject author = object.getJSONObject("author");
                        actor.setCountry(author.getString("name"));


                        JSONArray catarray = object.getJSONArray("categories");
                        JSONObject catobject = catarray.getJSONObject(0);
                        actor.setHeight(catobject.getString("title"));


                       // JSONArray imgarray = object.getJSONArray("attachments");
                       // JSONObject imgobject = imgarray.getJSONObject(0);
                        //actor.setImage(imgobject.getString("url"));

                        actorsList.add(actor);
                    }
                    return true;
                }

                //------------------>>

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        protected void onPostExecute(Boolean result) {
            dialog.cancel();
           // adapter.notifyDataSetChanged();
            if (result == false) {
               Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
            }
        }


    }
}

Layout: fragment_top_rated.xml          

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:listitem="@layout/row" >

    </ListView>

</LinearLayout>

row.xml          

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Tom Cruise"
                android:textColor="#166CED"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/tvDateOfBirth"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="Date of Birth: July 3, 1962" />

            <TextView
                android:id="@+id/tvHeight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Height: 1.80 m"
                android:textColor="#D64530"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/tvCountry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="United States" />
    <TextView
        android:id="@+id/tvDescriptionn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#009A57"
        android:text="Description"
        android:visibility="gone"/>
        </LinearLayout>

` 有人能帮助我吗?

0 个答案:

没有答案