Android PopupMenu in recycleview not worked? - java

I have tried to add sub menu to recycleview but when click on sub menu in every row A message appears : unfortunately app has stopped
after that The application is automatically closed
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvAnimals"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
// recycleview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/tvAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<TextView
android:id="#+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="⋮"
android:textAppearance="?android:textAppearanceLarge" />
</LinearLayout>
// MainActivity class
package com.example.hamoda.recyvlastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView =(RecyclerView) findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
// MyRecyclerViewAdapter class
package com.example.hamoda.recyvlastexample;
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData = Collections.emptyList();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// binds the data to the textview in each row
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating a popup menu
PopupMenu popup = new PopupMenu((Context)mData,holder.buttonViewOption);
/*
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
break;
case R.id.menu2:
//handle menu2 click
break;
case R.id.menu3:
//handle menu3 click
break;
}
return false;
}
});
//displaying the popup
popup.show();
*/
}
});
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myTextView;
public TextView buttonViewOption;
public ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
//textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view,getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Error log:
03-31 11:13:57.461 10139-10139/com.example.hamoda.recyvlastexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hamoda.recyvlastexample, PID: 10139
java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.content.Context
at com.example.hamoda.recyvlastexample.MyRecyclerViewAdapter$1.onClick(MyRecyclerViewAdapter.java:38)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

You haven't pass Context in PopupMenu constructor and you have cast data list object in Context that is wrong.
PopupMenu popup = new PopupMenu((Context)mData,holder.buttonViewOption);
use below line :
PopupMenu popup = new PopupMenu(context,holder.buttonViewOption);
In above line context is reference of Activity context that is passes in MyRecyclerViewAdapter constructor in your code see below :
// data is passed into the constructor
public MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
So create one global reference of contextand pass in PopupMenu constructor.

Related

Null Pointer on RecyclerView

I am getting a null pointer exception on the following statement within my recyclersetup method.
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
It is due to the following statement not setting a pointer to recyclerView in the previous statement which is
recyclerView = getView().findViewById(R.id.check_in_recent_row);
I cannot determine why I am not getting the recyclerView pointer established via this statement. the ID for the data is correct. What am I missing?
This is the entire fragment code
CheckInRecentList.java
package com.example.checkingin;
import android.content.Context;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProvider.Factory;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter adapter;
private MainViewModelProviderFactory viewModelFactory;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;
private OnFragmentInteractionListener mListener;
public CheckInRecentList() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
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);
Log.i(TAG, "onCreate: On Create");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// These were originally set up from the recycler view add to the fragment
// recyclerView = findViewById(R.id.check_in_recent_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
//recyclerView.setHasFixedSize(true);
/*
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
*/
// specify an adapter (see also next example)
//checkInListAdapter = new CheckInListAdapter();
// recyclerView.setAdapter(checkInListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "onCreateView: On Create View");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.recycler_view_item, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Log.i(TAG, "onButtonPressed: ");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach: OnAttach");
viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Log.i(TAG,"OnAttach completed");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: On Activity Created");
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);
recyclerSetup();
Log.i(TAG,"OnActivityCreated: Recycler SetUp");
//listenerSetup();
//Log.i(TAG, "onActivityCreated: Listener SetUp");
observerSetup();
Log.i(TAG, "onActivityCreated: Observer SetUp");
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach: ");
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}
private void listenerSetup() {
ImageButton editCheckInButton = getView().findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = getView().findViewById(R.id.checkInResendButton);
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "listenerSetup: ");
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
private void observerSetup() {
Log.i(TAG, "observerSetup:");
if(mViewModel.getAllCheckIn() != null)
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
adapter.setCheckInList(allCheckIn);
}
});
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>() {
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
if (allCheckIn.size() > 0) {
Log.i(TAG, "onChanged: all check in size greater than zero");
checkInLastDateTime.setText(allCheckIn.get(0).getCheckInLastDateTime());
Log.i(TAG, "onChanged: running again");
checkInDestinationName.setText(allCheckIn.get(0).getCheckInDestinationName());
checkInTitle.setText(allCheckIn.get(0).getCheckInTitle());
checkInComments.setText(allCheckIn.get(0).getCheckInComments());
} else {
checkInLastDateTime.setText("None Found");
}
}
});
}
private void recyclerSetup() {
Log.i(TAG, "recyclerSetup: ");
adapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
//recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
}
}
The following are the xml files for the fragment
fragment_check_in_recent_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CheckInRecentList">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/check_in_recent_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/recycler_view_item"/>
</FrameLayout>
and recycler_view_item.xml
<?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:orientation="horizontal"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/check_in_recent_row"
android:layout_width="389dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:padding="30dp">
<TableRow
android:layout_width="346dp"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInLastDateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/checkInTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/checkInDestinationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageButton
android:id="#+id/checkInEditButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_edit"
android:tooltipText="Edit Check In" />
<ImageButton
android:id="#+id/checkInResendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_share"
android:tooltipText="Resend Check In" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
CheckInListAdapter
package com.example.checkingin;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
private int checkInListLayout;
private List<CheckInTable> checkInList;
public CheckInListAdapter(int layoutId) {
checkInListLayout = layoutId;
}
public void setCheckInList(List<CheckInTable> allCheckIn) {
checkInList = allCheckIn;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return checkInList == null ? 0 : checkInList.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View view = LayoutInflater.from(
parent.getContext()).inflate(checkInListLayout, parent, false);
ViewHolder checkInListViewHolder = new ViewHolder(view);
return checkInListViewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView checkInLastDateTime = holder.checkInLastDateTime;
TextView checkInTitle = holder.checkInTitle;
TextView checkInDestinationName = holder.checkInDestinationName;
TextView checkInComments = holder.checkInComments;
ImageView checkInEditButton = holder.checkInEditButton;
ImageView checkInResendButton = holder.checkInResendButton;
Log.i(TAG, "onBindViewHolder: ");
checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
checkInComments.setText(checkInList.get(listPosition).getCheckInComments());
holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);
ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
}
);
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView checkInLastDateTime;
TextView checkInTitle;
TextView checkInDestinationName;
TextView checkInComments;
ImageView checkInEditButton;
ImageView checkInResendButton;
ViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "ViewHolder: ");
checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
checkInTitle = itemView.findViewById(R.id.checkInTitle);
checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
checkInComments = itemView.findViewById(R.id.checkInComments);
checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
}
Your RecyclerView's ID is check_in_recent_recycler_view. Your findViewById call is using check_in_recent_row. These need to match.

ListView cannot show a List retrieved from URL

I'm new to Android Studio. I'm trying to custom a Fragment automatically created by the IDE using the option create -> new Fragment (List). I'm not able to show the List retrieved from an http page, but if I manually add items to my list, the emulator let me see it. How can I solve this problem?
municipioFragment.java
package com.example.is2_app.ui.municipio;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class municipioFragment extends Fragment {
// TODO: Customize parameters
private int mColumnCount = 1;
private List<News> lstNews;
private OnListFragmentInteractionListener mListener;
public municipioFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstNews = new ArrayList<>();
getURL();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_municipio_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(News item);
}
public void getURL() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.comune.candida.av.it").get();
Element content = doc.getElementById("b370");
Elements subcontent = content.getElementsByTag("p");
String Text = null;
String Href = null;
int i = 0;
for (Element link : subcontent) {
Href = link.attr("href");
Text = link.text();
builder.append("\n").append(Text);
i = i + 1;
lstNews.add(new News(Integer.toString(i), Text));
}
} catch (IOException e) {
builder.append("Error: ").append(e.getMessage()).append("\n");
}
}
}).start();
}
}
MunicipioRecyclerViewAdapter.java
package com.example.is2_app.ui.municipio;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import com.example.is2_app.ui.municipio.municipioFragment.OnListFragmentInteractionListener;
import java.util.List;
public class MymunicipioRecyclerViewAdapter extends RecyclerView.Adapter<MymunicipioRecyclerViewAdapter.ViewHolder> {
private final OnListFragmentInteractionListener mListener;
List<News> mData;
public MymunicipioRecyclerViewAdapter(List<News> mData, OnListFragmentInteractionListener listener) {
this.mData = mData;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_municipio, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
//holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mData.get(position).getId());
holder.mContentView.setText(mData.get(position).getContent());
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.item_number);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
fragment_municipio.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" /> </LinearLayout>
fragment_municipio_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/list"
android:name="com.example.is2_app.ui.municipioFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.municipio.municipioFragment"
tools:listitem="#layout/fragment_municipio" />
So getUrl() is running in a Thread. In addition, getting the Document with JSoup is gonna need some time. This means that onCreateView will probably run before your lstNews is filled with the data you are scraping from the Document.
So you want to update your dataset; then, you want to notify your Adapter that your dataset changed.
Add this method to your Adapter
public void updateData(List<News> mData) {
this.mData = mData;
this.notifyDataSetChanged();
}
And after the for loop in getUrl(), you want to do the following:
runOnUiThread(new Runnable() {
#Override
public void run() {
recyclerViewAdapter.updateData(lstNews);
}
});
Where, recyclerViewAdapter is defined alongside recyclerView and initialized in the onCreateView.
So the following line:
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
Will become:
recyclerViewAdapter = new MymunicipioRecyclerViewAdapter(lstNews, mListener);
recyclerView.setAdapter(recyclerViewAdapter);

Cannot find symbol method setItemClickListener

"I am trying to make Cardview clickable where it opens new activity,but i am lost somewhere in calling setitemclcik listener. its gives an error code f anonymous itemclicklistener."
RecyclerViewAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import info.techabyte.parentsapp.newsletter.DetailActivity;
import java.util.List;
import info.techabyte.parentsapp.R;
import static info.techabyte.parentsapp.R.id.imageUrl;
import static info.techabyte.parentsapp.R.id.year;
import static info.techabyte.parentsapp.R.id.quarter;
public class NewsletterRecyclerViewAdapter extends RecyclerView.Adapter<NewsletterRecyclerViewAdapter.ViewHolder> {
Context context;
List<NewsletterAdapter> getNewsletterAdapter;
ImageLoader imageLoader1;
public NewsletterRecyclerViewAdapter(List<NewsletterAdapter> getNewsletterAdapter, Context context){
super();
this.getNewsletterAdapter = getNewsletterAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.newsletter_recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
NewsletterAdapter getNewsletterAdapter1 = getNewsletterAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getNewsletterAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getNewsletterAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getNewsletterAdapter1.getImageTitleName());
Viewholder.YearView.setText(getNewsletterAdapter1.getYear());
Viewholder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
openDetailActivity(quarter,year,imageUrl);
Toast.makeText(context,quarter,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return getNewsletterAdapter.size();
}
private void openDetailActivity(String quarter, String year, int image)
{
Intent i=new Intent(context, DetailActivity.class);
//PACK DATA TO SEND
i.putExtra("quarter",quarter);
i.putExtra("year",year);
i.putExtra("imageUrl",image);
//open activity
context.startActivity(i);
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public TextView YearView;
public NetworkImageView networkImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
YearView = (TextView) itemView.findViewById(R.id.textView_item1) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import info.techabyte.parentsapp.R;
public class DetailActivity extends AppCompatActivity {
TextView quartertxt;
TextView yeartxt;
ImageView imageUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//INITIALIZE VIEWS
quartertxt= (TextView) findViewById(R.id.quarter);
yeartxt= (TextView) findViewById(R.id.year);
imageUrl= (ImageView) findViewById(R.id.imageUrl);
//RECEIVE DATA
Intent i=this.getIntent();
String quarter=i.getExtras().getString("quarter");
String year=i.getExtras().getString("year");
int image=i.getExtras().getInt("imageUrl");
//BIND DATA
quartertxt.setText(quarter);
yeartxt.setText(year);
imageUrl.setImageResource(image);
}
}
Newsletterrecyclerviewitems.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/quarter"
android:id="#+id/textView_item"
android:layout_centerVertical="false"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_marginLeft="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/year"
android:id="#+id/textView_item1"
android:layout_centerVertical="false"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_below="#+id/textView_item"
android:layout_marginLeft="20dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Wrong Approach
Viewholder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
......
}
});
Right Way.
Your Viewholder holds XML Attributes . You should call your RootLayout Object.
Viewholder.Your_root_layout_OBJ.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
......
}
});
Your code has multiple troubles:
1) Do not call fields of ViewHolder in that way. You need cast it from holder parameter in onBindViewHolder method.
YourViewHolderClass yourViewHolderMember = (YourViewHolderClass)
holder;
2) Yours ViewHolder class doesn't has method setItemClickListener. But it has field of root elemet called itemView. Try like this:
yourViewHolderMember.itemView.setOnClickListener()

RecyclerView Data is not showing up

I am trying to create Navigation Drawer with RecyclerView. I am following a tutorial on YouTube to do this because I am new to this. The problem is RecyclerView does not show any data from the adapter. I need help. Any suggestion on this is appreciated.
NavigationDrawerFragment.java
package com.pixalstudio.cakedekho;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
int i=0;
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private InfoAdapter adapter;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private View containerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new InfoAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.seven1, R.drawable.seven2, R.drawable.seven3, R.drawable.seven4};
String[] titles = {"Login", "Location", "Home", "About Us"};
for (int i=0; i < titles.length && i < icons.length; i++) ;
{
Information current = new Information();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
Information.java
package com.pixalstudio.cakedekho;
/**
* Created by akkie on 7/10/2015.
*/
public class Information {
int iconId;
String title;
}
InfoAdapter.java
package com.pixalstudio.cakedekho;
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.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by akkie on 7/10/2015.
*/
public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.MyViewHolder> {
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
public InfoAdapter(Context context, List<Information> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
customrow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:src="#drawable/seven1" />
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:text="Dummy Text" />
</LinearLayout>
fragment_navigation_drawer.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DADADA"
tools:context="com.pixalstudio.cakedekho.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FB8C00">
<ImageView
android:layout_width="240dp"
android:layout_height="140dp"
android:src="#drawable/ic_abstract1" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_below="#+id/containerDrawerImage"
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Please let me know if anyone needs any other information to fix my problem. Thank you in advance.

getView is not called

Hi all i have problemm that getView() is not called. Sup please. And in project i am using ViewPager. So maybe it's becouse of that
Here my MainActivity
package com.uinleader.animewatcher;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private List<View> pages;
private View recent;
private View top_seven;
private ViewPager mPager;
private final ArrayList<Parsed> info = new ArrayList<Parsed>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUi();
LVInit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(android.R.menu.main, menu);
return true;
}
private void initUi() {
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
recent = inflater.inflate(R.layout.recent, null);
recent.setTag(getString(R.string.recent));
top_seven = inflater.inflate(R.layout.top_seven, null);
top_seven.setTag(getString(R.string.top));
pages.add(recent);
pages.add(top_seven);
PAdapter adapter = new PAdapter(pages);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
mPager.setCurrentItem(0);
}
private void LVInit() {
LayoutInflater inflater = LayoutInflater.from(this);
Parsed one = new Parsed("One", "1", R.drawable.ic_launcher);
Parsed two = new Parsed("Two", "2", R.drawable.ic_launcher);
Parsed three = new Parsed("Three", "3", R.drawable.ic_launcher);
View v = inflater.inflate(R.layout.top_seven, null);
info.add(one);
info.add(two);
info.add(three);
ListView lv = (ListView) v.findViewById(R.id.listView1);
MArrayAdapter radapter = new MArrayAdapter(MainActivity.this, R.id.listView1, info);
lv.setAdapter(radapter);
}
}
Here is adapter
package com.uinleader.animewatcher;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by uinleader on 28.09.13.
*/
public class MArrayAdapter extends ArrayAdapter<Parsed> {
private final Activity activity;
private final ArrayList<Parsed> items;
public MArrayAdapter(Activity a, int textViewResourceId, ArrayList<Parsed> items) {
super(a, textViewResourceId, items);
activity = a;
this.items = items;
Log.e("ListViewDebug", "Inside Adapter");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.e("ListViewDebug", "Start Function");
View view = convertView;
ViewHolder holder;
if (view == null) {
Log.e("ListViewDebug", "In First IF");
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.anime_title);
holder.ep_num = (TextView) view.findViewById(R.id.ep_number);
holder.ep_preview = (ImageView) view.findViewById(R.id.ep_preview);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
Parsed item = items.get(position);
if(item!=null) {
holder.title.setText(item.anime_title);
holder.ep_num.setText("Episode: "+item.ep_num);
holder.ep_preview.setImageResource(item.img);
}
return view;
}
#Override
public int getCount() {
return items.size();
}
private static class ViewHolder {
public TextView title;
public TextView ep_num;
public ImageView ep_preview;
}
}
Here is my class for data. And XML's
package com.uinleader.animewatcher;
/**
* Created by uinleader on 28.09.13.
*/
public class Parsed {
public String anime_title;
public String ep_num;
public int img;
public Parsed (String anime_title, String ep_num, int img ){
this.anime_title = anime_title;
this.ep_num = ep_num;
this.img = img;
}
}
XML for list.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</ListView>
</LinearLayout>
XML for row's
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
>
<ImageView
android:layout_width="200px"
android:layout_height="200px"
android:id="#+id/ep_preview"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/anime_title"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/ep_preview" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ep_number"
android:layout_below="#+id/anime_title"
android:layout_toRightOf="#+id/ep_preview" />
</RelativeLayout>
The setContentView(R.layout.activity_main); already "inflates" the current layout the activity is using..i don't why you are inflating other stuff in the "init" methods, that is probably why nothing is being called because the activity remains displaying the view set on R.layout.activity_main.
ArrayAdapter works a bit differently than BaseAdapter - which is for what you're implementing your getView
I suggest several options to fix :
change your ArrayAdapter to BaseAdapter
or use the built in ArrayList that comes with the ArrayList adapter
in your constructor write the following :
public MArrayAdapter(Activity a, int textViewResourceId, ArrayList<Parsed> items) {
super(a, textViewResourceId, items); //<== call to super instantiates the items
activity = a;
//ArrayListAdapter has a built in arrayList - use it
Log.e("ListViewDebug", "Inside Adapter");
}
change your getView to this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.e("ListViewDebug", "Start Function");
View view = convertView; // **note why do you allocate again? just write convertview everywhere instead of view**
ViewHolder holder;
if (view == null) {
Log.e("ListViewDebug", "In First IF");
//**I recommend instantiating the inflater once inside the constructor**
LayoutInflater inflater =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.anime_title);
holder.ep_num = (TextView) view.findViewById(R.id.ep_number);
holder.ep_preview = (ImageView) view.findViewById(R.id.ep_preview);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
Parsed item = (Parsed)getItem(position); //<==== this
if(item!=null) {
holder.title.setText(item.anime_title);
holder.ep_num.setText("Episode: "+item.ep_num);
holder.ep_preview.setImageResource(item.img);
}
return
view;
}

Categories