This question already has answers here:
getLayoutInflater() in fragment
(5 answers)
Closed 4 years ago.
I'm trying to code an app that downloads data of some events from an online MySQL database and writes it into my android app. Right now, what i'm trying to do is just testing if downloading the name of the event works, but i keep getting this error:
java.lang.NoSuchMethodError: No virtual method getLayoutInflater()Landroid/view/LayoutInflater; in class Lcom/suspicio/appfisio_business/FrammentoCorsi; or its super classes (declaration of 'com.suspicio.appfisio_business.FrammentoCorsi' appears in /data/app/com.suspicio.appfisio_business-1/split_lib_slice_8_apk.apk)
at com.suspicio.appfisio_business.FrammentoCorsi$EventoAdapter.getView(FrammentoCorsi.java:204)
which points to the line:
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
Here's my code (it's a fragment):
FrammentoCorsi.java:
public class FrammentoCorsi extends Fragment {
public static final int CODE_GET_REQUEST = 1024;
public static final int CODE_POST_REQUEST = 1025;
public FrammentoCorsi() { //Vuoto
}
boolean isUpdating = false;
View rootView;
List<Evento> eventoList;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frammento_corsi, container, false);
listView = (ListView) rootView.findViewById(R.id.listViewEventi);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
eventoList = new ArrayList<>();
readEventi();
}
private void readEventi() {
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_EVENTI, null, CODE_GET_REQUEST);
request.execute();
}
private void refreshEventoList(JSONArray eventi) throws JSONException {
//clearing previous heroes
eventoList.clear();
//traversing through all the items in the json array
//the json we got from the response
for (int i = 0; i < eventi.length(); i++) {
//getting each hero object
JSONObject obj = eventi.getJSONObject(i);
//adding the hero to the list
eventoList.add(new Evento(
obj.getInt("id"),
obj.getString("titolo"),
obj.getString("inizio"),
obj.getString("fine"),
obj.getInt("categoria"),
obj.getString("link"),
obj.getString("luogo")
));
}
//creating the adapter and setting it to the listview
EventoAdapter adapter = new EventoAdapter(eventoList);
listView.setAdapter(adapter);
}
//inner class to perform network request extending an AsyncTask
public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
//the url where we need to send the request
String url;
//the parameters
HashMap<String, String> params;
//the request code to define whether it is a GET or POST
int requestCode;
ProgressBar barra = (ProgressBar) getView().findViewById(R.id.progressBar);
//constructor to initialize values
PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
//when the task started displaying a progressbar
#Override
protected void onPreExecute() {
super.onPreExecute();
barra.setVisibility(View.VISIBLE);
}
//this method will give the response from the request
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
barra.setVisibility(View.INVISIBLE);
try {
JSONObject object = new JSONObject(s);
if (!object.getBoolean("error")) {
Toast.makeText(getActivity().getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
refreshEventoList(object.getJSONArray("eventi"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//the network operation will be performed in background
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
}
class EventoAdapter extends ArrayAdapter<Evento> {
List<Evento> eventoList;
//constructor to get the list
public EventoAdapter(List<Evento> eventoList) {
super(getActivity(), R.layout.frammento_corsi, eventoList);
this.eventoList = eventoList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listViewItem = convertView;
if (listViewItem == null) {
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
}
//getting the textview for displaying name
TextView textViewName = listViewItem.findViewById(R.id.nomeeventocalendario);
//the update and delete textview
//ImageView textViewUpdate = listViewItem.findViewById(R.id.notifica);
//ImageView textViewDelete = listViewItem.findViewById(R.id.link);
final Evento evento = eventoList.get(position);
textViewName.setText(evento.getTitolo());
return listViewItem;
}
}
}
And its resource file frammento_corsi.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.suspicio.appfisio_business.FrammentoCorsi">
<ListView
android:id="#+id/listViewEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/nomeeventocalendario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</FrameLayout>
Can you help me out?
Thanks in advance!
Use this
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
listViewItem = layoutInflater.inflate(R.layout.frammento_corsi, null ,true);
Instead of this
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
Related
I am trying to use Volley to get data via JSON and populate the data in RecyclerView in fragment. I have tested the code with normal activity and it works, but I am finding it difficult implementing thesame thing in fragment. I can see the response in JSON format when I Log in console but it seems no data is added to the list item, thus nothing is displayed in fragment and no error in LogCat.
explore_content.xml
This is the xml that'l be inflated in the adapter
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imagesExplore1"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/testUrl"
android:layout_below="#+id/imagesExplore1"
android:paddingLeft="50dp"
android:textSize="19sp"
/>
</RelativeLayout>
fragment_challenge.xml
This is where I put the RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="fragments.ChallengeFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/testRecyclerView"
android:paddingBottom="20dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:scrollbars="vertical"
android:layout_marginTop="20dp"
/>
</RelativeLayout>
ExploreImagesAdapter.java
The adapter I use
public class ExploreImagesAdapter extends RecyclerView.Adapter<ExploreImagesAdapter.MyViewHolder> {
private Context context;
private List<ExploreImages> exploreImagesList;
RequestOptions options;
public ExploreImagesAdapter(Context context, List<ExploreImages> exploreImagesList) {
this.context = context;
this.exploreImagesList = exploreImagesList;
options = new RequestOptions().centerCrop().placeholder(R.drawable.add_photo).error(R.drawable.back_left_icon);
}
#NonNull
#Override
public ExploreImagesAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.explore_content, parent, false);
return new ExploreImagesAdapter.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Glide.with(context).load(exploreImagesLlist.get(position).getImage_url()).apply(options).into(holder.imageView);
holder.testUrl.setText(exploreImagesList.get(position).getImage_url());
}
#Override
public int getItemCount() {
int a ;
if(exploreImagesList != null && exploreImagesList.isEmpty()) {
a = exploreImagesList.size();
}
else {
a = 0;
}
return a;
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView testUrl;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imagesExplore1);
testUrl = itemView.findViewById(R.id.testUrl);
}
}
public void setItems(List<ExploreImages> data) {
exploreImagesList = data;
notifyDataSetChanged();
}
public void addData (List<ExploreImages> data) {
exploreImagesList.addAll(data);
notifyDataSetChanged();
}
}
ExploreImages.java
A model for the data
ublic class ExploreImages {
private String image_id;
private String image_url;
private String photo_year;
public ExploreImages(){
}
public ExploreImages(String image_id, String image_url, String photo_year) {
this.image_id = image_id;
this.image_url = image_url;
this.photo_year = photo_year;
}
public String getImage_id() {
return image_id;
}
public String getImage_url() {
return image_url;
}
public String getPhoto_year(){
return photo_year;
}
public void setImage_id(String image_id) {
this.image_id = image_id;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public void setPhoto_year(String photo_year){ this.photo_year = photo_year;}
}
ExploreFragment.java
Finally the fragment where I make the network call and set the Adapter
public class ExploreFragment extends Fragment {
private JsonArrayRequest request;
private RequestQueue requestQueue;
private List<ExploreImages> lstAnime;
private ArrayList<ExploreImages> tempList;
public ChallengeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lstAnime = new ArrayList<>();
View root = inflater.inflate(R.layout.fragment_explore, container, false);
RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.testRecyclerView);
ExploreImagesAdapter myAdapter = new ExploreImagesAdapter(getActivity(), lstAnime);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
/* myAdapter.notifyDataSetChanged();*/
jsonrequest();
// Inflate the layout for this fragment
return root;
}
private void jsonrequest() {
request = new JsonArrayRequest(EndPoints.EXPLORE_IMAGES_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
/*Log.e("Errorrr", "["+response+"]");*/
JSONObject jsonObject = null;
int i;
for(i=0; i<response.length(); i++){
try {
jsonObject = response.getJSONObject(i);
ExploreImages anime = new ExploreImages();
anime.setImage_id(jsonObject.getString("id"));
anime.setImage_url(jsonObject.getString("url"));
anime.setPhoto_year(jsonObject.getString("photo_year"));;
Log.e("CHAAAA", "["+response+"]");
lstAnime.add(anime);
ExploreImagesAdapter myAdapter = new ExploreImagesAdapter(getActivity(),
lstAnime);
myAdapter.setItems(lstAnime);
}
catch (JSONException e){
e.printStackTrace();
Log.e("TESTERROR", "["+response+"]");
}
/*ExploreImagesAdapter myAdapter = new ExploreImagesAdapter(getActivity(), lstAnime);
myAdapter.addData(lstAnime);*/
setRecyclerView(lstAnime);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
private void setRecyclerView(List<ExploreImages> lstAnime) {
RecyclerView recyclerViewx = getActivity().findViewById(R.id.testRecyclerView);
ExploreImagesAdapter myAdapter = new ExploreImagesAdapter(getActivity(), lstAnime);
recyclerViewx.setAdapter(myAdapter);
recyclerViewx.setLayoutManager(new LinearLayoutManager(getActivity()));
}
}
I have searched Everywhere and tried everything but no data is displayed even when the JSON is parsed in Volley
Do these things
1) Set linearlayout manager after declaring recyclerview
2) Declare recyclerview and adapter class globally
3) Update adapter after parsing JSON array to arraylist
Eg
public class ExploreFragment extends Fragment {
private JsonArrayRequest request;
private RequestQueue requestQueue;
private List<ExploreImages> lstAnime;
private ArrayList<ExploreImages> tempList;
ExploreImagesAdapter myAdapter;
public ChallengeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lstAnime = new ArrayList<>();
View root = inflater.inflate(R.layout.fragment_explore, container, false);
RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.testRecyclerView);
// set layout manager here
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myAdapter = new ExploreImagesAdapter(getActivity(), lstAnime);
recyclerView.setAdapter(myAdapter);
jsonrequest();
// Inflate the layout for this fragment
return root;
}
private void jsonrequest() {
request = new JsonArrayRequest(EndPoints.EXPLORE_IMAGES_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
/*Log.e("Errorrr", "["+response+"]");*/
JSONObject jsonObject = null;
int i;
for(i=0; i<response.length(); i++){
try {
jsonObject = response.getJSONObject(i);
ExploreImages anime = new ExploreImages();
anime.setImage_id(jsonObject.getString("id"));
anime.setImage_url(jsonObject.getString("url"));
anime.setPhoto_year(jsonObject.getString("photo_year"));;
Log.e("CHAAAA", "["+response+"]");
lstAnime.add(anime);
}
catch (JSONException e){
e.printStackTrace();
Log.e("TESTERROR", "["+response+"]");
}
}
// update adapter here
myAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
}
you are doing several things wrong here
make ExploreImagesAdapter as global variable inside of fragment and use it everywhere else
now when you will get your data just call your adapter and add Data in it you already have function for that.
First of all you're always creating a new Adapter instance and you shouldn't. Keep one instance global to this Fragment and you're good to go. Then update that same instance.
Using your code:
private ExploreImagesAdapter myAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
lstAnime = new ArrayList<>();
View root = inflater.inflate(R.layout.fragment_explore, container, false);
RecyclerView recyclerViewx = getActivity().findViewById(R.id.testRecyclerView);
myAdapter = new ExploreImagesAdapter(getActivity(), lstAnime);
recyclerViewx.setAdapter(myAdapter);
recyclerViewx.setLayoutManager(new LinearLayoutManager(getActivity()));
jsonrequest();
return root;
}
private void jsonrequest() {
request = new JsonArrayRequest(EndPoints.EXPLORE_IMAGES_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
/*Log.e("Errorrr", "["+response+"]");*/
JSONObject jsonObject = null;
int i;
for(i=0; i<response.length(); i++){
try {
jsonObject = response.getJSONObject(i);
ExploreImages anime = new ExploreImages();
anime.setImage_id(jsonObject.getString("id"));
anime.setImage_url(jsonObject.getString("url"));
anime.setPhoto_year(jsonObject.getString("photo_year"));;
Log.e("CHAAAA", "["+response+"]");
lstAnime.add(anime);
}
catch (JSONException e){
e.printStackTrace();
Log.e("TESTERROR", "["+response+"]");
}
}
myAdapter.setItems(lstAnime);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
RecyclerView recyclerViewx = getActivity().findViewById(R.id.testRecyclerView);
this line refers to the RecyclerView in your activity. You should use in the fragment
When I click the listview in tab Fragment 1 it won't work jump into next activities. I already setOnItemClickListener in the class, but still won't work. Now my problem is when I click the listview it won't work.
public class TabFragment1_Staff extends Fragment {
ListView lsReport;
ArrayList<HashMap<String, String>> reportlist;
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.activity_tab_fragment1__staff, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
reportlist = new ArrayList<>();
lsReport = getActivity().findViewById(R.id.listReport);
loadReport();
lsReport.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(),AddStatusDialogWindow.class);
Bundle bundle = new Bundle();
Log.e("HANIS",reportlist.get(position).get("reportID"));
bundle.putString("reportID",reportlist.get(position).get("reportID"));
bundle.putString("fullName",reportlist.get(position).get("fullName"));
bundle.putString("icNum",reportlist.get(position).get("icNum"));
bundle.putString("phoneNum",reportlist.get(position).get("phoneNum"));
bundle.putString("Rdate",reportlist.get(position).get("Rdate"));
bundle.putString("Rtime",reportlist.get(position).get("Rtime"));
bundle.putString("timeName",reportlist.get(position).get("timeName"));
bundle.putString("typeVehicle",reportlist.get(position).get("typeVehicle"));
bundle.putString("registrationnum",reportlist.get(position).get("registrationnum"));
bundle.putString("location",reportlist.get(position).get("location"));
bundle.putString("brief",reportlist.get(position).get("brief"));
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
tabFragment1.xml
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listReport"
android:layout_width="match_parent"
android:layout_height="300dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
</ScrollView>
LoadReport class
class LoadReport extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// Perform api call
}
#Override
protected void onPostExecute(String s) {
reportlist.clear();
// Parse api response and fill in reportlist var
ListAdapter adapter = new CustomList_StatusReport(
getActivity(), reportlist,
R.layout.activity_custom_list__status_report, new String[]
{"reportID","fullName","icNum","phoneNum"}, new int[]
{R.id.tvReport_ID,R.id.tvCompliantName,R.id.tvCompliantIC,R.id.tvCompliantPhone});
lsReport.setAdapter(adapter);
Toast.LENGTH_SHORT).show();
}
}
LoadReport loadReport = new LoadReport();
loadReport.execute();
}
public class CustomList_StatusReport extends SimpleAdapter {
private Context mContext;
public LayoutInflater inflater = null;
public CustomList_StatusReport(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
mContext = context;
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
try {
if (convertView == null)
vi = inflater.inflate(R.layout.activity_custom_list__status_report, null);
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
TextView reportID = vi.findViewById(R.id.tvReport_ID);
TextView cName = vi.findViewById(R.id.tvCompliantName);
TextView cIC = vi.findViewById(R.id.tvCompliantIC);
TextView cPhone = vi.findViewById(R.id.tvCompliantPhone);
String id = (String) data.get("reportID");
String name = (String)data.get("fullName");
String ic = (String)data.get("icNum");
String phone = (String)data.get("phoneNum");
reportID.setText(id);
cName.setText(name);
cIC.setText(ic);
cPhone.setText(phone);
}catch (IndexOutOfBoundsException e){}
return vi;
}
In tabFragment1.xml, why you are using the below lines code?
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
Please remove these if not needed and let us know whether this issue exists?
I have ListView, where I have ImageView. I need to get the image from url and show in ImageView, but that's not working, the image is not visible. In that ListView I have a TextView and CheckBox too, but you not need it because that works. I'm using Glide. So what's the problem?
I set in glide placeholders and it loads the placeholders. I've done debug and I saw that the glide gets the image URL. But the image doesn't load.
Ok here's the item code.
public class LanguageItem {
String imagePath;
LanguageItem(String imagePath,) {
this.imagePath = imagePath;
}
public String getImagePath() {
return imagePath;
}
There are textView and checkbox too, but I'm not showing it to you, because that works fine.
Here the adapter.
public class LanguageAdapter extends BaseAdapter {
private Context context;
private LayoutInflater lInflater;
private ArrayList<LanguageItem> objects;
LanguageAdapter(Context context, ArrayList<LanguageItem> itemObj) {
this.context = context;
objects = itemObj;
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//amount of elements
#Override
public int getCount() {
return objects.size();
}
//element by position
#Override
public Object getItem(int position) {
return objects.get(position);
}
//id by position
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.language_items, parent, false);
}
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
Glide.with(context).load(objects.get(position).getImagePath()).thumbnail(0.5f).crossFade().into(imageView);
return view;
}
And here's the fragment. I'm doing my work in fragment.
public class FragmentLanguage extends BaseFragment {
private static final String IMAGE = "IMAGE";
private ApiClient apiClient;
private ArrayList<LanguageItem> objS;
private LanguageAdapter adapter;
private View mainView;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.languages, container, false);
listView = (ListView) mainView.findViewById(R.id.language_list);
apiClient = ApiClient.getInstance();
//calling methods
fillData();
showResult();
return mainView;
}
public void fillData() {
objS = new ArrayList<>();
getLanguageCall();
}
public void getLanguageCall() {
Call<ResponseBody> getLanguage = apiClient.getLanguage(SharedPreferencesManager.getInstance().getAccessToken());
getLanguage.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String data = response.body().string();
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String languageName = object.getString("name");
String path = object.getString("image_path");
String real_path = "https://supportop.eu-gb.mybluemix.net" + path.substring(1, path.length());
Toast.makeText(context, real_path, Toast.LENGTH_SHORT).show();
objS.add(new LanguageItem(languageName,real_path, false));
}
adapter = new LanguageAdapter(getActivity(), objS);
listView.setAdapter(adapter);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
Ok here's the code. I done debug and the Image url it gets successfully, but glide not loads it. Thank you for reading.
Ok and here's the layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/white"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="45dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_marginStart="20dp" />
And here the listView part.
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/language_list"
android:layout_marginTop="10dp"
android:layout_below="#+id/linearLayout"
android:layout_above="#+id/bottomNavigationView">
</ListView>
Try to use http inside https. I think that's a server problem.
You can use Glide or Picasso. From an activity the code will like:
Picasso
Picasso.get().load(url).resize(50, 50).centerCrop().into(imageView)
Glide
Glide.with (context)
.load ( "http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
.into (imageView);
I'm a total Android beginner and my problem was that I was missing the INTERNET permission (as I could read in the Logcat tab after an hour long hassle).
So try adding this to your AndroidManifest.xml:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>
Use Request Options with glide
RequestOptions options = new RequestOptions()
.centerCrop()
.placeholder(R.mipmap.ic_launcher_round)
.error(R.mipmap.ic_launcher_round);
Glide.with(this).load(image_url).apply(options).into(imageView);
I just added <uses-permission android:name="android.permission.INTERNET" /> and it worked finaly.
There are two weird glitches in my app
When using Listview, when I scroll down fast and up again, the first Item changes.
I didn't implement anything that would cause this, is it a glitch with
Listview?
When updating the Listview, it fetches the data and when it goes to update it, it does the first 12 items right, then repeats them them again, then the first six again (for the total number of dorms)
I can't find the a reason it repeated at 12 specifically here's my code
MainActivity class:
public class MainActivity extends AppCompatActivity {
private Button btnGetData;
private final String URL = "https://www.laundryalert.com/cgi-bin/urba7723/LMPage?Login=True";
private List<DormMachines> dorms;
private BaseAdapterDorm dormsAdapter;
private ListView dormsList;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set click listener for button
btnGetData = (Button) findViewById(R.id.btnContent);
btnGetData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new GetContent().execute();
}
}); dorms = new ArrayList<DormMachines>();
dormsList = (ListView) findViewById(R.id.myListView);
dormsAdapter = new BaseAdapterDorm(dorms, this);
dormsList.setAdapter(dormsAdapter);
setupListViewListener();
}
private void setupListViewListener() {
dormsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dorms.remove(position);
dormsAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
private class GetContent extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Getting Content");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
dorms.clear();
try {
Document doc = Jsoup.connect(URL).get();
Element table = doc.getElementById("tableb");
Elements rows = table.getElementsByTag("tr");
// Removes table headers and whitespace at end
rows.remove(0);
rows.remove(0);
rows.remove(30);
for(Element row : rows) {
int index = 0;
DormMachines dorm = new DormMachines();
for (Element rowData : row.getElementsByTag("td")) {
switch (index) {
case 1:
// Dorm Name
dorm.dormName = rowData.text();
break;
case 2:
// Washers Free
dorm.washersFree = Integer.parseInt(rowData.text());
break;
case 3:
// Dryers Free
dorm.dryersFree = Integer.parseInt(rowData.text());
break;
case 5:
// Washers in Use
dorm.washersInUse = Integer.parseInt(rowData.text());
break;
case 7:
// Dryers In Use
dorm.dryersInUse = Integer.parseInt(rowData.text());
break;
default:
break;
}
index++;
}
dorms.add(dorm);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
dormsAdapter.notifyDataSetChanged();
mProgressDialog.dismiss();
}
}
}
BaseAdapterDorm class:
public class BaseAdapterDorm extends BaseAdapter {
private List<DormMachines> list;
private LayoutInflater layoutInflater;
public BaseAdapterDorm(List<DormMachines> list, Context context) {
this.list = list;
this.layoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
DormViewHolder dormViewHolder;
if(view == null) {
view = layoutInflater.inflate(R.layout.listview_dorm_item, parent, false);
dormViewHolder = new DormViewHolder();
dormViewHolder.textViewDormName = (TextView) view.findViewById(R.id.list_item_dorm_item_name);
dormViewHolder.textViewWasherAvail = (TextView) view.findViewById(R.id.list_item_washers_avail);
dormViewHolder.textViewWasherOccupied = (TextView) view.findViewById(R.id.list_item_washer_occupied);
dormViewHolder.textViewDryersAvail = (TextView) view.findViewById(R.id.list_item_dryers_avail);
dormViewHolder.textViewDryersOccupied = (TextView) view.findViewById(R.id.list_item_dryers_occupied);
dormViewHolder.textViewDormName.setText(list.get(position).dormName);
dormViewHolder.textViewWasherAvail.setText(""+list.get(position).washersFree);
dormViewHolder.textViewWasherOccupied.setText(""+list.get(position).washersInUse);
dormViewHolder.textViewDryersAvail.setText(""+list.get(position).dryersFree);
dormViewHolder.textViewDryersOccupied.setText(""+list.get(position).dryersInUse);
}
return view;
}
static class DormViewHolder {
TextView textViewDormName;
TextView textViewWasherAvail;
TextView textViewWasherOccupied;
TextView textViewDryersAvail;
TextView textViewDryersOccupied;
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8sp"
tools:context="com.sergiodlz.jsoupexample.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get data"
android:id="#+id/btnContent"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="0sp"
android:id="#+id/myListView"
android:layout_weight="1">
</ListView>
</LinearLayout>
The rest is on Github
ListAdapters recycle their views (these views being the "entries" in the list). The number of views is arbitrary as far as we are usually concerned, but in this instance it is probably 12.
The idea is this... Once that arbitrary number of views has been created ( meaning all views have hit this if(view == null){...create/initialize} ), then every time you get a view at position Y, you will need to replace the contents of the view at position Y, otherwise you will see the content of the original entry that got slapped on that view.
Now to fix your problem, do something like this:
public View getView(int position, View view, ViewGroup parent) {
DormViewHolder dormViewHolder;
if(view == null) {
view = layoutInflater.inflate(R.layout.listview_dorm_item, parent, false);
dormViewHolder = new DormViewHolder();
dormViewHolder.textViewDormName = (TextView) view.findViewById(R.id.list_item_dorm_item_name);
dormViewHolder.textViewWasherAvail = (TextView) view.findViewById(R.id.list_item_washers_avail);
dormViewHolder.textViewWasherOccupied = (TextView) view.findViewById(R.id.list_item_washer_occupied);
dormViewHolder.textViewDryersAvail = (TextView) view.findViewById(R.id.list_item_dryers_avail);
dormViewHolder.textViewDryersOccupied = (TextView) view.findViewById(R.id.list_item_dryers_occupied);
// Set the View Tag with the ViewHolder to save View properties.
view.setTag(dormViewHolder);
}
else
{
// Recycle the view (all View properties already set).
dormViewHolder = (DormViewHolder) view.getTag();
}
dormViewHolder.textViewDormName.setText(list.get(position).dormName);
dormViewHolder.textViewWasherAvail.setText(""+list.get(position).washersFree);
dormViewHolder.textViewWasherOccupied.setText(""+list.get(position).washersInUse);
dormViewHolder.textViewDryersAvail.setText(""+list.get(position).dryersFree);
dormViewHolder.textViewDryersOccupied.setText(""+list.get(position).dryersInUse);
return view;
}
This is a well known issue in android, to overcome this you need to use viewholder inside your list view. The reason why it happens is because the list view recycles the views which causes this to happen
I have made a custom Adapter and populate it with the data. I have used Logcat to see whether the array i'm passing to custom Adapter class contains the data and it does.
The error i got is following. It occurs when this CategoryBlog is created. Activity is created but it does not contain list view
exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
'mainblogpost' contains the array with all the data i want to populate with.
'MainListActivityAdapter' is the Adapter Class.
'Category_Blogs' is the class where i want to set the list view.
Category_Blog.java
I don't add import statement. there is no error in it
public class Category_Blogs extends AppCompatActivity implements AbsListView.OnItemClickListener {
public static final String TAG = MainActivity.class.getSimpleName();
public final static String EXTRA_MESSAGE = "com.example.talha.appforblog.MESSAGE";
List<StackOverflowXmlParser.Entry> mainBlogPost = new ArrayList<StackOverflowXmlParser.Entry>();
private ListAdapter mAdapter;
private AbsListView mListView;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
//Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
//setSupportActionBar(toolbar);
Intent intent = getIntent();
String message = intent.getStringExtra(Tab2.EXTRA_MESSAGE);
String link = message.trim() + "?feed=titles";
Log.d("ye category click krne par next activity me ye link bnta hy parsing ke liye",link);
loadPage(link);
}
#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_category__blogs, 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;
}
return super.onOptionsItemSelected(item);
}
public void loadPage(String link) {
Log.d(TAG, "loadpage me a gae nh");
// if((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) {
new DownloadXmlTask(this).execute(link);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<StackOverflowXmlParser.Entry>> {
private Context mContext;
public DownloadXmlTask(Context context) {
mContext = context;
}
#Override
protected List<StackOverflowXmlParser.Entry> doInBackground(String... urls) {
try {
return loadXmlFromNetwork(urls[0]);
} catch (Exception e) {
Log.d("test", "" + e);
}
return null;
}
#Override
protected void onPostExecute(List<StackOverflowXmlParser.Entry> results) {
if (results != null) {
try {
String title, link, image, pubDate;
Log.d("test", "onpost");
// custom array adapter
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (StackOverflowXmlParser.Entry result : results) {
title = result.title;
link = result.link;
image = result.image;
pubDate = result.pubDate;
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put("link", link);
blogPost.put("title", title);
blogPost.put("image", image);
blogPost.put("pubDate", pubDate);
blogPosts.add(blogPost);
}
// copying to main item List array
for (int i = 0; i < results.size(); i++) {
mainBlogPost.add(results.get(i));
}
Log.d("fff", results.get(1).pubDate);
MainListActivityAdapter mAdapter =
new MainListActivityAdapter(Category_Blogs.this, mainBlogPost);
listView.setAdapter(mAdapter);
//((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(Category_Blogs.this);
}
catch (Exception e){
Log.d("test", "exception: "+e);
}
}
}
private List<StackOverflowXmlParser.Entry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
// Instantiate the parser
StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
List<StackOverflowXmlParser.Entry> entries = null;
String title = null;
String url = null;
try {
//opening the connection and fetching
stream = downloadUrl(urlString);
entries = stackOverflowXmlParser.parse(stream);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} catch (Exception e) {
Log.d("test", "" + e);
} finally {
if (stream != null) {
stream.close();
}
}
for (StackOverflowXmlParser.Entry entry : entries) {
Log.d("aaa",entry.pubDate);
}
return entries;
}
private InputStream downloadUrl(String urlString) throws IOException {
java.net.URL url = new java.net.URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
return conn.getInputStream();
}
}
}
MainListActivityAdapter.java
public class MainListActivityAdapter extends BaseAdapter {
private Activity activity;
List<StackOverflowXmlParser.Entry> mainBlogPost = new ArrayList<StackOverflowXmlParser.Entry>();
private static LayoutInflater inflater = null;
public MainListActivityAdapter(Activity a, List<StackOverflowXmlParser.Entry> main) {
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mainBlogPost = main;
}
public int getCount() {
return mainBlogPost.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
Log.d("test", "fetching" + position);
String tit = mainBlogPost.get(position).title;
String cate = mainBlogPost.get(position).pubDate;
String pub = mainBlogPost.get(position).pubDate;
String image_url = "http://download.androidhive.info/img/btn_fb_login.png";
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView) vi.findViewById(R.id.title); // title
TextView cat = (TextView) vi.findViewById(R.id.category); // category
ImageView image = (ImageView) vi.findViewById(R.id.list_image); // image
TextView publish = (TextView) vi.findViewById(R.id.pubDate); // publish date
// Setting all values in listview
title.setText(tit);
cat.setText(cate);
publish.setText(pub);
Glide.with(activity)
.load(image_url)
.into(image);
return vi;
}
}
Activity_category_blog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="wrap_content" tools:context="com.example.talha.test_fragement.Category_Blogs"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<include layout="#layout/tool_bar" />
<FrameLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#layout/tool_bar">
<ListView android:id="#android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/adView" android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:layout_alignParentBottom="true"
/>
<TextView android:id="#android:id/empty" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center"
android:layout_gravity="right|top" />
</FrameLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
listView = (ListView) findViewById(R.id.lvID);//where lvID is id from your listview placed in activity_category__blogs layout.
You fail to initialize the listview.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
//Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
**listView = (ListView) findViewById(R.id.list);**
//setSupportActionBar(toolbar);
Intent intent = getIntent();
String message = intent.getStringExtra(Tab2.EXTRA_MESSAGE);
String link = message.trim() + "?feed=titles";
Log.d("ye category click krne par next activity me ye link bnta hy parsing ke liye",link);
loadPage(link);
}