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);
Related
Please help with the following problems, the problem is that the data does not want to appear in the fragment home, even though the internet condition is on
My HomeFragment code:
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
My RecyclerAdapter code:
package untag.adproj.lestari.lestari.Home;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Data> listdata;
private Activity activity;
private Context context;
public RecyclerAdapter(Activity activity, ArrayList<Data> listdata) {
this.listdata = listdata;
this.activity = activity;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_home_list, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.mImage.setImageResource(listdata.get(position).getThubnail());
holder.id.setText(listdata.get(position).getId());
holder.judul.setText(listdata.get(position).getJudul());
holder.harga.setText(listdata.get(position).getHarga());
final ViewHolder x=holder;
Glide.with(activity)
.load(listdata.get(position).getThubnail())
.into(holder.thumbnail);
holder.id.setVisibility(View.GONE);
}
#Override
public int getItemCount() {
return listdata.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private CardView cv;
private TextView id,judul,harga;
private ImageView thumbnail;
public ViewHolder(View v) {
super(v);
cv=(CardView)v.findViewById(R.id.card_view);
id=(TextView)v.findViewById(R.id.id);
judul=(TextView)v.findViewById(R.id.judul);
harga=(TextView)v.findViewById(R.id.harga);
thumbnail=(ImageView)v.findViewById(R.id.thumbnail);
}
}
}
My Data code:
package untag.adproj.lestari.lestari.Home;
public class Data {
private String id;
private String judul;
private String harga;
private String thubnail;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getThubnail() {
return thubnail;
}
public void setThubnail(String thubnail) {
this.thubnail = thubnail;
}
}
My code refresh comes from Youtube
but in the tutorial it does not use fragment, please anyone help me
You have a wrong point, that is not update the list of recycler view, the list you add value in code listdata.add(item); belong to your fragment
Please add below method in your adapter
public void addData(List<Data> data) {
listdata.addAll(data);
notifyDataSetChanged();
}
And edit AmbilData function as below
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.addData(listdata);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private ArrayList<Data> tempList;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
tempList = new ArrayList<Data>();
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
tempList.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
listdata.clear();
listdata.addAll(tempList);
recyclerAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
Use temp list then addAll() method then call notifyDataSetChanged() method.
If you want to notify your adapter from a loop then you should go for notifyItemInserted() otherwise keep the notifyDataSetChanged() outside of the loop.
Like this;
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyItemInserted(listdata.size()-1); //To update the recyclerview one by one from a loop.
} catch (JSONException e) {
}
}
// OR
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.notifyDataSetChanged(); //To update the whole recyclerview in one shot
Everything works, but after I check the log it shows:
"E/RecyclerView: No adapter attached; skipping layout ".
My home fragment code:
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
I saw another question similar to this, that said to attach the adapter before running other threads but I don't believe I have any other threads running in this activity.
You start a new thread in this line:
new LoadLatestNews().execute(Constant.URL_LATEST);
and it is executed before control reaches:
recyclerView.setAdapter(adapterRecent);
This however should not be the problem you have since AsyncTask publishes to the UIThread.
Instead you should set an empty adapter in onCreateView and update it with adapterRecent.notifyDataSetChanged(); once you have loaded your data.
I have simply used a custom list inside a fragment.I have retrieved those data from api using volley.It shows following error.I am getting any idea to resolve this,Can somebody please help me.
java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.example.user.ekta.AppController.getImageLoader()' on a null object reference
at com.example.user.ekta.MyBookAdapter.<init>(MyBookAdapter.java:25)
at com.example.user.ekta.FullInfoTabFragment.onCreateView(FullInfoTabFragment.java:85).
This is my Fragment class
package com.example.user.ekta;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FullInfoTabFragment extends Fragment {
private static final String EXTRA_SRORT_CARD_MODEL = "EXTRA_SRORT_CARD_MODEL";
// String transitionTag;
private SportCardModel sportCardModel;
private Toolbar toolbar;
private ImageView ivPhoto;
private static final String TAG = FullInfoTabFragment.class.getSimpleName();
private static final String url = "http://myeducationhunt.com/public/schools";
private ProgressDialog pDialog;
private List<MyBook> ourBooksListItems = new ArrayList<MyBook>();
private ListView listView;
private MyBookAdapter adapter;
public static FullInfoTabFragment newInstance(SportCardModel sportCardModel) {
FullInfoTabFragment fragment = new FullInfoTabFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
sportCardModel = getArguments().getParcelable(EXTRA_SRORT_CARD_MODEL);
}
if (savedInstanceState != null) {
sportCardModel = savedInstanceState.getParcelable(EXTRA_SRORT_CARD_MODEL);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_full_info, container, false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
ivPhoto = (ImageView) view.findViewById(R.id.ivPhoto);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MyBookAdapter(getActivity(), ourBooksListItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// OurSchool ourSchool = new OurSchool();
// Intent i = new Intent(getContext(), SchoolDetails.class);
// i.putExtra("id", ourSchoolsListItems.get(position).schoolId);
// i.putExtra("name", ourSchoolsListItems.get(position).schoolName);
// i.putExtra("location", ourSchoolsListItems.get(position).schoolLocation);
// i.putExtra("logo", ourSchoolsListItems.get(position).schoolLogo);
// i.putExtra("email", ourSchoolsListItems.get(position).schoolEmail);
// i.putExtra("website", ourSchoolsListItems.get(position).schoolWebsite);
// i.putExtra("created_at", ourSchoolsListItems.get(position).createdAt);
// i.putExtra("updated_at", ourSchoolsListItems.get(position).updatedAt);
// startActivity(i);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading…");
pDialog.show();
// Creating volley request obj
JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyBook myBook = new MyBook();
myBook.bookName = obj.getString("name");
myBook.bookAuthor = obj.getString("location");
myBook.bookCover= obj.getString("logo");
// adding schools to ourSchool list
ourBooksListItems.add(myBook);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar.setTitle(sportCardModel.getSportTitle());
toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), sportCardModel.getBackgroundColorResId()));
ivPhoto.setImageResource(sportCardModel.getImageResId());
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
super.onSaveInstanceState(outState);
}
static class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
private Drawable mDivider;
/**
* Default divider will be used
*/
public DividerItemDecoration(Context context) {
final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
mDivider = styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
/**
* Custom divider will be used
*/
public DividerItemDecoration(Context context, int resId) {
mDivider = ContextCompat.getDrawable(context, resId);
}
#Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
}
And this is my adapter class
package com.example.user.ekta;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
/**
* Created by user on 11/27/2016.
*/
public class MyBookAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<MyBook> ourbooksList;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MyBookAdapter(Activity activity, List<MyBook> ourbooksListsList) {
this.activity = activity;
this.ourbooksList = ourbooksListsList;
}
#Override
public int getCount() {
return ourbooksList.size();
}
#Override
public Object getItem(int location) {
return ourbooksList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_books, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView bookCover = (NetworkImageView) convertView
.findViewById(R.id.bookCover);
TextView bookName = (TextView) convertView.findViewById(R.id.bookName);
TextView boookAuthor = (TextView) convertView.findViewById(R.id.bookAuthor);
MyBook m = ourbooksList.get(position);
bookCover.setImageUrl(m.getBookCover(), imageLoader);
bookName.setText("Name: " + m.getBookName());
boookAuthor.setText("Address: " + String.valueOf(m.getBookAuthor()));
return convertView;
}
}
AppController.getInstance() is returning null, you have not initialized your Appcontroller.
If AppController extends your application, then you have to change your manifest
android:name= "path to AppController" in app section.
I have an activity with a tablayout. When the activity is created, the viewpageradapter is created and adds 3 instances of the same fragment class to it. Then, then, I set the adapter to the view pager.
I know that the fragment addition is happening correctly because my fragment executes an asyncTask and its logging statements appear in the console. For some reason, when I start the activity, I can see the app bar and the widget displaying the tabs, but the space where the fragment should appear is empty. What am I doing wrong?
This is my code:
MainActivity
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final String LIST_TAG = MovieListFragment.class.getSimpleName();
private final String DETAIL_TAG = DetailActivityFragment.class.getSimpleName();
private final String POPULAR = "POPULAR";
private final String HIGHEST_RATED = "HIGHEST RATED";
private final String FAVOURITE = "FAVOURITE";
private boolean mTwoPane;
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//We check if the layout selected has two fragments
if (findViewById(R.id.movie_detail_container) != null) {
//If it has two, we update our member variable
mTwoPane = true;
/*If the activity has been recently created, we replace the placeholder
frameview with the actual detail fragment
*/
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(
R.id.movie_detail_container,
new DetailActivityFragment(),
DETAIL_TAG
).commit();
}
} else {
mTwoPane = false;
}
mViewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(mViewPager);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*If it's the first time we launch the activity, we create a fragment
and tag it so we have a reference to find it later
*/
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
MovieListFragment popular = new MovieListFragment();
MovieListFragment highestRated = new MovieListFragment();
MovieListFragment favourites = new MovieListFragment();
populateFragment(popular);
populateFragment(highestRated);
populateFragment(favourites);
adapter.addFragment(popular, POPULAR);
adapter.addFragment(highestRated, HIGHEST_RATED);
adapter.addFragment(favourites, FAVOURITE);
viewPager.setAdapter(adapter);
}
private void populateFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//We identify the option clicked and act accordingly
switch (id) {
/* Not necessary at this stage of the project. Will be
populated later.
*/
case R.id.action_settings: {
return true;
}
/* If the sort method is changed we start an asynchronous task
and fetch the appropriate movies.
*/
case R.id.sort_popularity: {
MovieListFragment.setmSortOrder("popularity.desc");
MovieListFragment movieListFragment = (MovieListFragment)
getSupportFragmentManager().findFragmentByTag(LIST_TAG);
movieListFragment.retrieveMovies();
break;
}
case R.id.sort_highest_Rating: {
MovieListFragment.setmSortOrder("vote_average.desc");
MovieListFragment movieListFragment = (MovieListFragment)
getSupportFragmentManager().findFragmentByTag(LIST_TAG);
movieListFragment.retrieveMovies();
break;
}
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position)
{
return new MovieListFragment();
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
MovieListFragment
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MovieListFragment extends Fragment {
//Defining size params for the images in the gridview
private final int IMAGE_WIDTH = 450;
private final int IMAGE_HEIGHT = 675;
private static String mSortOrder = "popularity.desc";
public final static String EXTRA_MOVIE = "com.example.android.movierating.EXTRA_MOVIE";
private final String LOG_TAG = MovieListFragment.class.getSimpleName();
MovieAdapter mMovieAdapter;
private LayoutInflater mInflater;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
// We want to add options to the Menu bar.
setHasOptionsMenu(true);
}
public static String getmSortOrder() {
return mSortOrder;
}
public static void setmSortOrder(String sortOrder) {
mSortOrder = sortOrder;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.movielist_fragment, menu);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = inflater;
// We inflate and store the rootView
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// We sotre the gridview and set a custom adapter to it. It is defined below
GridView gridView = (GridView) getActivity().findViewById(R.id.gridview);
mMovieAdapter = new MovieAdapter(
getContext(),
R.id.image_thumbnail,
new ArrayList<Movie>()
);
gridView.setAdapter(mMovieAdapter);
/* The gridView will react to a user clicking on it by creating
an intent and populating it with the movie object. That object
will provide the data necessary to display facts about the movie
*/
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = mMovieAdapter.getItem(position);
Intent detailIntent = new Intent(getActivity(), DetailActivity.class)
.putExtra(EXTRA_MOVIE, (Parcelable) movie);
startActivity(detailIntent);
}
});
return rootView;
}
public void retrieveMovies() {
if (getmSortOrder() == "popularity.desc" || getmSortOrder() == "vote_average.desc") {
FetchMoviesTask moviesTask = new FetchMoviesTask();
String sortOrderArray[] = {mSortOrder};
moviesTask.execute(sortOrderArray);
}
}
#Override
public void onStart() {
super.onStart();
retrieveMovies();
}
// Custom adapter to display Movies on a gridView
public class MovieAdapter extends ArrayAdapter<Movie> {
//Context member variable
private Context mContext;
//Constructor
public MovieAdapter(Context context, int imgViewResourceId,
ArrayList<Movie> items) {
super(context, imgViewResourceId, items);
mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
view = mInflater.inflate(R.layout.fragment_main,null);
} else {
view = convertView;
}
ImageView imageView = (ImageView) view.findViewById(R.id.image_thumbnail);
TextView textView = (TextView) view.findViewById(R.id.overlay_text);
String url = getItem(position).getUrlPath();
Picasso.with(mContext)
.load(url)
.resize(IMAGE_WIDTH,IMAGE_HEIGHT)
.centerCrop()
.into(imageView);
String movieTitle = getItem(position).getOriginalTitle();
textView.setText(movieTitle);
textView.setBackgroundColor(getResources().getColor(R.color.translucid_black));
textView.setTextColor(getResources().getColor(R.color.opaque_white));
return view;
}
}
// Nested class to fetch the Json information about the movies
public class FetchMoviesTask extends AsyncTask<String, Void, List<Movie>> {
//Log tag for debugging purposes
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
// Method to take a JSON string and return a list of Movie
// objects.
private List<Movie> parseJSONtoArrayList(String stringJSON)
throws JSONException{
// String constants and the arraylist holding the results
final String MDB_RESULTS = "results";
final String MDB_ID = "id";
final String MDB_PATH = "poster_path";
final String MDB_TITLE = "original_title";
final String MDB_SYNOPSIS = "overview";
final String MDB_RATING = "vote_average";
final String MDB_VOTE_COUNT = "vote_count";
final String MDB_RELEASE = "release_date";
List<Movie> movieArrayList = new ArrayList<>();
// We turn the results into a JSONObject and we extract the JSONObjects
// into an array of objects.
JSONObject dataJSON = new JSONObject(stringJSON);
JSONArray movieArray = dataJSON.getJSONArray(MDB_RESULTS);
/* We iterate over the array of JSONObjects, we create a new
Movie object and we append it to the arraylist holding the
results.
*/
for (int i=0; i<movieArray.length(); i++) {
// Select a JSONObject in every iteration.
JSONObject target = movieArray.getJSONObject(i);
/* Create a Movie Object by retrieving the necessary elements
of the JSONObject
*/
Movie movie = new Movie(
target.getInt(MDB_ID),
createURL(target.getString(MDB_PATH)),
target.getString(MDB_TITLE),
target.getString(MDB_SYNOPSIS),
Float.parseFloat(target.getString(MDB_RATING)),
Integer.parseInt(target.getString(MDB_VOTE_COUNT)),
target.getString(MDB_RELEASE)
);
// Once we have created our object, we add it to the arrayList
movieArrayList.add(movie);
}
return movieArrayList;
}
/* Transform a relative path provided by the API into a fully functional
URL path.
*/
private String createURL(String relativePath) {
final String BASE_IMAGE_URL = "http://image.tmdb.org/t/p/";
final String PIX_MEASURE = "w185";
return BASE_IMAGE_URL + PIX_MEASURE + relativePath;
}
#Override
protected List<Movie> doInBackground(String... params) {
// Our default sorting parameter, request declaration,
// reader and empty string
String sortMethod = params[0];
HttpURLConnection connection = null;
BufferedReader reader = null;
String moviesJSON = null;
try {
// We build the URI
final String BASE_URL =
"http://api.themoviedb.org/3/discover/movie?";
final String API_KEY = "api_key";
final String SORT = "sort_by";
String uri = Uri.parse(BASE_URL)
.buildUpon().appendQueryParameter(SORT, sortMethod)
.appendQueryParameter(API_KEY, getString(R.string.ApiKey))
.build().toString();
URL url = new URL(uri);
//Create the request and open the connection
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// Create objects to hold the results of the API call
InputStream inputStream = connection.getInputStream();
StringBuilder builder = new StringBuilder();
// If we don't receive anything, we just return
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
// We write the api call results into the string builder
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + '\n');
}
// We check that the result is not empty
if (builder.length() == 0) {
return null;
}
moviesJSON = builder.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "There was a problem fetching the movies");
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader !=null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "We found a problem while closing the reader");
e.printStackTrace();
}
}
}
try {
return parseJSONtoArrayList(moviesJSON);
} catch (JSONException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Movie> movies) {
super.onPostExecute(movies);
if (movies != null) {
// Every time we call this task, we flush the Movies in the adaptor
// And fill it up again with the results of the API call.
mMovieAdapter.clear();
Log.e(LOG_TAG, movies.toString());
mMovieAdapter.addAll(movies);
}
}
}
}
Thank you very much in advance
I'm passing a value from MainActivity.class to this fragment ResultFrag.class. In this class, it's supposed to display the places that is within the requested value from the user's current location.
The json return is correct.
I also tried to debug and display the item in the myList through Logcat and it is fine. So meaning that the json is parsed correctly and it's being added to the myList.
myAdapter = new MyAdapter(getActivity(), getTheList());
This particular line that pass the list to the custom adapter; I don't think it's getting the list from the getTheList() method. Because I tried debugging using below codes by putting it in onCreateView but it's not logging anything:
for (int b = 0; b < getTheList().size(); b++) {
Log.d("list: ", Integer.toString(b) + " : " + getTheList().get(b).getPlace());
}
Can anyone help? I've been working on this since yesterday.
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
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 java.util.Map;
public class ResultFrag extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
double latitude, longitude;
String lat, lng;
private Bundle bundle;
private String data;
private static final String TAG_URL_DISTANCE = "///remove link///";
private static final String LOG_DISTANCE = ResultFrag.class.getSimpleName();
private MyAdapter myAdapter;
private RecyclerView recyclerView;
List<GetterSetter> myList = new ArrayList<>();
private static final String TAG = ResultFrag.class.getSimpleName();
private static final int REQUEST_CODE = 1000;
Location location;
GoogleApiClient googleClient;
public ResultFrag() {
}
public void searchPlace(final String dist, final String latitude, final String longitude) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, TAG_URL_DISTANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(LOG_DISTANCE, response.toString());
try {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setId(obj.getString("id"));
getterSetter.setPlace(obj.getString("name"));
getterSetter.setDistance(obj.getInt("distance"));
myList.add(getterSetter);
}
for (int b = 0; b < getTheList().size(); b++) {
Log.d("list: ", Integer.toString(b) + " : " + getTheList().get(b).getPlace());
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "JSONException: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(LOG_DISTANCE, "Volley Error: " + error.getMessage());
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("dist", dist);
params.put("latitude", latitude);
params.put("longitude", longitude);
return params;
}
};
Volley.newRequestQueue(getContext()).add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.result_frag, container, false);
bundle = this.getArguments();
data = bundle.getString(MainActivity.option);
if (checkGooglePlayServices()) {
buildGoogleClient();
}
lat = getLatitude();
lng = getLongitude();
Log.d("radius", data);
Log.d("latitude", lat);
Log.d("longitude", lng);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
myAdapter = new MyAdapter(getActivity(), getTheList());
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
/* recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
}
})
);*/
return rootView;
}
private boolean checkGooglePlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
// Show error
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), REQUEST_CODE).show();
} else {
Toast.makeText(getContext(),
"No GPS",
Toast.LENGTH_LONG).show();
}
return false;
}
return true;
}
protected synchronized void buildGoogleClient() {
googleClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onStart() {
super.onStart();
if (googleClient != null) {
googleClient.connect();
}
}
#Override
public void onResume() {
super.onResume();
checkGooglePlayServices();
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(googleClient);
searchPlace(data, getLatitude(), getLongitude());
Toast.makeText(getContext(), getLatitude() + ", " + getLongitude(), Toast.LENGTH_LONG).show();
}
public List<GetterSetter> getTheList() {
return myList;
}
public String getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return String.valueOf(latitude);
}
public String getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return String.valueOf(longitude);
}
#Override
public void onConnectionSuspended(int i) {
googleClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
}
MyAdapter.class
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
List<GetterSetter> data = Collections.emptyList();
private LayoutInflater layoutInflater;
private Context context;
public MyAdapter (Context context, List<GetterSetter> data) {
this.context = context;
this.data = data;
layoutInflater = layoutInflater.from(context);
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.mylist, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
// Get event data
GetterSetter current = data.get(position);
holder.id.setText(current.getId());
holder.place.setText(current.getPlace());
holder.distance.setText("Distance: " + String.valueOf(current.getDistance()) + " km");
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView place;
TextView distance;
public MyViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.placeId);
place = (TextView) itemView.findViewById(R.id.name);
distance = (TextView) itemView.findViewById(R.id.distance);
}
}
}
Did you fix it in the meantime? What I see is that you actually share the list between the adapter and the Fragment. And you make changes (add items) to the list after the adapter was constructed. But you do not call notfyDatasetChanged() on the adapter. Add that call once you are done with applyting changes to the list.
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setId(obj.getString("id"));
getterSetter.setPlace(obj.getString("name"));
getterSetter.setDistance(obj.getInt("distance"));
myList.add(getterSetter);
}
myAdapter.notfyDatasetChanged()