I want to load some data from a website using Jsoup in my fragment activity and show the output in the Textview. I am using AsyncTask to load the data from a website using Jsoup but after successfully getting the data from the website the onPostExecute method in AsyncTask is not displaying the data. I have tried to debug it and it seems like the there is a problem in onPostExecute
and I don't know why.
Here is my code..
MainActivity2.java
package com.example.ebad.bustudentprofile;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.example.ebad.bustudentprofile.tabs.SlidingTabLayout;
public class MainActivity2 extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// Layout manager that allows the user to flip through the pages
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// getSupportFragmentManager allows use to interact with the fragments
// MyFragmentPagerAdapter will return a fragment based on an index that is passed
viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity2.this));
// Initialize the Sliding Tab Layout
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
// Connect the viewPager with the sliding tab layout
slidingTabLayout.setViewPager(viewPager);
}
}
MyFragmentPagerAdapter.java
package com.example.ebad.bustudentprofile;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = new String[]{"Tab 1", "Tab 2", "Tab 3"};
private Context context;
public MyFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return 3;
}
// Return the correct Fragment based on index
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new TabFragment1();
} else if (position == 1) {
return new TabFragment2();
} else if (position == 2) {
return new TabFragment3();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Return the tab title to SlidingTabLayout
return tabTitles[position];
}
}
TabFragment1.java
package com.example.ebad.bustudentprofile;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.util.HashMap;
public class TabFragment1 extends Fragment {
ProgressDialog progressDialoge;
TextView fa, na;
String urlw = "http://111.68.99.8/StudentProfile/PersonalInfo.aspx";
HashMap<String, String> hashMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
hashMap = Data.map;
//hashMap = (HashMap<String, String>) getArguments().get("hashMap");
View rootview = inflater.inflate(R.layout.tab_fragment_1, container, false);
Activity activity = getActivity();
fa = (TextView) rootview.findViewById(R.id.Fathere);
na = (TextView) rootview.findViewById(R.id.Y_Name);
new peea(activity,rootview).execute();
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
private class peea extends AsyncTask<Void, Void, Void> {
String father ;
String son ;
private Context activity;
private View rootView;
public peea(Context context, View main){
this.activity=context;
this.rootView=main;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialoge = new ProgressDialog(getActivity());
progressDialoge.setMessage("Getting into your information");
progressDialoge.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doce = Jsoup.connect(urlw)
.cookies(hashMap)
.get();
father = doce.select("span[id=ctl00_Body_FATHERNAME]").html();
son = doce.select("span[id=ctl00_Body_NAME]").html();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPreExecute();
TextView wa = (TextView)rootView.findViewById(R.id.Y_Name);
wa.setText(son);
/*fa.setText(father);
na.setText(son);*/
/*fa = (TextView)findViewById(R.id.das);
fa.setText(father);*/
progressDialoge.dismiss();
}
}
}
tab_fragment_1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/Fathere"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Father Name"
android:textSize="25dp" />
<TextView
android:id="#+id/Y_Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Your name"
android:textSize="30dp" />
</LinearLayout>
If you guys tell where the problem is or how to solve it, it will be very helpful to me
I don't think that your super class has an onPreExecute function, so
super.onPreExecute();
may be causing you some issues. You can try
super.onPostExecute();
That may be fix it.
Related
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);
i have created the online wallpaper application and i used to activity for my app and i use volley and glide for my app but when i use bottom navigation drawer , activity is not useful .
after that i use fragment but now when i run application my recyclerview doesn't show anything
MainFragment.java:
package ir.zooding.wallpaper.activity;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.adapter.GalleryAdapter;
import ir.zooding.wallpaper.app.AppController;
import ir.zooding.wallpaper.model.Image;
import ir.zooding.wallpaper.receiver.ConnectivityReceiver;
public class MainFragment extends Fragment implements ConnectivityReceiver.ConnectivityReceiverListener {
RecyclerView recycler_view;
static final String url="";
ArrayList<Image> images;
GalleryAdapter mAdapter;
ProgressDialog pd;
View v;
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
Toolbar toolbar=(Toolbar)v.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
recycler_view=(RecyclerView) v.findViewById(R.id.recycler_view);
pd=new ProgressDialog(getActivity());
pd.setCancelable(false);
images=new ArrayList<>();
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
RecyclerView.LayoutManager mLayoutManager=new GridLayoutManager(getActivity().getApplicationContext(),2);
recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setAdapter(mAdapter);
Log.i("LOG:","stop 1");
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
recycler_view.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getActivity().getApplicationContext(),recycler_view, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle=new Bundle();
bundle.putSerializable("images",images);
bundle.putInt("position",position);
//Log.i("LOG:",""+position);
// FragmentTransaction ft=getFragmentManager().beginTransaction();
android.app.FragmentTransaction ft=getActivity().getFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment=SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft,"slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
checkConnection();
fetchImages();
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "دسترسی به حافظه داخلی لغو شد!!!", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void fetchImages()
{
pd.setMessage("در حال بارگزاری ...");
pd.show();
StringRequest req = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("", response.toString());
pd.dismiss();
images.clear();
try {
JSONObject object = new JSONObject(response);
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataObject = dataArray.getJSONObject(i);
Image image = new Image();
image.setName_client(dataObject.getString("name_client"));
image.setName(dataObject.getString("name"));
// JSONObject url = object.getJSONObject("url");
image.setSmall(dataObject.getString("small"));
image.setOriginal(dataObject.getString("orginal"));
image.setTimestamp(dataObject.getString("timestamp"));
images.add(image);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("LOG:","stop 2");
mAdapter.notifyDataSetChanged();
Log.i("LOG:","stop 3");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("", "Error: " + error.getMessage());
pd.dismiss();
}
});
AppController.getmInstance().addToRequsetQueue(req);
}
// Method to manually check connection status
private void checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
}
// Showing the status in Snackbar
private void showSnack(boolean isConnected) {
String message ="";
//View parentLayout = v.findViewById(android.R.id.content);
RelativeLayout parentLayout = (RelativeLayout)v.findViewById(R.id.mroot);
if (!isConnected) {
message = "اتصال شما به اینترنت برقرار نیست!";
Snackbar snackbar = Snackbar
.make(parentLayout, message, Snackbar.LENGTH_LONG)
.setAction("بررسی مجدد", new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchImages();
checkConnection();
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.setActionTextColor(Color.parseColor("#e62d3f"));
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.parseColor("#FFC107"));
snackbar.setDuration(8000);
snackbar.show();
}
}
#Override
public void onResume() {
super.onResume();
// register connection status listener
AppController.getmInstance().setConnectivityListener(this);
}
/**
* Callback will be triggered when there is change in
* network connection
*/
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
}
GalleryAdapter.java:
package ir.zooding.wallpaper.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.model.Image;
import static android.R.animator.fade_in;
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
List<Image> images;
Context mContext;
public GalleryAdapter (Context context,List<Image> images){
this.images = images;
mContext = context;
}
#Override
public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_thumbnail,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(GalleryAdapter.MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getSmall())
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.loading)
.fitCenter()
.into(holder.thumbnail);
}
#Override
public int getItemCount() {
return images.size();
}
public interface ClickListener{
void onClick (View view,int position);
void onLongClick (View view,int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
GalleryAdapter.ClickListener clickListener;
GestureDetector gestureDetector;
public RecyclerTouchListener(Context context,final RecyclerView recyclerView,final GalleryAdapter.ClickListener clickListener){
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e){
return true;
}
#Override
public void onLongPress(MotionEvent e){
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if(child != null && clickListener != null){
clickListener.onLongClick(child,recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(),e.getY());
if(child != null && clickListener != null&& gestureDetector.onTouchEvent(e)){
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail =(ImageView) view.findViewById(R.id.thumbnail);
}
}
}
MainActivity.java:
package ir.zooding.wallpaper.activity;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import ir.adad.client.Adad;
import ir.zooding.wallpaper.R;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Adad.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = MainFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = CategoryFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = InfoFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, MainFragment.newInstance());
transaction.commit();
//Used to select an item programmatically
//bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
}
fragment_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/mroot"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/include"
layout="#layout/content_main"/>
content_main.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?attr/actionBarSize">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="vertical"/>
There are Contexts considerations you need to make throught your code. You may be using the wrong Contexts example very big Contexts. For example from what I can see fast one of it is this line in MainFragment.java:
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
You have passed the application context while you need just Context from Activity. So change that to:
mAdapter=new GalleryAdapter(getActivity(),images); // remove the method getApplicationContext
Try doing that if it will work or else lets try finding more code that may bring a problem.
i have created an app which contain number of buttons and each button is connected with number of photos (image slider (i think i am using image slider using viewerpage)) ....... it works perfectly on some devices such as 6.0.1 but when i am tring to use it on another devices such as 4.2.2 it stops immediately once i click on the butuon and here and i have done in xml (it's name tip_3)
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
and i have created another xml ( as the walk-through in the youtube ) (xml name algwhra )
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
and here is the java for (tips_3) :
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Tips_3 extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_3);
viewPager = (ViewPager) findViewById(R.id.viewPager);
AlGwhra viewPagerAdapter = new AlGwhra(this);
viewPager.setAdapter(viewPagerAdapter);
}
}
and here is the (algwhra) java :
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import javax.xml.transform.Result;
/**
* Created by Hassan on 12-Jul-17.
*/
public class AlGwhra extends PagerAdapter{
private Context context;
private LayoutInflater layoutInflater;
private Integer[] images ={R.drawable.g1,R.drawable.g2,R.drawable.g3,R.drawable.g4,R.drawable.g5,R.drawable.g6,R.drawable.g7,R.drawable.g8,R.drawable.g9,R.drawable.g10,R.drawable.g11,R.drawable.g12,R.drawable.g13};
public AlGwhra(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.algwhra, null);
ImageView imageView =(ImageView) view.findViewById(R.id.imageView2);
imageView.setImageResource(images[position]);
ViewPager vp =(ViewPager) container;
vp.addView(view ,0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp =(ViewPager) container;
View view =(View) object;
vp.removeView(view);
}
}
I have some weird Stackoverflowerror which is thrown in the onCreateView() method of a Fragment i use.
As you can see in this image, that is the method where it breaks. The First TODO should be where the error comes from.
I have no idea what could be wrong with that line:
view = inflater.inflate(R.layout.activity_chat, container, false); //it breaks here
I would be very glad to hear any tipps from anyone.
Edit: this is another strange errorreport i got after the initial error:
Edit: Content of Activity_chat.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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_bright"
android:orientation="vertical">
<fragment
android:id="#+id/msg_list"
android:name="com.example.f00.mobileapp.listener.TabFragment2"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
tools:layout="#layout/tab_fragment_2" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_green_dark">
<Button
android:id="#+id/send_btn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Send" />
<EditText
android:id="#+id/msg_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/send_btn"
android:layout_toLeftOf="#+id/send_btn"/>
</RelativeLayout>
</LinearLayout>
Edit: TabFragment2.java:
package com.example.f00.mobileapp.listener;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.f00.mobileapp.R;
import com.example.f00.mobileapp.activities.MainActivity;
import com.example.f00.mobileapp.application.Common;
import com.example.f00.mobileapp.fragments.EditContactDialog;
import com.example.f00.mobileapp.fragments.MessagesFragment;
import com.example.f00.mobileapp.utils.AsyncResponse;
import com.example.f00.mobileapp.utils.DataProvider;
import com.example.f00.mobileapp.utils.GcmUtil;
import com.example.f00.mobileapp.utils.Utils;
import java.io.IOException;
import java.util.Random;
// Chat chat real chat.
public class TabFragment2 extends Fragment implements MessagesFragment.OnFragmentInteractionListener,
EditContactDialog.OnFragmentInteractionListener, View.OnClickListener {
View view;
private EditText msgEdit;
private Button sendBtn;
private String profileId;
private String profileName;
private String profileEmail;
private GcmUtil gcmUtil;
public Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.tab_fragment_2, container, false); //TODO this it where it breaks
//////////////
profileId = getActivity().getIntent().getStringExtra(Common.PROFILE_ID);
msgEdit = (EditText) getActivity().findViewById(R.id.msg_edit);
sendBtn = (Button) getActivity().findViewById(R.id.send_btn);
sendBtn.setOnClickListener(this);
android.app.ActionBar actionBar = getActivity().getActionBar(); //TODO
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Cursor c = getActivity().getContentResolver().query(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), null, null, null, null);
if (c.moveToFirst()) {
profileName = c.getString(c.getColumnIndex(DataProvider.COL_NAME));
profileEmail = c.getString(c.getColumnIndex(DataProvider.COL_EMAIL));
actionBar.setTitle(profileName);
}
actionBar.setSubtitle("connecting ...");
getActivity().registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
gcmUtil = new GcmUtil(getActivity().getApplicationContext());
///////////
return view;
}
/*
/**
* The important piece of code is in onCreate() where we instantiate GcmUtil.
* This triggers registration with GCM if it's not already done.
* Recall that GcmUtil broadcasts the registration status which this activity
* registers to listen.
*
* #param savedInstanceState
*/
/* #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.activity_chat);
getActivity().getIntent().getStringArrayExtra(Common.PROFILE_ID);
profileId = getActivity().getIntent().getStringExtra(Common.PROFILE_ID);
msgEdit = (EditText) getActivity().findViewById(R.id.msg_edit);
sendBtn = (Button) getActivity().findViewById(R.id.send_btn);
sendBtn.setOnClickListener(this);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Cursor c = getContentResolver().query(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), null, null, null, null);
if (c.moveToFirst()) {
profileName = c.getString(c.getColumnIndex(DataProvider.COL_NAME));
profileEmail = c.getString(c.getColumnIndex(DataProvider.COL_EMAIL));
actionBar.setTitle(profileName);
}
actionBar.setSubtitle("connecting ...");
registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
gcmUtil = new GcmUtil(getApplicationContext());
}*/
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.chat, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
EditContactDialog dialog = new EditContactDialog();
Bundle args = new Bundle();
args.putString(Common.PROFILE_ID, profileId);
args.putString(DataProvider.COL_NAME, profileName);
dialog.setArguments(args);
dialog.show(getActivity().getSupportFragmentManager(), "EditContactDialog");
return true;
case android.R.id.home:
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_btn:
send(msgEdit.getText().toString());
msgEdit.setText(null);
break;
}
}
#Override
public void onEditContact(String name) {
getActivity().getActionBar().setTitle(name); //TODO
}
#Override
public String getProfileEmail() {
return profileEmail;
}
/**
* Finally to send a message we post the data to our server asynchronously.
*
* #param txt
*/
private void send(final String txt) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Utils sendMsg = new Utils(new AsyncResponse() {
#Override
public void asyncResponse(Object output, boolean status) {
}
});
//TODO
sendMsg.sendChatMessage(System.identityHashCode(new Random()), txt, getActivity().getApplicationContext());
/* ServerUtilities.send(txt, profileEmail);
ContentValues values = new ContentValues(2);
values.put(DataProvider.COL_TYPE, DataProvider.MessageType.OUTGOING.ordinal());
values.put(DataProvider.COL_MESSAGE, txt);
values.put(DataProvider.COL_RECEIVER_EMAIL, profileEmail);
values.put(DataProvider.COL_SENDER_EMAIL, Common.getPreferredEmail());
values.put(DataProvider.COL_ID, System.currentTimeMillis());
getContentResolver().insert(DataProvider.CONTENT_URI_MESSAGES, values);
*/
} catch (IOException ex) {
msg = "Message could not be sent";
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
if (!TextUtils.isEmpty(msg)) {
Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
}.execute(null, null, null);
}
public void sendNewOrder(final String text) {
//TODO
}
#Override
public void onPause() {
ContentValues values = new ContentValues(1);
values.put(DataProvider.COL_COUNT, 0);
getActivity().getContentResolver().update(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), values, null, null);
super.onPause();
}
#Override
public void onDestroy() {
getActivity().unregisterReceiver(registrationStatusReceiver);
gcmUtil.cleanup();
super.onDestroy();
}
/**
*
*/
{ }
private BroadcastReceiver registrationStatusReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
switch (intent.getIntExtra(Common.EXTRA_STATUS, 100)) {
case Common.STATUS_SUCCESS:
getActivity().getActionBar().setSubtitle("online");
break;
case Common.STATUS_FAILED:
getActivity().getActionBar().setSubtitle("offline");
break;
}
}
}
};
}
I think you are doing a lot of things in your onCreateView - My recommendation is that you move the rest of the code in the onActivityCreated(Bundle savedInstanceState). Change the onCreateView into:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_chat, container, false);
return rootView;
}
Then you can move the rest of the code to onActivityCreated. This method is called after the onCreateView() method when the host activity is created.
Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method.
So I was faced with yet another "surprise" problem when writing your application. I know that there ListFragment, but using a Fragment. When I put the markup for a fragment of a ListView, when you call the adapter in the list does not function adds elements - not a cunning way I tracked on the logs that you do not call getView (). What is more interesting - if I do not use instead of just a list of the fragment and you add the adapter works well when everything - the list is filled. I can not understand why this is happening - why in the fragment list of works not adequate.
activity_start.xml
<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:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:scrollbars="vertical"
android:scrollbarStyle="insideInset"
android:gravity="center_vertical"
android:orientation="vertical"
android:background="#e8e8e8"
>
<Button
android:id="#+id/button_add_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableRight="#drawable/green_add"
android:drawablePadding="5dp"
android:text="ADD URL"
/>
<LinearLayout
android:id="#+id/linear_layout_list_show_monitor_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border_background"
android:orientation="vertical"
android:padding="1dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
>
<!-- <ListView
android:id="#+id/list_view_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/> -->
<fragment
android:id="#+id/fragment_list"
android:name="pront.android.exservice.FragmentList"
android:layout_width="match_parent"
android:layout_height="300dp"/>
</LinearLayout>
StartActivity.java
import java.util.ArrayList;
import pront.android.exservice.FragmentDialogAddNewUrl.FragmentDialogAddNewUrlConectActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout.LayoutParams;
import android.widget.Toast;
public class StartActivity
extends FragmentActivity
implements OnClickListener,
FragmentDialogAddNewUrlConectActivity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.getWindow().addFlags
(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_start);
listViewUrl = (ListView) findViewById(R.id.list_view_fragment);
screenWidthPx = this.getResources().getDisplayMetrics().widthPixels;
screenHeightPx = this.getResources().getDisplayMetrics().heightPixels;
layoutMarginPx = 16;
screenDp = this.getResources().getDisplayMetrics().density;
layoutMarginDp = (int)(layoutMarginPx*screenDp);
typefaceRoboto = Typeface.createFromAsset(getAssets(),
"Roboto-Thin.ttf");
LinearLayout linearLayout = (LinearLayout)
findViewById(R.id.linear_layout_list_show_monitor_url);
LayoutParams layoutParams =
new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(layoutMarginDp, layoutMarginDp,
layoutMarginDp, layoutMarginDp);
linearLayout
.setLayoutParams(layoutParams);
buttonAddUrl = (Button) findViewById(R.id.button_add_url);
buttonAddUrl.setTypeface(typefaceRoboto, Typeface.BOLD);
buttonAddUrl.setOnClickListener(this);
broadcastReceiver = new MyBroadcastReceiver();
intentFilter = new IntentFilter(BROADCAST);
registerReceiver(broadcastReceiver, intentFilter);
}
public void onStart(){
super.onStart();
}
public void onRestart(){
super.onRestart();
}
public void onResume(){
super.onResume();
}
public void onPause(){
super.onPause();
}
public void onStop(){
super.onStop();
}
public void onDestroy(){
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
#Override
public void onBackPressed(){
super.onBackPressed();
}
public void onClick(View view) {
if(view.getId() == R.id.button_add_url){
buttonAddUrl.setClickable(false);
fragmentDialogAddNewUrl = new FragmentDialogAddNewUrl();
fragmentDialogAddNewUrl.show(this.getSupportFragmentManager(),
"fragmentDialogAddNewUrl");
buttonAddUrl.setClickable(true);
}
}
public void fragmentDialogClickButtonListener(String url,
String pathFavIcon)
{
fragmentDialogAddNewUrl.onDestroyView();
this.url = url;
Toast toastInfo = Toast
.makeText(this.getApplicationContext(),
"Service start monitor\n"+url,
Toast.LENGTH_LONG);
toastInfo.setGravity(Gravity.TOP, 0, 0);
toastInfo.show();
arrayListUrl.add(new UrlBox(this.getApplicationContext(),
url,
pathFavIcon));
Log.d("StartActivity", "fragmentDialogClick...() listViewUrl.setAdapter()");
FragmentList fragmentList = (FragmentList) this.getSupportFragmentManager().findFragmentById(R.id.fragment_list);
fragmentList.setAdapter(arrayListUrl);
// MyListAdapter adapter = new MyListAdapter(this, R.layout.expandable_list_view_child_item, arrayListUrl);
// adapter.notifyDataSetChanged();
// listViewUrl.setAdapter(adapter);
}
public static class MyBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.d("", intent.getIntExtra("RESULT", 0)+"");
}
}
private Button buttonAddUrl;
private ListView listViewUrl;
private MyBroadcastReceiver broadcastReceiver;
private IntentFilter intentFilter;
private Typeface typefaceRoboto;
private DialogFragment fragmentDialogAddNewUrl;
private MyListAdapter myListAdapter = null;
private ArrayList<UrlBox> arrayListUrl = new ArrayList<UrlBox>();
private int layoutMarginPx;
private float screenDp;
private int screenWidthPx;
private int screenHeightPx;
private int layoutMarginDp;
private ArrayList<String> childUrl = new ArrayList<String>();
private ArrayList<Drawable> childFavIcon = new ArrayList<Drawable>();
private String url;
private final static String BROADCAST = "pront.android.exservice";
}
FragmentList.java
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class FragmentList extends Fragment {
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
listView = (ListView) inflater.inflate(R.layout.layout_fragment_list, null, false).findViewById(R.id.list_view_fragment);
return inflater.inflate(R.layout.layout_fragment_list, null, false);
}
public void setAdapter(ArrayList<UrlBox> arrayList){
listAdapter = new MyListAdapter(getActivity(), R.layout.expandable_list_view_child_item, arrayList);
listAdapter.notifyDataSetChanged();
if(listView != null){
listView.setAdapter(listAdapter);
System.out.println("set adapter");
}
}
MyListAdapter listAdapter;
ListView listView;
}
MyListAdapter.java
import java.util.ArrayList;
import android.app.Activity;
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;
public class MyListAdapter extends ArrayAdapter{
MyListAdapter(Activity context, int layoutResourceId, ArrayList<UrlBox> arrayList) {
super(context, layoutResourceId);
Log.d("MyListAdapter", "constructor");
this.context = context;
this.arrayListUrlBox = arrayList;
this.layoutResourceId = layoutResourceId;
}
#Override
public View getView (int position, View convertView, ViewGroup parent){
Log.d("MyListAdapter", "getView");
View returnView = convertView;
ListItemTagHolder tag = null;
if(convertView == null){
LayoutInflater inflater = context.getLayoutInflater();
returnView = inflater.inflate(layoutResourceId, null, false);
tag = new ListItemTagHolder();
tag.ImageViewFavicon = (ImageView) returnView.findViewById(R.id.image_view_favicon);
tag.ImageViewStatus = (ImageView) returnView.findViewById(R.id.image_view_status);
tag.TextViewUrl = (TextView) returnView.findViewById(R.id.text_view_url);
returnView.setTag(tag);
}
else{
tag = (ListItemTagHolder) returnView.getTag();
}
tag.ImageViewFavicon.setImageDrawable(arrayListUrlBox.get(position).getDrawableFavIcon());
tag.ImageViewStatus.setImageDrawable(arrayListUrlBox.get(position).getDrawableFavIcon()); // !
tag.TextViewUrl.setText(arrayListUrlBox.get(position).getUrl());
return returnView;
}
#Override
public int getCount() {
return arrayListUrlBox.size();
}
public UrlBox getItem(int position) {
return arrayListUrlBox.get(position);
}
private ArrayList<UrlBox> arrayListUrlBox;
private Activity context;
private int layoutResourceId;
static class ListItemTagHolder{
protected ImageView ImageViewFavicon;
protected ImageView ImageViewStatus;
protected TextView TextViewUrl;
}
}
The issue is related to MyListAdapter. You have two options:
Override getCount() and let it returns the number of items in your dataset
Pass to the super() your dataset
For instance, in your adapter:
#Override
public int getCount() {
return arrayListUrlBox.size();
}
or inside MyListAdapter constructor you can call:
super(context, layoutResourceId, arrayList);
instead of
super(context, layoutResourceId);
Hi modify your MyListAdapter as below
public class MyListAdapter extends ArrayAdapter**<UrlBox>** {
MyListAdapter(Activity context, int layoutResourceId, ArrayList<UrlBox> arrayList) {
super(context, layoutResourceId, arrayList);
Log.d("MyListAdapter", "constructor", **arrayList**);
this.context = context;
this.arrayListUrlBox = arrayList;
this.layoutResourceId = layoutResourceId;
}
....<continue with rest part of your code>...
There is 2 places i have changed.. Hope this will do the work.