image Gridview is not showing in fregment android - java

my image grid view is not showing ,i am using Picasso to show images on grid by using URL fetched from database i am trying to show it inside a fragment in navigation bar , when i add anything else to the fragment it shows it , the problem is just with the grid i am not getting any error though can you help pleas
this is my fragment.java code
public class event extends Fragment {
int userid ;
String START ;
private String GET_IMAGES_URL =
"http://192.168.1.107/android/v1/getimages.php";
public static final String TAG_IMAGE_URL = "URL";
private GridView gridView;
private ArrayList<String> images;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public event() {
}
public static event newInstance(String param1, String param2) {
event fragment = new event();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
userid = SharedPrefManager.getInstance(getActivity()).getUserid();
images = new ArrayList<>();
START = "";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_event, container, false);
gridView = (GridView) view.findViewById(R.id.gridview);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getActivity(), "" + position,
Toast.LENGTH_SHORT).show();
}
});
getData();
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void getData() {
final ProgressDialog loading = ProgressDialog.show(getActivity(),
"Please wait...", "Fetching data...", false, false);
StringRequest stringRequest = new StringRequest(
Request.Method.POST, GET_IMAGES_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
loading.dismiss();
showGrid(array);
} catch (JSONException e) {
loading.dismiss();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid", String.valueOf(userid));
return params;
}
};;
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void showGrid(JSONArray array){
for(int i = 0; i<array.length(); i++){
JSONObject obj = null;
try {
images.add(START + array.getString(i)+START);
} catch (JSONException e) {
e.printStackTrace();
}
}
gridView.setAdapter(new
GridViewAdapter(getActivity().getApplicationContext(),images));
}
}
my adapter class is this
public class GridViewAdapter extends BaseAdapter {
private final Context context;
ArrayList<String> urls;
// private String[] url ;
public GridViewAdapter(Context context, ArrayList<String> images) {
this.context = context;
urls =images;
}
#Override public View getView(int position, View convertView, ViewGroup
parent) {
ImageView view = (ImageView) convertView;
if (view == null) {
view = new ImageView(context);
view.setLayoutParams(new GridView.LayoutParams(85, 85));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setPadding(8, 8, 8, 8);
}
else {
view = (ImageView) convertView;
}
// Get the image URL for the current position.
String url = getItem(position);
//
// Trigger the download of the URL asynchronously into the image view.
Picasso.with(context) //
.load(url) //
.fit() //
.tag(context) //
.into(view);
return view;
}
#Override public int getCount() {
return urls.size();
}
#Override public String getItem(int position) {
return urls.get(position);
}
#Override public long getItemId(int position) {
return position;
}
}

Picasso only works if you have Internet Permission in your Manifest.

Related

RecyclerView: No adapter attached; skipping layout Problem

I'm getting the error:
RecyclerView﹕ No adapter attached; skipping layout
I checked some other answers people have given for this issue, but had no luck.
Adapter:
public class MyAdapter extends RecyclerView.Adapter<com.example.myapplication.MyAdapter.MyViewHolder> {
private Context context;
private List<HeadlineModel> headlineModelList;
public MyAdapter(Context context, List<HeadlineModel> headlineModelList) {
this.context = context;
this.headlineModelList = headlineModelList;
}
#NonNull
#Override
public com.example.myapplication.MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.news_item_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final com.example.myapplication.MyAdapter.MyViewHolder holder, int position) {
final HeadlineModel headlineModel=headlineModelList.get(position);
holder.newTitle.setText(headlineModel.getTitle());
holder.newsDescription.setText(headlineModel.getDescription());
holder.newsDescription.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri= Uri.parse(headlineModel.getUrl());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
//Log.v("SSSSSS",headlineModel.getUrl());
}
});
holder.newsName.setText(headlineModel.getName());
holder.newsTime.setText(headlineModel.getPublishedAt());
Glide.with(context).load(headlineModel.getUrlToImage())
.thumbnail(0.5f)
.into(holder.newsImage);
}
#Override
public int getItemCount() {
return headlineModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView newTitle;
TextView newsDescription;
TextView newsName;
TextView newsTime;
ImageView newsImage;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
newTitle=itemView.findViewById(R.id.tv_news_title);
newsDescription=itemView.findViewById(R.id.tv_news_desc);
newsName=itemView.findViewById(R.id.tv_name);
newsTime=itemView.findViewById(R.id.tv_news_date);
newsImage=itemView.findViewById(R.id.im_news_image);
}
}
}
The recycler view in onCreateView in my fragment is initialized like this:
RecyclerView recyclerView;
com.example.myapplication.MyAdapter myAdapter;
private ProgressDialog progressDialog;
List<com.example.myapplication.HeadlineModel> headlineModelList;
private static final String URL="http://newsapi.org/v2/top-headlines?country=in&apiKey=cbd46bd6a4f54fe69d0cb261dbe1a878";
public HeadlinesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_headlines, container, false);
// Inflate the layout for this fragment
recyclerView=rootview.findViewById(R.id.headRecyclerView);
headlineModelList=new ArrayList<>();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false));
progressDialog=new ProgressDialog(getContext(),R.style.ProgressColor);
progressDialog.setMessage("loading...");
progressDialog.show();
loadData();
return rootview;
}
loadData() function that is called
private void loadData() {
progressDialog.setMessage("Loading data...");
//progressDialog.show();
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONArray jsonArray=response.getJSONArray("articles");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String title=jsonObject.getString("title");
String desc=jsonObject.getString("description");
String url=jsonObject.getString("url");
String urlToImage=jsonObject.getString("urlToImage");
String publishedAt=jsonObject.getString("publishedAt");
JSONObject source=jsonObject.getJSONObject("source");
String name=source.getString("name");
// for formatting time and date //
String year=publishedAt.substring(0,4);
String month=publishedAt.substring(5,7);
String date=publishedAt.substring(8,10);
String hour=publishedAt.substring(11,13);
//String hour="11";
String min=publishedAt.substring(14,16);
//Log.v("XXXXXX",min);
String updatedDate=date.concat("-").concat(month).concat("-").concat(year).concat(" ");
String print="";
int convertHour= Integer.parseInt(hour);
int convertMin= Integer.parseInt(min);
if (convertHour==12) {
convertHour=12;
print="PM";
}
else if (convertHour>11&&convertMin>0){
convertHour=convertHour-12;
print="PM";
}else {
print="AM";
}
String newHour= String.valueOf(convertHour);
String updatedTime=updatedDate.concat(newHour).concat(":").concat(min).concat(" ").concat(print);
myAdapter=new com.example.myapplication.MyAdapter(getContext(),headlineModelList);
com.example.myapplication.HeadlineModel headlineModel=new com.example.myapplication.HeadlineModel(name,title,desc,url,urlToImage,updatedTime);
headlineModelList.add(headlineModel);
recyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), cacheEntry);
} catch (UnsupportedEncodingException | JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(JSONObject response) {
super.deliverResponse(response);
}
#Override
public void deliverError(VolleyError error) {
super.deliverError(error);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
};
RequestQueue queue= Volley.newRequestQueue(getContext());
queue.add(jsonObjectRequest);
}
Does anyone know what I'm doing wrong?
Set the Adapter before the API call success because your API response is async and till will take time depending upon response size, network speed etc, till that time recycler view needs to be created and it is having no adapter.
You can set adaptor before calling loadData() and later when you get the list of response set the data in the adapter of your recylerview and call notify on the adapter.
myAdapter=new com.example.myapplication.MyAdapter(getContext(),headlineModelList);
recyclerView.setAdapter(myAdapter);
use it on onCreateView method and myAdapter.notifyDataSetChanged(); use it when API success

create recycler view in fragment?

i want create a fragment and have inside a recycler view for show products ...
but when i render it is show this error : RecyclerView: No adapter attached; skipping layout
below i copy my codes;
this code is for adapter class :
private ArrayList<Products> ProductsList;
private Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}
and this one for web api class :
public class WebApiHandler {
Context context;
String apiLink = "";
ArrayList<Products> products = new ArrayList<>();
public WebApiHandler(Context context) {
this.context = context;
}
void apiConnect(String type) {
switch (type) {
case "getproducts": {
apiLink = Config.getProductsWebApi;
break;
}
}
ProgressDialog dialog = ProgressDialog.show(context, "Connecting...",
"please wait", false, false);
StringRequest request = new StringRequest(Request.Method.POST,
apiLink, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
showJson(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
}
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
}
private void showJson(String response) {
products.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
products.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
VerticalFragment.productsArrayList = products;
IData iData = (IData) context;
iData.sendData();
}}
and my fragment code :
public class VerticalFragment extends Fragment implements IData {
RecyclerView rcVertical;
WebApiHandler webApiHandler;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical, container, false);
rcVertical = view.findViewById(R.id.rcVertical);
webApiHandler = new WebApiHandler(getContext());
webApiHandler.apiConnect("getproducts");
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getContext(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
return view;
}
#Override
public void sendData() {
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager((getContext())));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
}}
i should say i create a interface and have one method i say it sendData
This is a common error when there is no adapter attached to recyclerview upon showing recyclerview. It will not cause any harm to your app, but you could avoid it by setting empty adapter without data, and later when you get your data, provide it to your adapter and notify it
Edit - Example added
Create setter for your list in adapter. After that, in your fragment make adapter global and in onCreateView make instance of your adapter and attach it to recyclerview
adapter = new Adapter(new ArrayList<>(), getContext());
rcVertical.setAdapter(adapter);
...Initialize recyclerview...
And then in your sendData interface put your loaded values in it
adapter.setData(productsArrayList);
adapter.notifyDataSetChanged();

Cannot cast onItem clicklistener inside Fragment Class form Adapter Class

I have an Fragment with recycleview where I populate it with json items from internet.
It load fine and Next step I want to is open new Activity when any row is clicked. It works in activity, thus I modified the same code for fragment but for fragment it throws exception in line
mExampleAdapter.setOnItemClickListener(getActivity());
with errror setOnItemClickListener of refrence adatper cannot be applied to Fragment activty and thus when I change line to
(ExampleAdapter.OnItemClickListener)
and when i build and run . Then app crashes with error that Mainactivity which holds framgnet cannot be cast in to .ExampleAdapter$OnItemClickListener
Here is my whole Fragment class
public class Mynotes extends Fragment implements ExampleAdapter.OnItemClickListener{
public static final String YTD_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
String url="https://api.myjson.com/bins/16mecx";
public Mynotes() {
}
#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.activity_jsonfeed, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new MyDividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL, 36));
mExampleList = new ArrayList<>();
mExampleAdapter = new ExampleAdapter(getActivity(), mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener((ExampleAdapter.OnItemClickListener) getActivity());
parseJSON();
return view;
}
private void parseJSON() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
mExampleList.add(new ExampleItem(videoTitle, link));
mExampleAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(getActivity(), NewActiviyt.class);
ExampleItem clickedItem = mExampleList.get(position);
intent.putExtra(YTD_LINK, clickedItem.getmLink());
startActivity(intent);
}
#Override
public void onRefresh() {
}
}
and my Adapter Class is
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> exampleList) {
mContext = context;
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
// int likeCount = currentItem.getLikeCount();
// String imageUrl = currentItem.getImageUrl();
holder.mTextViewCreator.setText(title);
// holder.mTextViewLikes.setText("Likes: " + likeCount);
// Glide.with(mContext).load(imageUrl).apply(RequestOptions.circleCropTransform()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTextViewCreator;
// public TextView mTextViewLikes;
// public ImageView mImageView;
public ExampleViewHolder(View itemView) {
super(itemView);
// mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
// mImageView = itemView.findViewById(R.id.image_view);
mTextViewCreator = itemView.findViewById(R.id.text_title);
}
#Override
public void onClick(View view) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}
}
Thanks in advance.
replace getActivity with getContext when you work in fragment,
You can read more here
What is different between getContext and getActivity from Fragment in support library?
Your activity should implement ExampleAdapter.OnItemClickListener

How to create a OnItemClickListener for custom list view when passing data from php using json

I am creating an app where a list of hotels will be shown, all the data is coming from MySQL using JSON and PHP, I created the custom list view by extending the base adapter to a custom one, but I am not able to implement a OnItemClickListener for the listview, as i want to show the Hotel Name of that row in Toast whenever the user clicks on a row of list view. I tried various example available on internet, but i just doesn't work.
Adapter
public class CustomListAdapterHotel extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<WorldsBillionaires> billionairesItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterHotel(Activity activity, List<WorldsBillionaires> billionairesItems) {
this.activity = activity;
this.billionairesItems = billionairesItems;
}
#Override
public int getCount() {
return billionairesItems.size();
}
#Override
public Object getItem(int location) {
return billionairesItems.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_hotel, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
//NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
TextView hotel_name = (TextView) convertView.findViewById(R.id.hotel_name);
TextView zone = (TextView) convertView.findViewById(R.id.zone);
TextView contact_person = (TextView) convertView.findViewById(R.id.contact_person);
TextView contact_number = (TextView) convertView.findViewById(R.id.contact_number);
TextView btc_direct = (TextView) convertView.findViewById(R.id.btcdirect);
// getting billionaires data for the row
WorldsBillionaires m = billionairesItems.get(position);
// name
hotel_name.setText(String.valueOf(m.getHotel_Name()));
zone.setText(String.valueOf(m.getHotel_Zone()));
contact_person.setText(String.valueOf(m.getContact_Person()));
contact_number.setText(String.valueOf(m.getContact_Number()));
btc_direct.setText(String.valueOf(m.getBtc_Direct()));
return convertView;
}
}
Model
public class WorldsBillionaires {
private String hotel_name,hotel_zone,contact_person,contact_number,btc_direct;
public WorldsBillionaires(String hotel_name, String hotel_zone, String contact_person, String contact_number, String btc_direct) {
this.hotel_name=hotel_name;
this.hotel_zone=hotel_zone;
this.contact_person=contact_person;
this.contact_number=contact_number;
this.btc_direct=btc_direct;
}
public WorldsBillionaires() {
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getHotel_Name() {
return hotel_name;
}
public void setHotel_Name(String hotel_name) {
this.hotel_name = hotel_name;
}
public String getHotel_Zone() {
return hotel_zone;
}
public void setHotel_Zone(String hotel_zone) {
this.hotel_zone = hotel_zone;
}
public String getContact_Person() {
return contact_person;
}
public void setContact_Person(String contact_person) {
this.contact_person = contact_person;
}
public String getContact_Number() {
return contact_number;
}
public void setContact_Number(String contact_number) {
this.contact_number = contact_number;
}
public String getBtc_Direct() {
return btc_direct;
}
public void setBtc_Direct(String btc_direct) {
this.btc_direct = btc_direct;
}
}
Main Activity
public class ShowHotel extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// Billionaires json url
private ProgressDialog pDialog;
private List<WorldsBillionaires> worldsBillionairesList = new ArrayList<WorldsBillionaires>();
private ListView listView;
private CustomListAdapterHotel adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_hotel);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapterHotel(this, worldsBillionairesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest billionaireReq = new JsonArrayRequest("http://192.168.247.1/AdminBihar/getHotel.php?zone="+methods.zone,
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);
WorldsBillionaires worldsBillionaires = new WorldsBillionaires();
worldsBillionaires.setHotel_Name(obj.getString("hotel_name"));
worldsBillionaires.setThumbnailUrl(obj.getString("image"));
worldsBillionaires.setHotel_Zone(obj.getString("zone"));
worldsBillionaires.setContact_Person(obj.getString("contact_person"));
worldsBillionaires.setContact_Number(obj.getString("contact_number"));
worldsBillionaires.setBtc_Direct(obj.getString("btc_direct"));
// adding Billionaire to worldsBillionaires array
worldsBillionairesList.add(worldsBillionaires);
} 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(billionaireReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
so after you get json data, in activity that shows your list do something like this:
public class DisplayListView extends AppCompatActivity {
ListView listView;
protected void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list_view);
listView = (ListView) findViewById(R.id.listview);
hotelAdapter = new CustomListAdapterHotel (this, R.layout.row_layout);
listView.setAdapter(hotelAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Model stuff = (Model) hotelAdapter.getItem(position);
String hotelName = stuff.getHotel_Name();
Toast.makeText(getApplicationContext(), hotelName, Toast.LENGTH_SHORT).show();
}
});
there, this worked for me :)

Context issues within a fragment (android.view.ContextThemeWrapper cannot be cast to android.app.Activity)

I was following this tutorial on SQLite: https://www.youtube.com/watch?v=3k3CunDZpFk&list=PLshdtb5UWjSrEUEKlfHwqQtYu2HxtCwu_&index=8
I'm attempting to do what he did, but from a fragment. I'm having trouble understanding the context error I get. Can anyone explain it to me?
If you need further information please don't hesitate to ask.
Thank you for your time.
10-18 17:33:16.860 7384-7384/com.example.michael.rogplayer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.michael.rogplayer, PID: 7384
java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to android.app.Activity
at com.example.michael.rogplayer.BackgroundTask.<init>(BackgroundTask.java:20)
at com.example.michael.rogplayer.CreateNewChar_Fragment$1.onClick(CreateNewChar_Fragment.java:98)
Line 20: activity = (Activity) ctx;
Line 98: BackgroundTask backgroundTask = new BackgroundTask(getView().getContext());
Here's CreateNewChar_Fragment.java
public class CreateNewChar_Fragment extends DialogFragment {
private static Activity scanForActivity(Context cont) {
if (cont == null)
return null;
else if (cont instanceof Activity)
return (Activity)cont;
else if (cont instanceof ContextWrapper)
return scanForActivity(((ContextWrapper)cont).getBaseContext());
return null;
}
EditText name;
Button CANCEL, SAVE;
String NAME;
Context CTX;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public static CreateNewChar_Fragment newInstance(String param1, String param2) {
CreateNewChar_Fragment fragment = new CreateNewChar_Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public CreateNewChar_Fragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("State your name!");
return inflater.inflate(R.layout.fragment_create_new_char_, container, false);
}
public void onViewCreated(View container, Bundle savedInstanceState) {
super.onViewCreated(container, savedInstanceState);
CTX = container.getContext();
SAVE = (Button) getView().findViewById(R.id.save);
CANCEL = (Button) getView().findViewById(R.id.cancel);
name = (EditText) getView().findViewById(R.id.name);
NAME = name.getText().toString();
SAVE.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(name.getText())) {
Toast.makeText(getView().getContext(), "Are you mute!?!?! State your name!!!",
Toast.LENGTH_LONG).show();
} else {
BackgroundTask backgroundTask = new BackgroundTask(getView().getContext());
backgroundTask.execute("add_info", NAME);
getDialog().dismiss();
}
}
});
CANCEL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDialog().dismiss();
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
}
Here's BackgroundTask.java
public class BackgroundTask extends AsyncTask <String,CharacterDisplay,String> {
Context ctx;
CharacterAdapter characterAdapter;
Activity activity;
ListView listView;
BackgroundTask(Context ctx) {
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseOperations databaseOperations = new DatabaseOperations(ctx);
if (method.equals("add_info")) {
String name = params[1];
SQLiteDatabase db = databaseOperations.getWritableDatabase();
databaseOperations.putInfo(db, name);
return "One row inserted";
} else if (method.equals("get_info")) {
listView = (ListView) activity.findViewById(R.id.char_list);
SQLiteDatabase db = databaseOperations.getReadableDatabase();
Cursor cursor = databaseOperations.getInfo(db);
characterAdapter = new CharacterAdapter(ctx, R.layout.display_character_row);
String name;
while (cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex(TableData.TableInfo.NAME));
CharacterDisplay characterDisplay = new CharacterDisplay(name);
publishProgress(characterDisplay);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(CharacterDisplay... values) {
characterAdapter.add(values[0]);
}
#Override
protected void onPostExecute(String result) {
if (result.equals("get_info")) {
listView.setAdapter(characterAdapter);
} else {
Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
}
}
}
Here's CharacterDisplay.java
public class CharacterDisplay {
private String name;
public CharacterDisplay(String name) {
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here's CharacterAdapter.java
public class CharacterAdapter extends ArrayAdapter {
List list = new ArrayList();
public CharacterAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Character object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CharacterHolder characterHolder;
if(row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.display_character_row, parent, false);
characterHolder = new CharacterHolder();
characterHolder.tx_name = (TextView) row.findViewById(R.id.char_name);
row.setTag(characterHolder);
} else {
characterHolder = (CharacterHolder) row.getTag();
}
CharacterDisplay characterDisplay = (CharacterDisplay) getItem(position);
characterHolder.tx_name.setText(characterDisplay.getName().toString());
return row;
}
static class CharacterHolder {
TextView tx_name;
}
}
Activity extends ContextThemeWrapper so the cast exception is caused because your ContextThemeWrapper is not an instance of an Activity. It might be another subclass or a ContextThemeWrapper by itself.
To get an Activity context inside a fragment you can use getActivity() instead of getView().getContext()

Categories

Resources