My Fragment is not showing custom listview data. Asynctask is working properly but after sometime application is crashing with null pointer exception.
My fragment class code :
package com.example.y34h1a.androidlime.Fragment;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
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 com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.adapter.FeedListAdapter;
import com.example.y34h1a.androidlime.data.FeedItem;
import com.example.y34h1a.androidlime.network.VolleySigleton;
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.util.ArrayList;
public class FragmentBoxOffice extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VolleySigleton volleySigleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private OnFragmentInteractionListener mListener;
private static final String TAG = FragmentBoxOffice.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private ArrayList<FeedItem> feedItems;
private String URL_FEED = "http://androidlime.com/wp-json/posts";
private FeedItem feedItem = new FeedItem();
// TODO: Rename and change types and number of parameters
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentBoxOffice() {
// Required empty public constructor
feedItems = new ArrayList<FeedItem>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_box_office, container, false);
listView = (ListView) view.findViewById(R.id.fragmentList);
new JSONAsyncTask().execute(URL_FEED);
return view;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
for(String url : urls){
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject titleObj = jsonArray.getJSONObject(i);
String title = titleObj.getString("title");
feedItem.setStatus(title);
Log.i("arif", title);
//DATE
String date = titleObj.getString("date");
feedItem.setTimeStamp(date);
Log.i("arif", date);
//Author Name
JSONObject author = titleObj.getJSONObject("author");
String name = author.getString("name");
feedItem.setName(name);
Log.i("arif", name);
//Author Profile Pic
String profilePic = author.getString("avatar");
feedItem.setProfilePic(profilePic);
Log.i("arif", profilePic);
//Post thumbnail
JSONObject thumnailObj = titleObj.getJSONObject("featured_image");
String thumbnail = thumnailObj.getString("guid");
feedItem.setThumnail(thumbnail);
Log.i("arif", thumbnail);
feedItems.add(feedItem);
}
return true;
//------------------>>
} catch (IOException e) {
Log.e("arif", "Parse Exception");
} catch (JSONException e) {
Log.e("arif", "Parse Exception");
}
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
if(result == false)
Log.i("arif","unable to featch data");
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
My Custom Adapter Class:
package com.example.y34h1a.androidlime.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.data.FeedItem;
import java.util.ArrayList;
import java.util.List;
public class FeedListAdapter extends ArrayAdapter<FeedItem> {
private LayoutInflater vi;
private List<FeedItem> feedItems;
int Resource;
ViewHolder holder;
public FeedListAdapter(Context context, int resource, ArrayList<FeedItem> feedItems) {
super(context, resource, feedItems);
this.feedItems = feedItems;
Resource = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
holder.name = (TextView) v.findViewById(R.id.name);
holder.status = (TextView) v.findViewById(R.id.txtStatusMsg);
holder.time = (TextView) v.findViewById(R.id.timestamp);
holder.url = (TextView) v.findViewById(R.id.txtUrl);
holder.profilePic = (ImageView) v.findViewById(R.id.profilePic);
holder.thumbnail = (ImageView) v.findViewById(R.id.thumbernail);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
v.setTag(holder);
holder.name.setText(feedItems.get(position).getName());
holder.status.setText(feedItems.get(position).getStatus());
holder.time.setText(feedItems.get(position).getTimeStamp());
holder.url.setText(feedItems.get(position).getUrl());
holder.profilePic.setImageResource(R.drawable.ic_launcher);
holder.profilePic.setImageResource(R.drawable.sample);
return v;
}
static class ViewHolder {
public TextView name;
public TextView status;
public TextView url;
public TextView time;
public ImageView profilePic;
public ImageView thumbnail;
}
}
The line where error showing is :
View v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);'
From your code, I think your error is more like ClassCastException, don't know why it's NPE, because
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
You pass a ApplicationContext then cast it to a Activity
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
Try this may works:
in onPostExecute:
if (getActivity() != null) {
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
}
in getView:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item, parent, false);
Try:
v = (LayoutInflater.from(getContext()).inflate(R.layout.feed_item, parent, false);
Related
I want to display what my array list value is. So, I want to loop with the size of array list as the limit. But after I add some value through a function, and want to get the size of it, it always 0. I still newbie in android programming. I had search in google, but still confused and not understand what the problem is. Thanks for you guys help
I had tried to set through global variable, but it's not work
Here is my activity file
package bobby.irawan.aticket;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
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.toolbox.JsonObjectRequest;
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.List;
public class DetailPromoActivity extends AppCompatActivity {
private ListView listView;
private TextView nama_detail_promo_tv;
private String nama_detail_promo;
private DetailPromoAdapter adapter;
private int counter_header=0, counter_promo = 0;
private View layout_kupon;
private int id_link_promo;
private RequestQueue requestQueue;
private String url = "192.168.11.134:8000";
private TextView header_promo, kupon_promo, notif_promo;
private ArrayList<DetailPromo> detailPromos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_promo);
View view = findViewById(R.id.layout_kupon);
header_promo = view.findViewById(R.id.header_promo_tv);
kupon_promo = view.findViewById(R.id.kode_promo_tv);
id_link_promo = (int) getIntent().getSerializableExtra("id_promo");
nama_detail_promo = (String) getIntent().getSerializableExtra("nama_promo");
String nama_ota = (String) getIntent().getSerializableExtra("nama_ota");
listView = findViewById(R.id.lv_detpro);
layout_kupon = findViewById(R.id.layout_kupon);
header_promo = layout_kupon.findViewById(R.id.header_promo_tv);
kupon_promo = layout_kupon.findViewById(R.id.kode_promo_tv);
notif_promo = layout_kupon.findViewById(R.id.notif_promo_tv);
requestQueue = Volley.newRequestQueue(this);
nama_detail_promo_tv = findViewById(R.id.nama_detail_promo);
nama_detail_promo_tv.setText(nama_detail_promo);
setDetailPromotoClass(id_link_promo);
adapter = new DetailPromoAdapter(detailPromos,this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Promo "+nama_ota);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
//Set kupon
System.out.println("Size detpro "+counter_header+" "+counter_promo);
if(counter_header == 0 && counter_promo == 0){
notif_promo.setVisibility(View.VISIBLE);
header_promo.setVisibility(View.GONE);
kupon_promo.setVisibility(View.GONE);
System.out.println("Masuk sini");
}
else if(counter_header == 0){
header_promo.setText("PROMO PESAWAT");
}
else{
kupon_promo.setText("Tidak perlu");
}
}
class DetailPromoAdapter extends BaseAdapter {
private List<DetailPromo> detailPromo;
private Context context;
public DetailPromoAdapter(List<DetailPromo> detailPromo, Context context) {
this.detailPromo = detailPromo;
this.context = context;
}
#Override
public int getCount() {
System.out.println("Detail promo size"+detailPromo.size());
return detailPromo.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.detail_promo_adapter, parent, false);
TextView nama_detail_promo = convertView.findViewById(R.id.isi_detail_promo);
if(detailPromo.get(position).getDetpro_role().equals("detail_promo")){
nama_detail_promo.setText(detailPromo.get(position).getDetpro_list());
}
return convertView;
}
}
public void setDetailPromotoClass(int id_linkpro){
detailPromos = new ArrayList<DetailPromo>();
String url_promo = "http://"+url+"/detail_promo/"+id_linkpro;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url_promo, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++){
JSONObject data_promo = jsonArray.getJSONObject(i);
int id_detpro = data_promo.getInt("id");
int id_promo = data_promo.getInt("promo_id");
int id_linkpro = data_promo.getInt("linkpro_id");
String detpro_list = data_promo.getString("detpro_list");
String detpro_role = data_promo.getString("detpro_role");
detailPromos.add(new DetailPromo(id_detpro,id_promo,id_linkpro,detpro_list,detpro_role));
System.out.println("Data promo yang diklik "+id_promo+" "+id_linkpro+" "+detpro_list+" "+detpro_role);
adapter.notifyDataSetChanged();
if(detpro_role.equals("header_promo")){
header_promo.setText(detailPromos.get(i).detpro_list);
System.out.println("Ada header");
counter_header++;
}
if(detpro_role.equals("kode_promo")){
System.out.println("Ada kupon");
kupon_promo.setText(detailPromos.get(i).detpro_list);
counter_promo++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
I have simply used a custom list inside a fragment.I have retrieved those data from api using volley.It shows following error.I am getting any idea to resolve this,Can somebody please help me.
java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.example.user.ekta.AppController.getImageLoader()' on a null object reference
at com.example.user.ekta.MyBookAdapter.<init>(MyBookAdapter.java:25)
at com.example.user.ekta.FullInfoTabFragment.onCreateView(FullInfoTabFragment.java:85).
This is my Fragment class
package com.example.user.ekta;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FullInfoTabFragment extends Fragment {
private static final String EXTRA_SRORT_CARD_MODEL = "EXTRA_SRORT_CARD_MODEL";
// String transitionTag;
private SportCardModel sportCardModel;
private Toolbar toolbar;
private ImageView ivPhoto;
private static final String TAG = FullInfoTabFragment.class.getSimpleName();
private static final String url = "http://myeducationhunt.com/public/schools";
private ProgressDialog pDialog;
private List<MyBook> ourBooksListItems = new ArrayList<MyBook>();
private ListView listView;
private MyBookAdapter adapter;
public static FullInfoTabFragment newInstance(SportCardModel sportCardModel) {
FullInfoTabFragment fragment = new FullInfoTabFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
sportCardModel = getArguments().getParcelable(EXTRA_SRORT_CARD_MODEL);
}
if (savedInstanceState != null) {
sportCardModel = savedInstanceState.getParcelable(EXTRA_SRORT_CARD_MODEL);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_full_info, container, false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
ivPhoto = (ImageView) view.findViewById(R.id.ivPhoto);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MyBookAdapter(getActivity(), ourBooksListItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// OurSchool ourSchool = new OurSchool();
// Intent i = new Intent(getContext(), SchoolDetails.class);
// i.putExtra("id", ourSchoolsListItems.get(position).schoolId);
// i.putExtra("name", ourSchoolsListItems.get(position).schoolName);
// i.putExtra("location", ourSchoolsListItems.get(position).schoolLocation);
// i.putExtra("logo", ourSchoolsListItems.get(position).schoolLogo);
// i.putExtra("email", ourSchoolsListItems.get(position).schoolEmail);
// i.putExtra("website", ourSchoolsListItems.get(position).schoolWebsite);
// i.putExtra("created_at", ourSchoolsListItems.get(position).createdAt);
// i.putExtra("updated_at", ourSchoolsListItems.get(position).updatedAt);
// startActivity(i);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading…");
pDialog.show();
// Creating volley request obj
JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyBook myBook = new MyBook();
myBook.bookName = obj.getString("name");
myBook.bookAuthor = obj.getString("location");
myBook.bookCover= obj.getString("logo");
// adding schools to ourSchool list
ourBooksListItems.add(myBook);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar.setTitle(sportCardModel.getSportTitle());
toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), sportCardModel.getBackgroundColorResId()));
ivPhoto.setImageResource(sportCardModel.getImageResId());
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
super.onSaveInstanceState(outState);
}
static class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
private Drawable mDivider;
/**
* Default divider will be used
*/
public DividerItemDecoration(Context context) {
final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
mDivider = styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
/**
* Custom divider will be used
*/
public DividerItemDecoration(Context context, int resId) {
mDivider = ContextCompat.getDrawable(context, resId);
}
#Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
}
And this is my adapter class
package com.example.user.ekta;
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 user on 11/27/2016.
*/
public class MyBookAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<MyBook> ourbooksList;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MyBookAdapter(Activity activity, List<MyBook> ourbooksListsList) {
this.activity = activity;
this.ourbooksList = ourbooksListsList;
}
#Override
public int getCount() {
return ourbooksList.size();
}
#Override
public Object getItem(int location) {
return ourbooksList.get(location);
}
#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_books, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView bookCover = (NetworkImageView) convertView
.findViewById(R.id.bookCover);
TextView bookName = (TextView) convertView.findViewById(R.id.bookName);
TextView boookAuthor = (TextView) convertView.findViewById(R.id.bookAuthor);
MyBook m = ourbooksList.get(position);
bookCover.setImageUrl(m.getBookCover(), imageLoader);
bookName.setText("Name: " + m.getBookName());
boookAuthor.setText("Address: " + String.valueOf(m.getBookAuthor()));
return convertView;
}
}
AppController.getInstance() is returning null, you have not initialized your Appcontroller.
If AppController extends your application, then you have to change your manifest
android:name= "path to AppController" in app section.
I have an activity with a tablayout. When the activity is created, the viewpageradapter is created and adds 3 instances of the same fragment class to it. Then, then, I set the adapter to the view pager.
I know that the fragment addition is happening correctly because my fragment executes an asyncTask and its logging statements appear in the console. For some reason, when I start the activity, I can see the app bar and the widget displaying the tabs, but the space where the fragment should appear is empty. What am I doing wrong?
This is my code:
MainActivity
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final String LIST_TAG = MovieListFragment.class.getSimpleName();
private final String DETAIL_TAG = DetailActivityFragment.class.getSimpleName();
private final String POPULAR = "POPULAR";
private final String HIGHEST_RATED = "HIGHEST RATED";
private final String FAVOURITE = "FAVOURITE";
private boolean mTwoPane;
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//We check if the layout selected has two fragments
if (findViewById(R.id.movie_detail_container) != null) {
//If it has two, we update our member variable
mTwoPane = true;
/*If the activity has been recently created, we replace the placeholder
frameview with the actual detail fragment
*/
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(
R.id.movie_detail_container,
new DetailActivityFragment(),
DETAIL_TAG
).commit();
}
} else {
mTwoPane = false;
}
mViewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(mViewPager);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*If it's the first time we launch the activity, we create a fragment
and tag it so we have a reference to find it later
*/
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
MovieListFragment popular = new MovieListFragment();
MovieListFragment highestRated = new MovieListFragment();
MovieListFragment favourites = new MovieListFragment();
populateFragment(popular);
populateFragment(highestRated);
populateFragment(favourites);
adapter.addFragment(popular, POPULAR);
adapter.addFragment(highestRated, HIGHEST_RATED);
adapter.addFragment(favourites, FAVOURITE);
viewPager.setAdapter(adapter);
}
private void populateFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//We identify the option clicked and act accordingly
switch (id) {
/* Not necessary at this stage of the project. Will be
populated later.
*/
case R.id.action_settings: {
return true;
}
/* If the sort method is changed we start an asynchronous task
and fetch the appropriate movies.
*/
case R.id.sort_popularity: {
MovieListFragment.setmSortOrder("popularity.desc");
MovieListFragment movieListFragment = (MovieListFragment)
getSupportFragmentManager().findFragmentByTag(LIST_TAG);
movieListFragment.retrieveMovies();
break;
}
case R.id.sort_highest_Rating: {
MovieListFragment.setmSortOrder("vote_average.desc");
MovieListFragment movieListFragment = (MovieListFragment)
getSupportFragmentManager().findFragmentByTag(LIST_TAG);
movieListFragment.retrieveMovies();
break;
}
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position)
{
return new MovieListFragment();
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
MovieListFragment
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MovieListFragment extends Fragment {
//Defining size params for the images in the gridview
private final int IMAGE_WIDTH = 450;
private final int IMAGE_HEIGHT = 675;
private static String mSortOrder = "popularity.desc";
public final static String EXTRA_MOVIE = "com.example.android.movierating.EXTRA_MOVIE";
private final String LOG_TAG = MovieListFragment.class.getSimpleName();
MovieAdapter mMovieAdapter;
private LayoutInflater mInflater;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
// We want to add options to the Menu bar.
setHasOptionsMenu(true);
}
public static String getmSortOrder() {
return mSortOrder;
}
public static void setmSortOrder(String sortOrder) {
mSortOrder = sortOrder;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.movielist_fragment, menu);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = inflater;
// We inflate and store the rootView
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// We sotre the gridview and set a custom adapter to it. It is defined below
GridView gridView = (GridView) getActivity().findViewById(R.id.gridview);
mMovieAdapter = new MovieAdapter(
getContext(),
R.id.image_thumbnail,
new ArrayList<Movie>()
);
gridView.setAdapter(mMovieAdapter);
/* The gridView will react to a user clicking on it by creating
an intent and populating it with the movie object. That object
will provide the data necessary to display facts about the movie
*/
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = mMovieAdapter.getItem(position);
Intent detailIntent = new Intent(getActivity(), DetailActivity.class)
.putExtra(EXTRA_MOVIE, (Parcelable) movie);
startActivity(detailIntent);
}
});
return rootView;
}
public void retrieveMovies() {
if (getmSortOrder() == "popularity.desc" || getmSortOrder() == "vote_average.desc") {
FetchMoviesTask moviesTask = new FetchMoviesTask();
String sortOrderArray[] = {mSortOrder};
moviesTask.execute(sortOrderArray);
}
}
#Override
public void onStart() {
super.onStart();
retrieveMovies();
}
// Custom adapter to display Movies on a gridView
public class MovieAdapter extends ArrayAdapter<Movie> {
//Context member variable
private Context mContext;
//Constructor
public MovieAdapter(Context context, int imgViewResourceId,
ArrayList<Movie> items) {
super(context, imgViewResourceId, items);
mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
view = mInflater.inflate(R.layout.fragment_main,null);
} else {
view = convertView;
}
ImageView imageView = (ImageView) view.findViewById(R.id.image_thumbnail);
TextView textView = (TextView) view.findViewById(R.id.overlay_text);
String url = getItem(position).getUrlPath();
Picasso.with(mContext)
.load(url)
.resize(IMAGE_WIDTH,IMAGE_HEIGHT)
.centerCrop()
.into(imageView);
String movieTitle = getItem(position).getOriginalTitle();
textView.setText(movieTitle);
textView.setBackgroundColor(getResources().getColor(R.color.translucid_black));
textView.setTextColor(getResources().getColor(R.color.opaque_white));
return view;
}
}
// Nested class to fetch the Json information about the movies
public class FetchMoviesTask extends AsyncTask<String, Void, List<Movie>> {
//Log tag for debugging purposes
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
// Method to take a JSON string and return a list of Movie
// objects.
private List<Movie> parseJSONtoArrayList(String stringJSON)
throws JSONException{
// String constants and the arraylist holding the results
final String MDB_RESULTS = "results";
final String MDB_ID = "id";
final String MDB_PATH = "poster_path";
final String MDB_TITLE = "original_title";
final String MDB_SYNOPSIS = "overview";
final String MDB_RATING = "vote_average";
final String MDB_VOTE_COUNT = "vote_count";
final String MDB_RELEASE = "release_date";
List<Movie> movieArrayList = new ArrayList<>();
// We turn the results into a JSONObject and we extract the JSONObjects
// into an array of objects.
JSONObject dataJSON = new JSONObject(stringJSON);
JSONArray movieArray = dataJSON.getJSONArray(MDB_RESULTS);
/* We iterate over the array of JSONObjects, we create a new
Movie object and we append it to the arraylist holding the
results.
*/
for (int i=0; i<movieArray.length(); i++) {
// Select a JSONObject in every iteration.
JSONObject target = movieArray.getJSONObject(i);
/* Create a Movie Object by retrieving the necessary elements
of the JSONObject
*/
Movie movie = new Movie(
target.getInt(MDB_ID),
createURL(target.getString(MDB_PATH)),
target.getString(MDB_TITLE),
target.getString(MDB_SYNOPSIS),
Float.parseFloat(target.getString(MDB_RATING)),
Integer.parseInt(target.getString(MDB_VOTE_COUNT)),
target.getString(MDB_RELEASE)
);
// Once we have created our object, we add it to the arrayList
movieArrayList.add(movie);
}
return movieArrayList;
}
/* Transform a relative path provided by the API into a fully functional
URL path.
*/
private String createURL(String relativePath) {
final String BASE_IMAGE_URL = "http://image.tmdb.org/t/p/";
final String PIX_MEASURE = "w185";
return BASE_IMAGE_URL + PIX_MEASURE + relativePath;
}
#Override
protected List<Movie> doInBackground(String... params) {
// Our default sorting parameter, request declaration,
// reader and empty string
String sortMethod = params[0];
HttpURLConnection connection = null;
BufferedReader reader = null;
String moviesJSON = null;
try {
// We build the URI
final String BASE_URL =
"http://api.themoviedb.org/3/discover/movie?";
final String API_KEY = "api_key";
final String SORT = "sort_by";
String uri = Uri.parse(BASE_URL)
.buildUpon().appendQueryParameter(SORT, sortMethod)
.appendQueryParameter(API_KEY, getString(R.string.ApiKey))
.build().toString();
URL url = new URL(uri);
//Create the request and open the connection
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// Create objects to hold the results of the API call
InputStream inputStream = connection.getInputStream();
StringBuilder builder = new StringBuilder();
// If we don't receive anything, we just return
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
// We write the api call results into the string builder
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + '\n');
}
// We check that the result is not empty
if (builder.length() == 0) {
return null;
}
moviesJSON = builder.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "There was a problem fetching the movies");
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader !=null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "We found a problem while closing the reader");
e.printStackTrace();
}
}
}
try {
return parseJSONtoArrayList(moviesJSON);
} catch (JSONException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Movie> movies) {
super.onPostExecute(movies);
if (movies != null) {
// Every time we call this task, we flush the Movies in the adaptor
// And fill it up again with the results of the API call.
mMovieAdapter.clear();
Log.e(LOG_TAG, movies.toString());
mMovieAdapter.addAll(movies);
}
}
}
}
Thank you very much in advance
As I can change the setContentView if I 'm in a Fragment
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.j_01_list);
new ProgressTask(jornada.this).execute();
}
If you are a Fragment you can set your view calling onCreateView() like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.j_01_list, container, false);
}
but this only will happens if you extends from FRAGMENT
Example of a Fragment
public class TestFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.j_01_list, container, false);
return rootView;
}
}
For more information check this Fragment Documentation and onCreateView() Documentation
package com.aab;
import android.app.ListActivity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class jornada extends ListFragment {
private Context context;
private static String url = "http://cadetes.esy.es/conexion/jornadas/j01.php";
private static final String FECHA = "fecha";
private static final String HORA = "hora";
private static final String LOCAL = "nomLocal";
private static final String RLOCAL = "resulLocal";
private static final String RVISI = "resulVisitante";
private static final String VISI = "nomVisitante";
private static final String ESTADO = "estadoPartido";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.j_01_list, container, false);
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(ListActivity activity) {
Log.i("1", "Called");
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Iniciando....");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.jornadas_row,
new String[]{FECHA, HORA, LOCAL, RLOCAL, VISI, ESTADO}, new int[]
{R.id.tv_fecha, R.id.tv_hora, R.id.tv_local, R.id.tv_result, R.id.tv_visitante, R.id.tv_espacio});
setListAdapter(adapter);
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vfecha = ("Fecha: " + c.getString(FECHA));
String vhora = ("Hora: " + c.getString(HORA));
String vlocal = c.getString(LOCAL);
String vrlocal = (c.getString(RLOCAL) + (" - " + c.getString(RVISI)));
String vrvisi = c.getString(RVISI);
String vvisi = c.getString(VISI);
String vestado = c.getString(ESTADO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(FECHA, vfecha);
map.put(HORA, vhora);
map.put(LOCAL, vlocal);
map.put(RLOCAL, vrlocal);
map.put(RVISI, vrvisi);
map.put(VISI, vvisi);
map.put(ESTADO, vestado);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
}
I have an app with three fragments which I need to Asynctask every swipe. But it seems that the Asynctask runs only on the opening of the app. But when it's already created, only the first and third fragment functions well when it comes to AsyncTask the second doesn't change when I update the database.
This is my MainActivity.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
/**
* Created by Lemueloodle on 2/12/14.
*/
public class MainActivity extends FragmentActivity{
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.viewPager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("FirstFragment").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("SecondFragment").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("ThirdFragment").setTabListener(tabListener));
}
}
This is my TabPagerAdapter
package com.example.RadarOperationMonitoringSystem;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Lemueloodle on 2/12/14.
*/
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch(i) {
case 0:
return new FirstFragment();
case 1:
return new SecondFragment();
case 2:
return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3; //No of Tabs
}
}
This is my FirstFragment.java
package com.example.RadarOperationMonitoringSystem;
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.TextView;
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View first = inflater.inflate(R.layout.first_frag, container, false);
// get the listview
((TextView)first.findViewById(R.id.textView)).setText("SecondFragment");
return first;
}
}
SecondFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SecondFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/networkstatus.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_NETSTAT1 = "netlink_stats1";
private static final String TAG_FORECAST1 = "forcasting_stats1";
private static final String TAG_MDSI1 = "pagasa_mdsi_stats1";
private static final String TAG_PNOAH1 = "projectnoah_stats1";
....so on
String site1 = "";
String netstat1 = "";
String forecast1 = "";
String mdsi1 = "";
String pnoah1 = "";
.....so on
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View second = inflater.inflate(R.layout.second_frag, container, false);
((TextView)second.findViewById(R.id.textView)).setText("SecondFragment");
return second;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// We set clear listener
new GetContactsb().execute();
}
public class GetContactsb extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler2.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
netstat1 = c.getString(TAG_NETSTAT1);
forecast1 = c.getString(TAG_FORECAST1);
mdsi1 = c.getString(TAG_MDSI1);
pnoah1 = c.getString(TAG_PNOAH1);
..so on
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_NETSTAT1, netstat1);
contact.put(TAG_FORECAST1, forecast1);
contact.put(TAG_MDSI1, mdsi1);
contact.put(TAG_PNOAH1, pnoah1);
...so on
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item2, new String[] { TAG_SITENAME1,TAG_SITENAME2,TAG_SITENAME3,TAG_SITENAME4,
TAG_SITENAME5,TAG_SITENAME6,TAG_SITENAME7},
new int[] { R.id.sitename1, R.id.sitename2, R.id.sitename3, R.id.sitename4,R.id.sitename5,
R.id.sitename6, R.id.sitename7}){
//This will change the color of the value depending on the limit given
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView netstata = (TextView) view.findViewById(R.id.netstat1);
TextView forecasta = (TextView) view.findViewById(R.id.forecast1);
TextView mdsia = (TextView) view.findViewById(R.id.pmdsi1);
TextView pnoaha = (TextView) view.findViewById(R.id.pnoah1);
....so on
//1 - Red = No link
//2 - Yellow = Delay
//3 - Green = Good
//Radar 1
//Network Link Status
if (netstat1.equals("1")){
netstata.setText("No-Link");
netstata.setTextColor(getResources().getColor(R.color.red));
}
else if(netstat1.equals("2")){
netstata.setText("Delay");
netstata.setTextColor(getResources().getColor(R.color.yellow));
}
else if(netstat1.equals("3")){
netstata.setText("Good");
netstata.setTextColor(getResources().getColor(R.color.green));
}
...so on to Radar 7
return view;
};
};
// updating listviews
setListAdapter(adapter);
}
}
}
ThirdFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ThirdFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/energyreadings.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_FREQUENCY1 = "Frequency1";
private static final String TAG_ACCURRENT1 = "AC_Voltage1";
private static final String TAG_ACVOLTAGE1 = "AC_Current1";
private static final String TAG_FSTAT1 = "Flimitstat1";
private static final String TAG_VSTAT1 = "Vlimitstat1";
private static final String TAG_CSTAT1 = "Climitstat1";
...so on
// contacts JSONArray
JSONObject c = null;
String site1 = "";
String freq1 = "";
String curr1 = "";
String volts1 = "";
String fstat1 = "";
String vstat1 = "";
String cstat1 = "";
.. so on
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View third = inflater.inflate(R.layout.third_frag, container, false);
((TextView)third.findViewById(R.id.textView)).setText("ThirdFragment");
return third;
}
public void StartProgress() {
new GetContactsc().execute();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// We set clear listener
new GetContactsc().execute();
}
public class GetContactsc extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler3 sh = new ServiceHandler3();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler3.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
freq1 = c.getString(TAG_FREQUENCY1);
curr1 = c.getString(TAG_ACCURRENT1);
volts1 = c.getString(TAG_ACVOLTAGE1);
fstat1 = c.getString(TAG_FSTAT1);
vstat1 = c.getString(TAG_VSTAT1);
cstat1 = c.getString(TAG_CSTAT1);
...so on
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_FREQUENCY1, freq1);
contact.put(TAG_ACCURRENT1, curr1);
contact.put(TAG_ACVOLTAGE1, volts1);
contact.put(TAG_FSTAT1, fstat1);
contact.put(TAG_VSTAT1, vstat1);
contact.put(TAG_CSTAT1, cstat1);
...so on
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_SITENAME1, TAG_FREQUENCY1, TAG_ACCURRENT1,
TAG_ACVOLTAGE1,TAG_SITENAME2, TAG_FREQUENCY2, TAG_ACCURRENT2,
TAG_ACVOLTAGE2,TAG_SITENAME3, TAG_FREQUENCY3, TAG_ACCURRENT3,
TAG_ACVOLTAGE3, TAG_SITENAME4, TAG_FREQUENCY4, TAG_ACCURRENT4,
TAG_ACVOLTAGE4, TAG_SITENAME5, TAG_FREQUENCY5, TAG_ACCURRENT5,
TAG_ACVOLTAGE5, TAG_SITENAME6, TAG_FREQUENCY6, TAG_ACCURRENT6,
TAG_ACVOLTAGE6, TAG_SITENAME7, TAG_FREQUENCY7, TAG_ACCURRENT7,
TAG_ACVOLTAGE7},
new int[] { R.id.sitename1, R.id.frequency1,
R.id.accurrent1, R.id.acvoltage1, R.id.sitename2, R.id.frequency2,
R.id.accurrent2, R.id.acvoltage2, R.id.sitename3, R.id.frequency3,
R.id.accurrent3, R.id.acvoltage3, R.id.sitename4, R.id.frequency4,
R.id.accurrent4, R.id.acvoltage4, R.id.sitename5, R.id.frequency5,
R.id.accurrent5, R.id.acvoltage5, R.id.sitename6, R.id.frequency6,
R.id.accurrent6, R.id.acvoltage6, R.id.sitename7, R.id.frequency7,
R.id.accurrent7, R.id.acvoltage7}){
//This will change the color of the value depending on the limit given
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView freqa = (TextView) view.findViewById(R.id.frequency1);
TextView voltsa = (TextView) view.findViewById(R.id.acvoltage1);
TextView curra = (TextView) view.findViewById(R.id.accurrent1);
... so on
//Radar 1
if (fstat1.equals("1")){
freqa.setTextColor(getResources().getColor(R.color.green));
}
else if(fstat1.equals("2")){
freqa.setTextColor(getResources().getColor(R.color.red));
}
if(vstat1.equals("1")){
voltsa.setTextColor(getResources().getColor(R.color.green));
}
else if(vstat1.equals("2")){
voltsa.setTextColor(getResources().getColor(R.color.red));
}
if(cstat1.equals("1")){
curra.setTextColor(getResources().getColor(R.color.green));
}
else if(cstat1.equals("2")){
curra.setTextColor(getResources().getColor(R.color.red));
}
... so on to Radar 7
return view;
};
};
// updating listviews
setListAdapter(adapter);
}
}
}
I had the same problem like u. I think that problem is because ViewPager saves states of last and next pager, and building them before they come. Try setting tab.setOffscreenPageLimit(0). By doing that u may encounter problem that when ever u swipe pages, pages will be rebuild.