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.
Related
I want to create tags using RecyclerView that can be selected to produce results.
What I want to achieve is when I tap on Books TextView on the top-right must change to Books immediately. In my case when I tap on Books it just stays in Art and it replaces Art with Books only when I replace my fragments. I also highlight buttons when clicked (changing border from grey to black) but after changing fragments highlights return back to Art again. Shortly I want to highlight button when clicked and change TextView content based on clicked button text. I partly achieved it by using interfacews but didn't get what I wanted. I provided codes below:
TrendCategoryTagsAdapter.java:
public class TrendCategoryTagsAdapter extends FirestoreRecyclerAdapter<CategorySelection, TrendCategoryTagsAdapter.TrendCategoryTagsHolder> {
Context context;
onCategoryTagClicked onCategoryTagClicked;
int row_index;
public TrendCategoryTagsAdapter(#NonNull FirestoreRecyclerOptions<CategorySelection> options, Context context, com.rajabmammadli.paragrafredesign.Interface.onCategoryTagClicked onCategoryTagClicked) {
super(options);
this.context = context;
this.onCategoryTagClicked = onCategoryTagClicked;
}
#Override
protected void onBindViewHolder(#NonNull final TrendCategoryTagsHolder holder, final int position, #NonNull CategorySelection model) {
holder.categoryNameText.setText(model.getCategoryName());
holder.categoryNameContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
row_index = position;
notifyDataSetChanged();
}
});
if (row_index == position) {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.black_rounded_bg));
onCategoryTagClicked.onTagClick(holder.categoryNameText.getText().toString());
} else {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.grey_rounded_bg));
}
}
#NonNull
#Override
public TrendCategoryTagsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.trendcategory_cell, parent, false);
return new TrendCategoryTagsAdapter.TrendCategoryTagsHolder(v);
}
public static class TrendCategoryTagsHolder extends RecyclerView.ViewHolder {
RelativeLayout categoryNameContainer;
TextView categoryNameText;
public TrendCategoryTagsHolder(#NonNull View itemView) {
super(itemView);
categoryNameContainer = itemView.findViewById(R.id.categoryNameContainer);
categoryNameText = itemView.findViewById(R.id.categoryNameText);
}
}
}
trendcategory_cell.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<RelativeLayout
android:id="#+id/categoryNameContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/grey_rounded_bg">
<TextView
android:id="#+id/categoryNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/gilroyregular"
android:padding="15dp"
android:text="categoryname"
android:textColor="#android:color/black" />
</RelativeLayout>
</RelativeLayout>
TrendingFragment.java:
public class TrendingFragment extends Fragment implements onCategoryTagClicked {
RecyclerView trendingCategoryRV;
TextView noPostTV, selectedCategoryText;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference categoryRef;
String selectedCategory = "Art";
TrendCategoryTagsAdapter trendCategoryTagsAdapter;
public TrendingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_trending, container, false);
trendPostRV = view.findViewById(R.id.trendPostRV);
trendingCategoryRV = view.findViewById(R.id.trendingCategoryRV);
noPostTV = view.findViewById(R.id.noPostTV);
selectedCategoryText = view.findViewById(R.id.selectedCategoryText);
selectedCategoryText.setText(selectedCategory);
setUpTrendCategoryTagsRV();
setUpTrendingPostRV();
// Inflate the layout for this fragment
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
trendCategoryTagsAdapter.startListening();
}
#Override
public void onDestroyView() {
super.onDestroyView();
trendCategoryTagsAdapter.stopListening();
}
private void setUpTrendCategoryTagsRV() {
categoryRef = db.collection("Categories");
Query query = categoryRef.orderBy("categoryName", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<CategorySelection> options = new FirestoreRecyclerOptions.Builder<CategorySelection>()
.setQuery(query, CategorySelection.class)
.build();
trendCategoryTagsAdapter = new TrendCategoryTagsAdapter(options, getContext(), this);
trendingCategoryRV.setNestedScrollingEnabled(false);
final LinearLayoutManager trendingTagsLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
trendingCategoryRV.setLayoutManager(trendingTagsLM);
trendingCategoryRV.setAdapter(trendCategoryTagsAdapter);
trendCategoryTagsAdapter.notifyDataSetChanged();
}
#Override
public void onTagClick(String categoryName) {
selectedCategory = categoryName;
}
}
Any help will be appreciated. Thanks in advance
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);
I am making an android app in which when an image is clicked, then it blurs and shows play and other options on the top of it. I am using a external library (https://github.com/daimajia/AndroidViewHover) for this particular effects but my problem is generic in nature.
Problem Statement:-
I am handling click event on the play option shown by the Blur surface i.e hover_sample.xml in the adapter (TrendingAdapter.java) and i want to call function for playing youtube video (public void openWebView(TrendingData image)) that is in fragment (TrendingFragment.java). So, essentially i want to access function in the fragment from its adapter.
I have tried various method but its not working. Code sample is as following.
TrendingFragment.java:-
public class TrendingFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterCallback {
private GridView mGridView;
private TrendingAdapter mAdapter;
private String movieJson;
private String caption;
Activity MyActivity = getActivity();
public static TrendingFragment getInstance() {
TrendingFragment fragment = new TrendingFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate( R.layout.activity_trending_fragment, container, false );
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mGridView = (GridView) view.findViewById( R.id.grid );
mGridView.setOnItemClickListener( this );
mGridView.setDrawSelectorOnTop( true );
TrendingActivity activity = (TrendingActivity) getActivity();
movieJson = activity.getMovieJson();
caption = activity.getNewCaption();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new TrendingAdapter( getActivity(), 0, this);
mGridView.setAdapter(mAdapter);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(movieJson)
.build();
TrendingApiInterface trendingApiInterface = restAdapter.create( TrendingApiInterface.class );
trendingApiInterface.getStreams(new Callback<List<TrendingData>>() {
#Override
public void success(List<TrendingData> galleryImages, Response response) {
if (galleryImages == null || galleryImages.isEmpty() || !isAdded() )
return;
for (TrendingData image : galleryImages) {
mAdapter.add(image);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void failure(RetrofitError error) {
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TrendingData image = (TrendingData) parent.getItemAtPosition( position );
openWebView(image);
}
public void openWebView(TrendingData image) {
try {
Intent intent = YouTubeStandalonePlayer.createVideoIntent(getActivity(), Config.YOUTUBE_API_KEY, image.getImage());
startActivity(intent);
}//If Youtube app is not present then open in webview
catch (ActivityNotFoundException ex){
Toast.makeText(getActivity(), "Please wait for few minutes.Its Loading...", Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), "Latest Youtube Player is missing on your device.Opening in WebView.Download it for better experience", Toast.LENGTH_LONG).show();
String complete_url="https://www.youtube.com/watch?v=";
Intent intent = new Intent(getActivity(), webView.class );
intent.putExtra( webView.EXTRA_IMAGE, complete_url+image.getImage());
intent.putExtra( webView.PREVIOUS_ACTIVITY, "TrendingActivity.class");
intent.putExtra(webView.EXTRA_CAPTION, image.getCaption());
intent.putExtra( webView.EXTRA_BG_IMAGE, image.getBgImage());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//finish();
startActivity(intent);
}
}
#Override
public void onMethodCallback(AdapterView<?> parent, View view, int position, long id) {
TrendingData image = (TrendingData) parent.getItemAtPosition( position );
openWebView(image);
}
}
TrendingAdapter.java:-
public class TrendingAdapter extends ArrayAdapter {
TrendingFragment lfg;
TrendingData image;
private AdapterCallback mAdapterCallback;
public TrendingAdapter(Context context, int resource, AdapterCallback callback) {
super(context, resource);
this.mAdapterCallback = callback;
}
//hover image
private BlurLayout mSampleLayout ;
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
if( convertView == null ) {
holder = new ViewHolder();
convertView = LayoutInflater.from( getContext() ).inflate( R.layout.activity_trending_adapter, parent, false );
holder.image = (ImageView) convertView.findViewById( R.id.image );
holder.caption=(TextView) convertView.findViewById(R.id.textView);
//holder.progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
convertView.setTag(holder);
BlurLayout.setGlobalDefaultDuration(450);
mSampleLayout = (BlurLayout)convertView.findViewById(R.id.blur_layout);
final View hover = LayoutInflater.from(getContext()).inflate(R.layout.hover_sample, null);
holder.play = (ImageView)hover.findViewById(R.id.heart);
holder.playList = (ImageView)hover.findViewById(R.id.share);
hover.findViewById(R.id.heart).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YoYo.with(Techniques.Tada)
.duration(550)
.playOn(v);
}
});
hover.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YoYo.with(Techniques.Swing)
.duration(550)
.playOn(v);
}
});
mSampleLayout.setHoverView(hover);
mSampleLayout.setBlurDuration(550);
mSampleLayout.addChildAppearAnimator(hover, R.id.heart, Techniques.FlipInX, 550, 0);
mSampleLayout.addChildAppearAnimator(hover, R.id.share, Techniques.FlipInX, 550, 250);
mSampleLayout.addChildAppearAnimator(hover, R.id.more, Techniques.FlipInX, 550, 500);
mSampleLayout.addChildDisappearAnimator(hover, R.id.heart, Techniques.FlipOutX, 550, 500);
mSampleLayout.addChildDisappearAnimator(hover, R.id.share, Techniques.FlipOutX, 550, 250);
mSampleLayout.addChildDisappearAnimator(hover, R.id.more, Techniques.FlipOutX, 550, 0);
mSampleLayout.addChildAppearAnimator(hover, R.id.description, Techniques.FadeInUp);
mSampleLayout.addChildDisappearAnimator(hover, R.id.description, Techniques.FadeOutDown);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ViewHolder tmp = holder;
Picasso.with(getContext()).load(getItem(position).getThumbnail())
.placeholder(getContext().getResources().getDrawable(R.drawable.place)).
error(getContext().getResources().getDrawable(R.drawable.place)).
into(holder.image);
return convertView;
}
private class ViewHolder {
ImageView image;
ProgressBar progress;
TextView caption;
ImageView play;
ImageView playList;
}
}
hover_sample.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">
<LinearLayout
android:id="#+id/animation_area"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="match_parent">
<ImageView
android:layout_marginRight="20dp"
android:id="#+id/heart"
android:src="#drawable/heart"
android:layout_width="50dp"
android:layout_height="50dp" />
<ImageView
android:id="#+id/share"
android:layout_marginRight="20dp"
android:src="#drawable/share"
android:layout_width="50dp"
android:layout_height="50dp"/>
<ImageView
android:id="#+id/more"
android:src="#drawable/more"
android:layout_width="50dp"
android:layout_height="50dp"/>
</LinearLayout>
<TextView
android:id="#+id/description"
android:text="Parse PHP SDK"
android:layout_marginLeft="12dp"
android:textColor="#ffffff"
android:layout_marginBottom="12dp"
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Please suggest how the same can be achieved. I have tried various way suggested in this form for similar question but without any success.
Use a callback method. Create an interface. Let your fragment implement it. Pass the callback to adapter in it's constructor. Adapter uses callback to call interface method from which you can call webview().
See How to create interface between fragment and adapter.
While calling any adapter's method from fragment, you can use adapter's instance but communication from adapter to fragment should be done with callbacks.
As suggested by cgr in above post, I created an interface to communicate between Fragment & it's Adapter. Follow link shared by cgr. It's awesome.
Interface definition:-
void onMethodCallback(String url, String caption, String bgImage);
Then, used the callback function in the adapter class as:-
mAdapterCallback.onMethodCallback(getItem(position).getImage(), getItem(position).getCaption(),getItem(position).getBgImage());
This resolved my problem. Now, I am successfully able to call any function in the adapter class from it's fragment class.
I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>
I'm very new to android and I was given a prewritten app that I must improve. One thing I have to do is add a delete button to each item in a ListView.
Here is the XML for my ListView element:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<ImageView
android:id="#+id/li_map_image"
android:layout_width="50dp"
android:layout_height="match_parent"
android:contentDescription="thumbnail" />
<TextView
android:id="#+id/li_map_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:paddingLeft="8dp"
android:textSize="16sp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/delete"
android:focusableInTouchMode="true"
android:background="#drawable/red_x"
android:layout_gravity="center|left"
android:onClick="deleteMap"></ImageButton>
Basically, I want the user to click the delete icon if they want to delete a row in the ListView. Also, this should delete the item's data from the database. I'm very confused about how to implement this because I don't know how I will know which delete button they are clicking. Also, when I added the ImageButton to the ListView code, it tells me to make the onClick method in main (should it be in main?); but how will I be able to delete data from the database? Also, Main Activity has a Fragment which obtains the ListView code. This is the Fragment class:
public class MapListFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int LOADER_ID = 1;
private static final String[] FROM = { Database.Maps.DATA,
Database.Maps.NAME };
private static final String[] CURSOR_COLUMNS = { Database.Maps.ID,
Database.Maps.DATA, Database.Maps.NAME };
private static final int[] TO = { R.id.li_map_image, R.id.li_map_name };
private SimpleCursorAdapter mAdapter;
// FIXME isn't this unnecessary?
public MapListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// FIXME reverse the order so the newest sessions are at the top
mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.map_list_item, null, FROM, TO, 0);
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.li_map_image) {
((ImageView) view).setImageURI(Uri.parse(cursor
.getString(columnIndex)));
return true;
}
return false;
}
});
setListAdapter(mAdapter);
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public void onListItemClick(ListView list, View v, int position, long id) {
final Intent nextIntent = new Intent(getActivity(),
ViewMapActivity.class);
nextIntent.putExtra(Utils.Constants.MAP_ID_EXTRA, id);
startActivity(nextIntent);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), DataProvider.MAPS_URI,
CURSOR_COLUMNS, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (loader.getId() == LOADER_ID)
mAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
I'm very lost as how to implement this delete feature. Any help will be much appreciated :)
here is a very good tutorial on how to put a clicklistener on a button inside listview.
follow this link
inside your adapter getView method, you need to put click listener on button like this
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.child_listview, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView
.findViewById(R.id.childTextView);
viewHolder.button = (Button) convertView
.findViewById(R.id.childButton);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position,temp);
}
}
});
return convertView;
}
Add Longclicklistner in Your Listview
try this , it may help you
Link