TabLayout not properly displaying fragment - android

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

Related

This error is coming while doing intent Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'?

I am getting this error when doing intent. I don't know why it is coming. I need to go to the fragment to activity. I need to go to the next activity with the api in this application. I have tried many times and I am not getting the answer.**Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'**I have given the image below How to do fragment to activity intent i am new android devloper
package com.kannada.newspaper.india.utils;
import static com.kannada.newspaper.india.Constant.EXTRA_OBJC;
import static com.kannada.newspaper.india.Constant.getApiUrl;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.kannada.newspaper.india.AppConfig;
import com.kannada.newspaper.india.Constant;
import com.kannada.newspaper.india.MainActivity;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.ActivityCategoryDetail;
import com.kannada.newspaper.india.adapters.GalleryAdapter;
import com.kannada.newspaper.india.model.Category;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private Call<CallbackHome> callbackCall = null;
SharedPref sharedPref;
private View root_view;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
private GalleryAdapter adapterCategory;
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
private Category category;
public FragmentCategory() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
requestAction();
category = (Category) getActivity().getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
// Inflate the layout for this fragment
root_view = inflater.inflate(R.layout.fragment_phones,container,false);
((TextView) root_view.findViewById(R.id.txt_title_category)).setText(getResources().getString(R.string.home_title_category));
return root_view;
}
private void requestAction() {
new Handler().postDelayed(this::requestHomeData, Constant.DELAY_TIME);
}
private void requestHomeData() {
this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
private void displayCategory(List<Category> list) {
GridView gridView = (GridView) root_view.findViewById(R.id.gridHolder);
adapterCategory = new GalleryAdapter(getActivity(), list);
gridView.setAdapter(adapterCategory);
GalleryAdapter.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
});
LinearLayout lyt_category = root_view.findViewById(R.id.lyt_category);
if (list.size() > 0) {
// lyt_category.setVisibility(View.VISIBLE);
} else {
// lyt_category.setVisibility(View.GONE);
}
}
}
GalleryAdapter adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
public static void setOnItemClickListener(Object o) {
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.category_name);
ImageView imageView = view.findViewById(R.id.category_image);
// prdId.setText(prdId.toString());
Picasso.get()
.load(getApiUrl + "/upload/category/" + mensWears.get(i).category_image())
.placeholder(R.drawable.ic_thumbnail)
.into(imageView);
prdId.setText(mensWears.get(i).getItemName());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
You cannot put Object type in putExtra , it has to be either serailized, string, double and other primitive type.
You can do like this:
Category category = (Category)adapter.getItemAtPosition(pos);
or this should also work:
Category category = (Category) obj
then,
intent.putExtra(EXTRA_OBJC,category)
Note: Your Category class should implement parcelable or serilizable to be passed as an intent.
public class Category implements Serializable {
..........}

GridView won't display images

Is there any way to have my app load all of the pictures that are visible on the screen on its own and without me having to rotate the device or swipe? I've noticed it works with some sizes and not with others (but I need the larger size that it is at now). Also, App doesn't work if I don't have the two sets of placeholder images (no clue why). Thanks in advance!
Here is my Image Adapter:
package tk.talcharnes.popularmovies;
import android.content.Context; import android.view.View; import
android.view.ViewGroup; import android.widget.BaseAdapter; import
android.widget.GridView; import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/** * Created by Tal on 2/24/2016. */ public class ImageAdapter
extends BaseAdapter { // private static String[] desc = new
String[9];
private static String[] desc = {
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg"
};
private static String[] imageArray = getDesc();
private Context mContext;
//private String[] asc = new String[PostersFragment.getMovieModelListLength()];
private static String[] asc = {};
public ImageAdapter(){
}
public int getCount() {
try{
return imageArray.length;}
catch(NullPointerException e){
e.printStackTrace();
return 0;
}
}
public ImageAdapter(Context c) {
mContext = c;
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return imageArray[position];
}
// create a new ImageView for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
int pixels = (int) (mContext.getResources().getDisplayMetrics().density + 0.5f);
imageView.setLayoutParams(new GridView.LayoutParams(185*pixels, 277*pixels));
convertView = imageView;
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(imageArray[position])
.placeholder(R.drawable.sample_0)
// .resize(185,277)
.into(imageView);
//imageView.setImageResource(Integer.parseInt(imageArray[position]));
return imageView;
}
public static String[] getAsc() {
return asc;
}
public static void setAsc(String[] asc) {
ImageAdapter.asc = asc;
}
public static String[] getDesc() {
return desc;
}
public static void setImageArray(String[] arrayName){
imageArray = arrayName;
} }
And here is my fragment:
package tk.talcharnes.popularmovies;
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.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
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.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class PostersFragment extends Fragment {
private static List<MovieModel> movieModelList;
private static int movieModelListLength;
GridView gridView;
private String done = null;
ImageAdapter adapter;
public PostersFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
FetchPostersTask fetchPostersTask = (FetchPostersTask) new FetchPostersTask().execute();
// should find gridview on the view which you are creating
gridView = (GridView) view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getContext()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getContext(), "You clicked " + movieModelList.get(position).getTitle() ,
Toast.LENGTH_SHORT).show();
}
});
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private final String BASE_URL = "https://api.themoviedb.org/3/";
private String middle_section = "discover/movie?sort_by=popularity.desc&api_key=";
private String jSonUrl = BASE_URL + middle_section + BuildConfig.MOVIE_DB_API_KEY;
//Get movie posters and data
public class FetchPostersTask extends AsyncTask<Void,Void,Void> {
private final String LOG_TAG = FetchPostersTask.class.getSimpleName();
//will contain raw Json data
String posterJsonString = null;
public Void parseMovieJson()
throws JSONException{
JSONObject jsonParentObject = new JSONObject(posterJsonString);
JSONArray movieJSonArray = jsonParentObject.getJSONArray("results");
movieModelList = new ArrayList<>();
for(int i = 0; i < movieJSonArray.length(); i++){
JSONObject movieJsonObject = movieJSonArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setTitle(movieJsonObject.getString("title"));
movieModel.setOverview(movieJsonObject.getString("overview"));
movieModel.setPoster_path(movieJsonObject.getString("poster_path"));
movieModel.setRelease_date(movieJsonObject.getString("release_date"));
movieModel.setVote_average(movieJsonObject.getString("vote_average"));
movieModelListLength++;
movieModelList.add(movieModel);
}
return null;
}
#Override
protected Void doInBackground(Void ...params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//
//will contain raw Json data
// String posterJsonString = null;
try{
//open connection to api
URL url = new URL(jSonUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//read input into string
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream == null){
//nothing else to do in this case
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine())!= null){
buffer.append(line + "\n");
}
if(buffer.length()==0){
//nothing here, don't parse
return null;
}
posterJsonString = buffer.toString();
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
Log.e(LOG_TAG, "Error", e);
return null;
}
finally {
if(urlConnection != null){
urlConnection.disconnect();
}
if(reader != null){
try{
reader.close();
}
catch (final IOException e){
Log.e(LOG_TAG,"Error closing stream", e);
}
}
}
try{
parseMovieJson();;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//ImageAdapter.setAsc(movieModelList.);
String[] asc = new String[movieModelList.size()];
for(int i = 0; i < asc.length; i++){
asc[i]=(getMovieModelList().get(i).getPoster_path());
//ImageAdapter.setAsc(asc);
}
adapter.setImageArray(asc);
}
}
public static List<MovieModel> getMovieModelList(){
return movieModelList;
}
public static int getMovieModelListLength(){
return movieModelListLength;
}
}
I believe this last piece should be last bit of needed code if at all which is the layout:
<FrameLayout 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=".PostersFragment">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:gravity="center"
android:horizontalSpacing="0dp"
android:verticalSpacing="0dp"
android:layout_margin="0dp"
/>
</FrameLayout>
Sorry in advance if code is a little clunky I am new programmer and have commented out a few things just to make sure I have them available if needed later. Thanks in advance again :D
Update: When I try to put in code: adapter.notifyDataSetChange(); after adapter.setImageArray(asc); I get this error code:
FATAL EXCEPTION: main
Process: tk.talcharnes.popularmovies, PID: 6558
java.lang.NullPointerException: Attempt to invoke virtual method 'void tk.talcharnes.popularmovies.ImageAdapter.notifyDataSetChanged()' on a null object reference
at tk.talcharnes.popularmovies.PostersFragment$FetchPostersTask.onPostExecute(PostersFragment.java:171)
at tk.talcharnes.popularmovies.PostersFragment$FetchPostersTask.onPostExecute(PostersFragment.java:70)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5290)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
I did get a similar error code previously which was a null pointer error for an array I had which somehow got fixed when I set the array to the array I have named desc, and then I had the postersfragment change immagearray to be asc array once it was done with asynctask. No idea why that stopped the error and pretty much fixed it though.
Call notifyDataSetChanged on your adapter when you add items like this
yourAdapter.notifyDataSetChanged();
(you can do this at the end of onPostExecute() method)

Custom ListView with Asynctask not working in Fragment

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);

Blank ListView in Android

I'm making a parse json app and i've got an issue !
I've got these codes :
Temps.java :
package model;
public class Temps {
private String direction;
private String ligne;
private String temps;
public Temps() {
}
public Temps(String direction, String ligne, String temps) {
this.direction = direction;
this.ligne = ligne;
this.temps = temps;
}
public String getDirection() {
return direction;
}
public void setDirection(String thumbnailUrl) {
this.direction = thumbnailUrl;
}
public String getTemps() {
return temps;
}
public void setTemps(String temps) {
this.temps = temps;
}
public String getLigne() {
return ligne;
}
public void setLigne(String ligne) {
this.ligne = ligne;
}
}
TempsActivity.java :
package activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
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 com.example.pierre.tan.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import adapter.CustomListAdapterTemps;
import app.AppController;
import model.Temps;
public class TempsActivity extends ActionBarActivity {
private Toolbar mToolbar;
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private List<Temps> directionList = new ArrayList<Temps>();
private ListView listView2;
private CustomListAdapterTemps adapter;
private SwipeRefreshLayout swipeLayout;
private Menu menu;
private MenuInflater inflater;
HashMap<String, String> lieumap = new HashMap<String, String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_temps, container, false);
// Inflate the layout for this fragment
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
System.out.println(intent.getExtras().getString("text") + " Test Test ");
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(getParent(), directionList);
listView2.setAdapter(adapter);
// Showing progress dialog before making http request
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Toast.makeText(getApplication(), "Rechargement...", Toast.LENGTH_SHORT).show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
swipeLayout.setRefreshing(false);
}
});
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_search) {
String title = getString(R.string.app_name);
Fragment fragment = null;
fragment = new ArretsFragment();
title = "Rechercher";
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temps);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(this, directionList);
listView2.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
}
And CustomListViewAdapterTemps.java :
package adapter;
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.example.pierre.tan.R;
import java.util.List;
import app.AppController;
import model.Temps;
public class CustomListAdapterTemps extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Temps> directionItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterTemps(Activity activity, List<Temps> directionItems) {
this.activity = activity;
this.directionItems = directionItems;
}
#Override
public int getCount() {
return directionItems.size();
}
#Override
public Object getItem(int location) {
return directionItems.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_rowtemps, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView direction = (TextView) convertView.findViewById(R.id.direction);
TextView ligne = (TextView) convertView.findViewById(R.id.ligne);
TextView temps = (TextView) convertView.findViewById(R.id.temps);
// getting movie data for the row
Temps m = directionItems.get(position);
// title
direction.setText(m.getDirection());
ligne.setText(m.getLigne());
temps.setText(m.getTemps());
return convertView;
}
}
I don't understand why I get a Blank ListView because the url json work and in the console we can see just the json Request with the data. If someone can help me it would be very nice!
That's because your directionList is empty. In your loops, where you parse JSON, you're creating your Temps object:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
but you're not adding them to your directionsList. Add this line just after the above:
directionList.add(temps);
Hi i think that you are not adding your response to the list, please try this:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
directionList.add(temps);

AsyncTask is not functioning on my second fragment connected to Mysql database on swipe

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.

Categories

Resources