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)
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 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
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);
I have a Fragment called User Management where I collect data from a server and display it in a ListView. It's also refreshable via SwipeRefreshLayout.
What happens is, if I get data on 1-4 users, it displays the data correctly. However, if I get data on more than 4 users, it displays the first 4 correctly, and instead of the fifth, it's the first one again, instead of the 6th, it's the second one and so on and so on.
I've tried everything I could think of, the adapter is getting the data correctly, the ListView is getting the adapter correctly, but for some reason, it peaks at 4 users displayed, and simply repeats them after that (the funny thing is, if I add a user and then refresh, it simply repeats the next user one more time in the list, so it's definitely aware of the change in user number)
Can you help me finding the problem?
The java class:
package com.softwarenation.jetfuel.fragments.userManagement;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.softwarenation.jetfuel.R;
import com.softwarenation.jetfuel.activities.MainActivity;
import com.softwarenation.jetfuel.fragments.Stations;
import com.softwarenation.jetfuel.managers.JetfuelManager;
import com.softwarenation.jetfuel.managers.StatusManager;
import com.softwarenation.jetfuel.managers.UserManager;
import com.softwarenation.jetfuel.utility.Global;
import com.softwarenation.jetfuel.utility.GlobalConnection;
import com.softwarenation.jetfuel.utility.users.User_pictures;
import com.softwarenation.jetfuel.utility.users.Users_mana;
import org.nicktate.projectile.Method;
import org.nicktate.projectile.Projectile;
import org.nicktate.projectile.StringListener;
import java.io.InputStream;
import java.util.ArrayList;
public class UserManagement extends Fragment {
private SwipeRefreshLayout swipeRefreshLayout;
//private View refreshView;
private Global font = new Global();
private ListView listView;
private ArrayList<User_pictures> pictureses = new ArrayList<User_pictures>();
private static boolean isfirst = false;
private PullToRefreshListView pullToRefreshView;
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**---------------------------------------------------------------------------------------------*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_usermanagemnet, container, false);
listView = (ListView)rootView.findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
// refreshView = (View) rootView.findViewById(R.id.swipe);
//First time, we get the data from a server, then only display that data until the user calls for a refresh
if(!StatusManager.getInstance().getUsermStatus()){
UsersTask usersTask = new UsersTask();
usersTask.execute();
}else{
setContent();
}
Button addUser = (Button)rootView.findViewById(R.id.addUser_button);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new AddUser();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
// Set a listener to be invoked when the list should be refreshed.
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.e("start","onRefresh");
new GetDataTask().execute();
}
}
);
/* pullToRefreshView = (PullToRefreshListView)rootView.findViewById(R.id.pull_to_refresh_listview);
pullToRefreshView.bringToFront();
pullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});*/
return rootView;
}
public void setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener){
swipeRefreshLayout.setOnRefreshListener(listener);
}
public boolean isRefreshing(){
return swipeRefreshLayout.isRefreshing();
}
public void setRefreshing(boolean refreshing){
swipeRefreshLayout.setRefreshing(refreshing);
}
public SwipeRefreshLayout getSwipeRefreshLayout(){
return swipeRefreshLayout;
}
//on refresh, get new data from the server
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... voids) {Log.e("start","GetDataTask");
UsersTask usersTask = new UsersTask();
usersTask.execute();
return new String[0];
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
// pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
MainActivity.setBackDisabled(false);
Log.e("GetDataTask","completed");
}
}
private class SampleItem {
public String id;
public String title;
public String username;
public String groupName;
public int userPicture;
public int editPicture;
public int dPicture;
public String activated;
public SampleItem(String id, String title, String username, String groupName, int userPicture, int editPicture, int dPicture, String activated ) {
this.id = id;
this.title = title;
this.username = username;
this.groupName = groupName;
this.userPicture = userPicture;
this.editPicture = editPicture;
this.dPicture = dPicture;
this.activated = activated;
}
}
static class ViewHolder {
private String checkBox;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private RelativeLayout relativeLayout2;
public void setCheckBox(String checkBox) {
this.checkBox = checkBox;
}
public void setLinearLayout(LinearLayout linearLayout) {
this.linearLayout = linearLayout;
}
public void setRelativeLayout(RelativeLayout relativeLayout) {
this.relativeLayout = relativeLayout;
}
public void setRelativeLayout2(RelativeLayout relativeLayout2) {
this.relativeLayout2 = relativeLayout2;
}
public LinearLayout getLinearLayout() {
return linearLayout;
}
public RelativeLayout getRelativeLayout() {
return relativeLayout;
}
public RelativeLayout getRelativeLayout2() {
return relativeLayout2;
}
public RelativeLayout getCheckBox() {
return relativeLayout;
}
}
public class SampleAdapter extends ArrayAdapter<SampleItem> {
final ViewHolder holder = new ViewHolder();
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
ImageView userPicture = (ImageView)convertView.findViewById(R.id.userpicture);
userPicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
TextView title = (TextView)convertView.findViewById(R.id.user_name);
font.setFont(title, 3, getActivity());
title.setText(getItem(position).title);
TextView username = (TextView)convertView.findViewById(R.id.username);
font.setFont(username, 2, getActivity());
username.setText(getItem(position).username);
TextView groupname = (TextView)convertView.findViewById(R.id.groupName);
font.setFont(groupname, 2, getActivity());
groupname.setText(getItem(position).groupName);
ImageView useredit = (ImageView)convertView.findViewById(R.id.editbutton);
useredit.setImageDrawable(getResources().getDrawable(getItem(position).editPicture));
useredit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new EditProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
/**---------------*/
ImageView userdelate = (ImageView)convertView.findViewById(R.id.deletebutton);
userdelate.setImageDrawable(getResources().getDrawable(getItem(position).dPicture));
holder.setLinearLayout((LinearLayout)convertView.findViewById(R.id.lin_show_profile));
//LinearLayout show = (LinearLayout)convertView.findViewById(R.id.lin_show_profile);
holder.getLinearLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new ShowProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
//
holder.setRelativeLayout((RelativeLayout)convertView.findViewById(R.id.delate_user));
//RelativeLayout delete_user = (RelativeLayout)convertView.findViewById(R.id.delate_user);
holder.getRelativeLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogStop("Are you sure?", getItem(position).username, getActivity(), getItem(position).id);
}
});
//
//holder.setCheckBox(getItem(position).activated);
//
/**---------------*/
//Red or Blue background
// RelativeLayout settings = (RelativeLayout)convertView.findViewById(R.id.settingsbutton);
holder.setRelativeLayout2((RelativeLayout) convertView.findViewById(R.id.settingsbutton));
//if(getItem(position).activated.equals("false")) {
if (getItem(position).activated.equals("false")) {
holder.getLinearLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout2().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
}
//holder.setCheckBox(getItem(position).activated);
convertView.setTag(holder);
} else {
convertView.getTag();
}
return convertView;
}
}
public void DialogStop(String title, String message,Context context, final String id){
new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dialog.cancel();
DeleteTask deleteTask = new DeleteTask();
deleteTask.execute(id);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private class DeleteTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
String response = null;
try {
response = new GlobalConnection().DELETE( getString(R.string.apicdeleteuser) + params[0].toString() );
Log.v("response", response + "");
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
Log.v("response", response + "");
}
}
private class UsersTask extends AsyncTask<String, Void, ArrayList<Users_mana>> {
#Override
protected ArrayList<Users_mana> doInBackground(String... strings) {
//Users_mana users = null;
String response = null;
ArrayList<Users_mana> users_manas = null;
try{Log.e("start","GET via GlobalConnection()");
response = new GlobalConnection().GET( getString(R.string.apiusers));
users_manas = new Gson().fromJson(response, new TypeToken<ArrayList<Users_mana>>(){}.getType());
Log.e("start","setUsers_mana");
UserManager.getInstance().setUsers_mana(users_manas);
}catch (Exception e){
Log.e("response error", e.getMessage().toString());
}
return users_manas;
}
#Override
protected void onPostExecute(ArrayList<Users_mana> response) {
if(!response.isEmpty()) {Log.e("start","setContent()");
setContent();
StatusManager.getInstance().setUsermStatus(true);
Log.e("UsermStatus:",String.valueOf(StatusManager.getInstance().getUsermStatus()));
}
super.onPostExecute(response);
}
}
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
/*
private class PicturesTask extends AsyncTask<String, String ,String>{
#Override
protected String doInBackground(String... urls) {
//String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
for(int i = 0; i < urls.length; i++) {
if(UserManager.getInstance().getUsers_mana().get(i).photo != null) {
InputStream in = new java.net.URL(getString(R.string.jetfuel_url ) + UserManager.getInstance().getUsers_mana().get(i).username).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
pictureses.add(new User_pictures(mIcon11, UserManager.getInstance().getUsers_mana().get(i).username, UserManager.getInstance().getUsers_mana().get(i).id));
UserManager.getInstance().setUserPictureses(pictureses);
}
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(!UserManager.getInstance().getUserPictureses().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUserPictureses().size(); i++) {
Log.v("pictures", UserManager.getInstance().getUserPictureses().get(i).picture + "");
}
}
super.onPostExecute(s);
}
}
*/
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
//menu.removeItem(R.id.Station);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Station:
Fragment fragment = new Stations();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**---------------------------------------------------------------------------------------------*/
}
The xml view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue">
<Button
android:id="#+id/addUser_button"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="#string/add_user"
android:background="#drawable/button_yellow_background"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#color/blue"/>
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
Thank you!
There is a huge problem in your SampleAdapter.getView() method.
When you scroll down the View disappearing at the top of the screen is reused to be injected at the bottom. This reused View is the convertView you get as getView parameter.
As you code is, the reused view is injected with the exact same data (because if (convertView == null) { is always false when you scroll).
Images and texts are not updated.
When you scroll down, the element disappearing at the top just appears at the bottom, and so does others...
You should be doing something like:
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
// The ViewHolder constructor should handle the mapping of its views
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here you should only use holder as in:
holder.userpicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
...
}
This method looks strange, and is perhaps suspect. I don't see getUsers_mana() defined anywhere in this sample code, so I don't know if it is the problem or not. For one, you should call that 'UserManager.getInstance().getUsers_mana()' and then 'get(i)' once each and store the results in variables.
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
It is because you are not doing anything in the
else {
convertView.getTag();
}
Check here
Why we should re-assign values for a recycled convertView in getView()
You have to reassign values to the convertView with the data of the 5th roq, 6th row etc. otherwise it still contains the old data
Remove the initialization of holder on the top and just put this line of code in the beginning of getView function.
ViewHolder holder = null;
You need to re initialize holder if its null and you need to update it with latest data if its not null.
See this sample it might help you
https://github.com/erikwt/PullToRefresh-ListView
i want to read from json on url address to list view but there is noting to show.
this is my code.
main activity.
package customlistviewvolley;
import com.example.customlistviewvolley.R;
/*import java.io.IOException;
import java.io.InputStream;*/
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import customlistviewvolleyadater.CustomListAdapter;
import customlistviewvolleyapp.AppController;
import customlistviewvolleymodel.App;
public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://192.168.1.5/public_html/android/new.json";
private ProgressDialog pDialog;
private List<App> appList = new ArrayList<App>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, appList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest appReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
App app = new App();
app.setAppTitle(obj.getString("app_title"));
app.setAppImageUrl(obj.getString("app_image"));
app.setRatingBar(((Number) obj.get("app_rating"))
.doubleValue());
app.setAppCreator(obj.getString("app_creator"));
app.setAppCase(obj.getString("app_case"));
// adding app to app array
appList.add(app);
} 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());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(appReq);
}
/* JSONObject obj1 = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj1.getJSONArray("apps");
//ArrayList<HashMap<String, String>> formList= new ArrayList<HashMap<String, String>>();
// HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
try {
JSONObject obj = m_jArry.getJSONObject(i);
App app = new App();
app.setAppTitle(obj.getString("app_title"));
app.setAppImageUrl(obj.getString("app_image"));
app.setRatingBar(((Number) obj.get("rating_bar"))
.doubleValue());
app.setAppCreator(obj.getString("app_creator"));
app.setAppCase(obj.getString("app_case"));
// adding movie to movies array
appList.add(app);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Same way for other value...
}*/
/*public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("jsonfile.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
} */
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
custom adapter.
package customlistviewvolleyadater;
import com.example.customlistviewvolley.R;
import java.util.List;
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.RatingBar;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import customlistviewvolleyapp.AppController;
import customlistviewvolleymodel.App;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<App> appItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<App> appItems) {
this.activity = activity;
this.appItems = appItems;
}
#Override
public int getCount() {
return appItems.size();
}
#Override
public Object getItem(int location) {
return appItems.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.top_new_free, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView appImage = (NetworkImageView) convertView
.findViewById(R.id.app_image);
TextView appTitle = (TextView) convertView.findViewById(R.id.app_title);
TextView appCase = (TextView) convertView.findViewById(R.id.app_case);
TextView appCreator = (TextView) convertView.findViewById(R.id.app_creator);
RatingBar ratingBar = (RatingBar) convertView.findViewById(R.id.app_rating_bar);
// getting app data for the row
App app = appItems.get(position);
// app image
appImage.setImageUrl(app.getAppImageUrl(), imageLoader);
// title
appTitle.setText(app.getAppTitle());
// app creator
appCreator.setText( app.getAppCreator());
// appCase
appCase.setText(app.getAppCase());
// rating bar
ratingBar.setNumStars((int) app.getRatingBar());
return convertView;
}
}
app controller.
package customlistviewvolleyapp;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import customlistviewvolleyutil.LruBitmapCache;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
app.
package customlistviewvolleymodel;
public class App {
private String appTitle, appImageUrl, appCreator;
private double ratingBar;
private String appCase;
public App() {
}
public App(String appName, String appImageUrl, String appCreator, double ratingBar,
String appCase) {
this.appTitle = appName;
this.appImageUrl = appImageUrl;
this.appCreator = appCreator;
this.ratingBar = ratingBar;
this.appCase = appCase;
}
public String getAppTitle() {
return appTitle;
}
public void setAppTitle(String name) {
this.appTitle = name;
}
public String getAppImageUrl() {
return appImageUrl;
}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;
}
public String getAppCreator() {
return appCreator;
}
public void setAppCreator(String appCreator) {
this.appCreator = appCreator;
}
public double getRatingBar() {
return ratingBar;
}
public void setRatingBar(double ratingBar) {
this.ratingBar = ratingBar;
}
public String getAppCase() {
return appCase;
}
public void setAppCase(String appCase) {
this.appCase = appCase;
}
}
here is my cache code .
` `package customlistviewvolleyutil;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
my main activity xml .
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:padding="5dip"
android:clipToPadding="false"
android:listSelector="#drawable/list_row_selector" />
</RelativeLayout>
my rows here .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/app_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp" />
<!-- App(movie) Title -->
<TextView
android:id="#+id/app_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/app_image"
android:layout_toLeftOf="#+id/app_image"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- App Creator -->
<TextView
android:id="#+id/app_creator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/app_image"
android:layout_toLeftOf="#+id/app_image"
android:textSize="#dimen/creator"
android:layout_marginTop="1dip"
android:textStyle="bold" />
<!-- Type Free or NotFree or Installed -->
<TextView
android:id="#+id/app_case"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:textColor="#color/year"
android:textSize="#dimen/type" />
<!-- Rating Bar -->
<RatingBar
android:id="#+id/app_rating_bar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/app_image"
android:layout_below="#+id/app_creator"
android:stepSize="0.5" />
</RelativeLayout>
plz help me to fix it.
You should access localhost sites in such a way:
http://localhost:8080/MyTestPage.html
Read this to get further information:
http://www.androidref.com//index.html#LocalBrowser