选项卡布局中的选项卡片段未在应用程序启动时获取数据

时间:2016-05-26 15:39:15

标签: android

我有一个标签布局,每个标签都包含一个从字符串响应中获取数据的列表,只有当我切换到下一个标签并返回到第一个时,我才会在第一个片段中获取数据。但是我没有得到我的应用程序首次启动时的数据。 我在选项卡之间切换后获取数据。 请帮帮我。

这是我的代码

package roastnow.volleyapp;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity 
     {

Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
TextView x;

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.gh);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    x= (TextView) findViewById(R.id.tv);
    tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

    // now add all the fragments to this adapter
    viewPagerAdapter.addFragments(new HomeFragment(), "Home");
    viewPagerAdapter.addFragments(new TopFreeFragment(), "Top Free");
    viewPagerAdapter.addFragments(new TopPaidFragment(), "Top Paid");
    viewPagerAdapter.addFragments(new SearchFragment(), "Search");
    viewPagerAdapter.addFragments(new AllFragment(), "All");
    //viewPager.setOffscreenPageLimit(4);
    viewPager.setAdapter(viewPagerAdapter);

    tabLayout.setupWithViewPager(viewPager);
    //TabLayout.Tab tab = tabLayout.getTabAt(2);
    //tab.select();
}
}

HomeFragment.java

 package roastnow.volleyapp;
 import android.app.ListFragment;
 import android.app.ProgressDialog;
 import android.content.Context;
 import android.media.tv.TvInputService;
 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.ListView;
 import android.widget.TextView;
 import com.android.volley.Request;
 import com.android.volley.RequestQueue;
 import com.android.volley.Response;
 import com.android.volley.VolleyError;
 import com.android.volley.VolleyLog;
 import com.android.volley.toolbox.JsonArrayRequest;
 import com.android.volley.toolbox.JsonObjectRequest;
 import com.android.volley.toolbox.StringRequest;
 import com.android.volley.toolbox.Volley;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 import org.w3c.dom.Text;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import com.android.volley.Request.Method;

 /**
  * A simple {@link Fragment} subclass.
  */
 public class HomeFragment extends Fragment {

private static final String url="http://192.168.1.2/fetch.php";
private static final String TAG= MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Venue> venueList=new ArrayList<Venue>();
private ListView listView;
private CustomListAdapter adapter;
public final boolean isVisibleToUser=false;
boolean _areLecturesLoaded = false;
private View rootView = null;
public HomeFragment() {
    // Required empty public constructor


}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    rootView= inflater.inflate(R.layout.fragment_home, container, false);
    return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    //venueList.clear();

        //loadData();





    // Log.w("lists", venueList.toString());
    //pDialog = new ProgressDialog(getActivity());

    //Showing progress dialog before making httprequest

    //pDialog.setMessage("Loading..");
    //pDialog.show();

    //creating volley request
    // venueList.clear();



//Log.w("lists2", venueList.toString());


    StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            Log.d(TAG, response.toString());

            hidepDialog();
            try {
                JSONObject jObj = new JSONObject(response);
                JSONArray jsonArray = jObj.getJSONArray("server_response");
                //Parsing json
                // JSONObject obj = response.getJSONObject();
                Log.w("js", jsonArray + "");
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject obj = jsonArray.getJSONObject(i);

                    Venue venue = new Venue();
                    venue.setTitle(obj.getString("name"));
                    venue.setAddress(obj.getString("address"));
                    venue.setImageUrl(obj.getString("image"));
                    venue.setRating(((Number) obj.get("rating")).doubleValue());

                    //adding the venue to venue array
                    venueList.add(venue);
                    Log.w("vl", venueList + "");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //Log.w("lists3", venueList.toString());
            //notify list adapter about the data change so that it rendersthe list view with updated data
            //adapter.notifyDataSetChanged();



        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error :" + error.getMessage());
            hidepDialog();

        }
    }
    );

    //Adding the request to request queue
    AppController.getInstance().addToRequestQueue(req);

    listView = (ListView) rootView.findViewById(R.id.list);
    listView.setAdapter(adapter);
    adapter = new CustomListAdapter(getActivity(), venueList);
}


@Override
public void onDestroy() {
    super.onDestroy();
    hidepDialog();
}

private void hidepDialog(){
    if(pDialog!=null){
        pDialog.dismiss();
**strong text**        pDialog=null;
    }
  }

 }

MyCustomListAdapter.java

 package roastnow.volleyapp;

 import android.app.Activity;
 import android.content.Context;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import android.widget.TextView;

 import com.android.volley.toolbox.ImageLoader;
 import com.android.volley.toolbox.NetworkImageView;
 import java.util.List;
 /**
  * Created by LUCKY on 5/25/2016.
  */
 public class CustomListAdapter extends BaseAdapter {

 private Activity activity;
 private LayoutInflater inflater;
 private List<Venue> venueItems;



 public CustomListAdapter(Activity activity,List<Venue> venueItems){
    this.activity=activity;
    this.venueItems=venueItems;
}


@Override
public int getCount() {
    return venueItems.size();
}

@Override
public Object getItem(int position) {
    return venueItems.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(inflater==null){
        inflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }
    if(convertView== null){
        convertView=inflater.inflate(R.layout.list_row,parent,false);
    }
    ImageLoader imageLoader=AppController.getInstance().getImageLoader();
    if(imageLoader==null){
        imageLoader=AppController.getInstance().getImageLoader();
    }
    NetworkImageView imageView= (NetworkImageView) convertView.findViewById(R.id.image);
    TextView title=(TextView) convertView.findViewById(R.id.title);
    TextView address= (TextView) convertView.findViewById(R.id.address);
    TextView rating= (TextView) convertView.findViewById(R.id.rating);

    //getting the data for the row
    Venue v=venueItems.get(position);

    //image
    imageView.setImageUrl(v.getImageUrl(),imageLoader);

    //title
    title.setText(v.getTitle());

    //address
    address.setText(v.getAddress());

    //rating
    rating.setText(String.valueOf(v.getRating()));


    return convertView;
   }
 }

1 个答案:

答案 0 :(得分:0)

将数据添加到列表生成

adapter.notifyDataSetChanged();

因为在设置适配器后完成了数据加载。您正在使用async请求。

也更好用的是:

adapter = new CustomListAdapter(getActivity(), venueList);    
listView.setAdapter(adapter);