OnBack Button inside fragment - android

how i can add an onback pressed button. On this activity appears the image of the onBack pressed button but not works. i have tried some methods but i can not resolve my problem. Hope you can help me. Thank you
here is the code :
public class MyAdsActivity extends Fragment{
public static MyAdsActivity newInstance(String param1, String param2) {
MyAdsActivity fragment = new MyAdsActivity();
return fragment;
}
public MyAdsActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private OnFragmentInteractionListener mListener;
Toolbar toolbar;
ListView lsv;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
String advertId;
public static boolean refreshFlag = false;
private SharedPreferences pref;
private AdView mAdView;
FloatingActionButton fabAddAds;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_myads, container, false);
typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/GandhiSerif-Bold.otf");
fabAddAds = (FloatingActionButton) view.findViewById(R.id.fabAddAds);
mAdView = (AdView)view.findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
pref = this.getActivity().getSharedPreferences("loginpreference", getActivity().MODE_PRIVATE);
advertId = pref.getString("advertId","");
lsv = (ListView)view.findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
fabAddAds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity() ,AddPostActivity.class));
}
});
new MyAdTask().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getActivity(), BrowseMyDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (refreshFlag) {
refreshFlag = false;
new MyAdTask().execute();
}
}
class MyAdTask extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(getActivity(), "Loading.....");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.MYADS_URL, advertId), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
catAddList.clear();
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter = new CateAdDisplayAdapter(getActivity(), catAddList);
adapter.notifyDataSetChanged();
lsv.setAdapter(adapter);
cd.dismissdialog();
}
}
}

I can't understand you ... You have an Button and want when you click on it to close the activity or what ? If it's that, then write this code :
Button yourButton = (Button) view.findViewById(R.id.your_button_id);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});

Related

How to send value from one fragment to another fragment from Recyclerview Adapter. Then close the first fragment and open the new Fragment

I need to send a value when i click on a row in recyclerview to another fragment (I thin on OnBind in the adapter). Then i need to close the fragment that contain the recyclerview and open the receiver fragment. I read somewhere that we can use bundle, but I am pretty new to android programming so I am confused.
This is the Fragment that contain RecyclerView
public class PasienFragment 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";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnPasienFragmentInteractionListener mPasienListener;
public PasienFragment() {
// Required empty public constructor
}
int countICU=0;
int countINAP=0;
int countUMUM=0;
int countBPJS=0;
RequestQueue queue;
String jenisAsuransi,jenisKamar;
String id="C0E0607E";
ImageView ivTotal,ivIcu,ivInap,ivBpjs,ivUmum;
TextView tvTOTAL,tvICU,tvINAP,tvBPJS,tvUMUM;
public static final String URL_JUMLAH = "http:";
public static PasienFragment newInstance(String param1, String param2) {
PasienFragment fragment = new PasienFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
queue = Volley.newRequestQueue(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_pasien, container, false);
ivTotal = (ImageView) view.findViewById(R.id.ivTotal);
ivIcu = (ImageView) view.findViewById(R.id.ivICU);
ivBpjs = (ImageView) view.findViewById(R.id.ivBPJS);
ivInap = (ImageView) view.findViewById(R.id.ivINAP);
ivUmum = (ImageView) view.findViewById(R.id.ivUMUM);
tvTOTAL = (TextView) view.findViewById(R.id.tvTotal);
tvICU = (TextView) view.findViewById(R.id.tvICU);
tvBPJS = (TextView) view.findViewById(R.id.tvBPJS);
tvINAP = (TextView) view.findViewById(R.id.tvINAP);
tvUMUM = (TextView) view.findViewById(R.id.tvUMUM);
ivTotal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien");
}
});
ivIcu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien ICU");
}
});
ivBpjs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien BPJS");
}
});
ivInap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien INAP");
}
});
ivUmum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien UMUM");
}
});
String url1 = URL_JUMLAH+id;
JsonObjectRequest req = new JsonObjectRequest(url1, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < users.length(); i++) {
try {
JSONObject obj = users.getJSONObject(i);
jenisAsuransi = (String) obj.get("Jenis_Asuransi");
jenisKamar = (String) obj.get("Jenis_Kamar");
if(jenisAsuransi.equals("BPJS")){
countBPJS++;
}
if(jenisAsuransi.equals("UMUM")){
countUMUM++;
}
if(jenisKamar.equals("INAP")){
countINAP++;
}
if(jenisKamar.equals("ICU")){
countICU++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
tvTOTAL.setText(String.valueOf(users.length()));
tvBPJS.setText(String.valueOf(countBPJS));
tvUMUM.setText(String.valueOf(countUMUM));
tvINAP.setText(String.valueOf(countINAP));
tvICU.setText(String.valueOf(countICU));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String sentence) {
if (mPasienListener != null) {
mPasienListener.onPasienFragmentInteraction(sentence);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPasienFragmentInteractionListener) {
mPasienListener = (OnPasienFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mPasienListener = null;
}
public interface OnPasienFragmentInteractionListener {
// TODO: Update argument type and name
void onPasienFragmentInteraction(String sentence);
}
}
This is the RecyclerView adapter
public class ListPasienAdapter extends RecyclerView.Adapter<ListPasienAdapter.PasienViewHolder> {
private List<Pasien> pasienList;
public int count = 0;
public ListPasienAdapter(List<Pasien> pasienList) {
this.pasienList = pasienList;
}
#Override
public void onBindViewHolder(final PasienViewHolder pasienViewHolder, int i) {
final Pasien pi = pasienList.get(i);
pasienViewHolder.tvTanggal.setText(pi.Tgl_Masuk);
pasienViewHolder.tvNama.setText(pi.Nama_Pasien + "/" + pi.Gender);
pasienViewHolder.tvKamar.setText(pi.No_Kamar);
if (pi.Perawatan.toString().equals("Merah")) {
pasienViewHolder.ivRambu.setImageResource(R.drawable.merah);
} else if (pi.Perawatan.toString().equals("Kuning")) {
pasienViewHolder.ivRambu.setImageResource(R.drawable.kuning);
} else if (pi.Perawatan.toString().equals("Hijau")) {
pasienViewHolder.ivRambu.setImageResource(R.drawable.hijau);
}
pasienViewHolder.ivRambu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public ListPasienAdapter.PasienViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_pasien, viewGroup, false);
return new ListPasienAdapter.PasienViewHolder(itemView);
}
#Override
public int getItemCount() {
return pasienList.size();
}
public static class PasienViewHolder extends RecyclerView.ViewHolder {
protected TextView tvTanggal;
protected TextView tvNama;
protected TextView tvKamar;
protected TextView tvGender;
protected ImageView ivRambu;
protected ImageView ivDown;
protected ImageView btnIngat;
protected ImageView btnTerkirim;
protected TextView tvPeringatan;
protected LinearLayout btnDetail;
public PasienViewHolder(View v) {
super(v);
tvTanggal = (TextView) v.findViewById(R.id.tvTanggal);
tvNama = (TextView) v.findViewById(R.id.tvNama);
tvKamar = (TextView) v.findViewById(R.id.tvKamar);
ivRambu = (ImageView) v.findViewById(R.id.ivRambu);
ivDown = (ImageView) v.findViewById(R.id.ivDown);
//btnIngat = (ImageView) v.findViewById(R.id.btnIngat);
//btnTerkirim = (ImageView) v.findViewById(R.id.btnTerkirim);
btnDetail = (LinearLayout) v.findViewById(R.id.btnDetail);
//tvPeringatan = (TextView) v.findViewById(R.id.tvPeringatan);
}
}
}
This is the receiver Fragment
public class ListAktivitas extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public ListAktivitas() {
// Required empty publtic constructor
}
public static final String URL_LIST_Aktivitas = "http";
public static final String URL_Pasien = "http://";
String id="3";
RequestQueue queue;
List<Aktivitas> resultAktivitas = new ArrayList<>();
List<Pasien> resultPasien = new ArrayList<>();
Aktivitas a = new Aktivitas();
ListAktivitasAdapter laa;
RecyclerView cardListAktivitas;
Integer Urut;
String Nama_Prosedur;
String Id_Prosedur;
String Id_Aktivitas;
String Status;
String Nama_Pasien, No_Kamar, Gender;
Context context;
TextView tvNamaPasien,tvKamar;
public static ListAktivitas newInstance(String param1, String param2) {
ListAktivitas fragment = new ListAktivitas();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
queue = Volley.newRequestQueue(getActivity());
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list_aktivitas, container, false);
cardListAktivitas = (RecyclerView) view.findViewById(R.id.cardListAktivitas);
cardListAktivitas.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
cardListAktivitas.setLayoutManager(llm);
tvNamaPasien = (TextView) view.findViewById(R.id.tvNamaPasien);
tvKamar = (TextView) view.findViewById(R.id.tvKamar);
String url2 = URL_Pasien+id;
JsonObjectRequest req2 = new JsonObjectRequest(url2, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject obj = users.getJSONObject(0);
Nama_Pasien = (String) obj.get("Nama_Pasien");
No_Kamar = (String) obj.get("No_Kamar");
if(obj.get("Gender").toString().equals("Laki-laki")){
Gender = "L";
}else if (obj.get("Gender").toString().equals("Perempuan")){
Gender = "P";
}
resultPasien.add(new Pasien(Nama_Pasien, No_Kamar,Gender));
} catch (JSONException e) {
e.printStackTrace();
}
tvNamaPasien.setText(Nama_Pasien+"/"+Gender);
tvKamar.setText("kamar:"+No_Kamar);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req2);
String url1 = URL_LIST_Aktivitas+id;
Toast.makeText(getActivity(), url1, Toast.LENGTH_SHORT).show();
JsonObjectRequest req = new JsonObjectRequest(url1, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "yes", Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), String.valueOf(users.length()), Toast.LENGTH_SHORT).show();
for (int i = 0; i < users.length(); i++) {
try {
JSONObject obj = users.getJSONObject(i);
Urut = (Integer) obj.get("Urut");
Nama_Prosedur= (String) obj.get("Nama_Prosedur");
Id_Prosedur = (String) obj.get("Id_Prosedur");
Id_Aktivitas = String.valueOf(obj.getInt(Id_Aktivitas));
Status = (String) obj.get("Status");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(context,Nama_Prosedur, Toast.LENGTH_SHORT).show();
resultAktivitas.add(new Aktivitas(Urut, Nama_Prosedur, Id_Prosedur, Id_Aktivitas, Status));
laa = new ListAktivitasAdapter(resultAktivitas);
cardListAktivitas.setAdapter(laa);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
/*
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This is the activity that contain the 2 fragment
public class PasienActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,PasienFragment.OnPasienFragmentInteractionListener {
PasienFragment pasienFragment;
ListPasienFragment listPasienFragment;
ListAktivitas listAktivitasFragment;
RequestQueue queue;
String Nama_Dokter,Nama_RS;
public static final String URL_LIST = "http:";
String id="vvvv";
View navHeaderView;
TextView tvNavDokter, tvNavRS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pasien);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
queue = Volley.newRequestQueue(this);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
listPasienFragment = new ListPasienFragment();
listPasienFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.listPasienContainer, listPasienFragment).commit();
pasienFragment = new PasienFragment();
pasienFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.pasienFragmentContainer,pasienFragment).commit();
listAktivitasFragment = new ListAktivitas();
listAktivitasFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.listAktivitasContainer, listAktivitasFragment).commit();
View navHeaderView = navigationView.getHeaderView(0);
tvNavDokter = (TextView) navHeaderView.findViewById(R.id.tvNavDokter);
tvNavRS = (TextView) navHeaderView.findViewById(R.id.tvNavRS);
String url1 = URL_LIST+id;
JsonObjectRequest req = new JsonObjectRequest(url1, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject obj = users.getJSONObject(0);
Nama_Dokter = (String) obj.get("Nama_Dokter");
Nama_RS = (String) obj.get("Rumah_Sakit");
tvNavDokter.setText(Nama_Dokter);
tvNavRS.setText(Nama_RS);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pasien, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
/*
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onPasienFragmentInteraction(String sentence) {
if(listPasienFragment!=null)
listPasienFragment.updateSentence(sentence);
}
}
You can send data using bundle to fragment.
EG. `Bundle data = new Bundle();
data.putString("key", "value");
NewFragment newFragment = new NewFragment ();
newFragment.setArguments(eventDetailsData);`
Then load fragment.
To kill/remove current fragment execute below code
getActivity().onBackPressed();

How to pass data from activity to fragment class?

I created a new project tabbed view. I want three layout on my main screen 1st home 2nd category 3rd favorite. I have code of Home activity which is fragment activity the code is here
public class HomeFragment extends android.support.v4.app.Fragment {
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
and I have another activity which is video playlist. I want to show the playlist activity in my home fragment page but I am too confused and new to Android I don't have idea what to do.
The code of video playlist is here. How can I call this code in my homeFragment class? I tried too many ways but got too confused.
Code is here which I want to implement in my home section
public ProgressBar nextBar;
List<String> next_title;
List title;
List vid;
List<String> next_vid;
ArrayList<Videos> videos=new ArrayList<Videos>();
Videos video;
ArrayList<Videos> toclear=new ArrayList<Videos>();
List<Videos> fav = new ArrayList<Videos>();
InterstitialAd mInterstitialAd;
ListView listview;
Toolbar toolbar,favourite;
int menu_id;
LinearLayout layout, no_fav;
private HttpHandler parserVideo;
String nextPageToken;
String apiKey = "AIzaSyDD73ZAzcR6bXa1qOv8YZY3fFmNwfTPs48";
String url;
Main_activity_adapter search;
Main_activity_adapter adapter;
String url_home= "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=15&playlistId=PLQGGrzFoybiOks7f2BReNzNwkRw3cN6RB&key="+apiKey+"";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_sec);
nextBar = (ProgressBar) findViewById(R.id.nextProgress);
layout = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
url = url_home;
listview = (ListView) findViewById(R.id.listview);
no_fav = (LinearLayout)findViewById(R.id.no_favourit);
no_fav.setVisibility(View.GONE);
parserVideo = new HttpHandler();
getVideosPlaylist videosplaylist = new getVideosPlaylist();
videosplaylist.execute();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listview.setOnScrollListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
final String toolbar_name = toolbar.getTitle().toString();
MenuItemCompat.setOnActionExpandListener(myActionMenuItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
updateList();
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (!s.isEmpty()) {
setSearch();
search.getFilter().filter(s);
}
return false;
}
});
return true;
}// end of toolbar control
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void updateList(){
adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
JSONObject jp_obj;
JSONArray jar_array;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
String toolbar_check = toolbar.getTitle().toString();
switch(view.getId()){
case R.id.listview:
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if(toolbar_check!="Favourites") {
OnScrollList onscroll = new OnScrollList();
onscroll.execute();
}
}
}
}
class getVideosPlaylist extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
jp_obj = parserVideo.getJsonFromYoutube(url);
try {
if (jp_obj.has("nextPageToken")) {
nextPageToken = jp_obj.getString("nextPageToken");
}
jar_array = new JSONArray(jp_obj.getString("items"));
if(jp_obj != null) {
JSONObject c = jar_array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
title = new ArrayList<String>(jar_array.length());
vid = new ArrayList<>(jar_array.length());
for (int j = 0; j < jar_array.length(); j++) {
c = jar_array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\\['\\]", ""));
String link = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
video = new Videos(str, link);
videos.add(video);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPreExecute() {
layout.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
updateList();
layout.setVisibility(View.GONE);
cancel(true);
super.onPostExecute(s);
}
}
class OnScrollList extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
if (nextPageToken!=null){
String nextPage = "&pageToken="+nextPageToken+"";
JSONObject next = parserVideo.getJsonFromYoutube(url+nextPage);
try {
JSONArray array = new JSONArray(next.getString("items"));
if (next != null) {
JSONObject c = array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
next_title = new ArrayList<String>(array.length());
next_vid = new ArrayList<String>((array.length()));
for (int j = 0; j < array.length(); j++) {
c = array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\'", ""));
next_title.add(str);
String nextLink = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
next_vid.add(nextLink);
video = new Videos(str, nextLink);
toclear.add(video);
}
}
}if (next.has("nextPageToken")){
nextPageToken = next.getString("nextPageToken");
}else if(!next.has("nextPageToken")){
nextPageToken = null;}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPostExecute(String s) {
videos.addAll(toclear);
adapter.notifyDataSetChanged();
nextBar.setVisibility(View.GONE);
toclear.clear();
cancel(true);
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
nextBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
public void setSearch()
{
search = new Main_activity_adapter(Videos_activity.this, videos, true);
listview.setAdapter(search);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos)search.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
public void favouritList(){
Main_activity_adapter favourit_adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(favourit_adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
Define variable like public static String test=""; in Activity then in Fragment get it like String test1=ActivityName.test; now you have value of test into test1
First of all, you need to understand that Activity contains fragments, not vice versa. So one way to make your idea come true is to make your activity contain three fragments:
1)Home
2)Category
3)Favorite
To send data from activity to fragment usually use Bundle object.
Then create the instance of the fragment and put bundle there by setArguments(yourBundle) method.
It is the main idea, if you want details then read official documentation and use search on SOF.
use a Bundle:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("yourArg","yourType"); //this could be String, int, float,etc
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.yourContainer,fragment).commit();
and in your Fragment's onCreateView:
Bundle bundle = getArguments();

how can rerun Asynctask inside fragment from recyclerview

I have fragment with Asynctask class which needs to Re-Run the Asynctask from my Recyclerview adapter class.
Note : I want re run asynctask inside of viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() { in onBindViewHolder and when use this line.
new maghalat.GetContacts().execute(); //maghalt is name of fragment contain GetContacts asynctask function
Give me red line under this line without any suggestion
this is my adapter :
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<jsonContent> jcontent;
public DataAdapter(Context context, List<jsonContent> jcontent) {
this.context=context;
this.jcontent=jcontent;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view ;
if(i == R.layout.card_row) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
}else {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.button_card, viewGroup, false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder,int i) {
if(i == jcontent.size()) {
viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//try This
((maghalat )context).asyncRun();
}
});
viewHolder.buttonprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
});
viewHolder.go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.pages.setText(Integer.toString(jcontent.get(i-1).pages));
}
else {
viewHolder.title.setText(jcontent.get(i).title);
Picasso.with(context).load(jcontent.get(i).imgurl).resize(300, 400).into(viewHolder.imageView);
}
}
#Override
public int getItemCount() {
return jcontent.size()+1;
}
#Override
public int getItemViewType(int position) {
return (position == jcontent.size()) ? R.layout.button_card : R.layout.card_row;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,pages;
private ImageView imageView;
private Button buttonnext,buttonprev,go;
private CardView cardView;
private EditText editText;
public ViewHolder(final View view) {
super(view);
title = (TextView)view.findViewById(R.id.post_title);
imageView=(ImageView)view.findViewById(R.id.img);
buttonnext =(Button)view.findViewById(R.id.next);
buttonprev=(Button)view.findViewById(R.id.prev);
go=(Button)view.findViewById(R.id.go);
editText=(EditText)view.findViewById(R.id.et_go_page);
cardView=(CardView)view.findViewById(R.id.cvv);
pages=(TextView)view.findViewById(R.id.number_pages);
}
}
}
this is my fragment :
public class maghalat extends Fragment {
private RecyclerView recyclerView;
private DataAdapter adapter;
private View myFragmentView;
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private int numpage=0;
public int sag;
private String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(sag)+"/?json=get_posts";
List<jsonContent> listcontent=new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
if(isNetworkConnected()) {
asyncRun();
}else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
return myFragmentView;
}
public void asyncRun(){
new GetContacts().execute();
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
sag=numpage+1;
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(),listcontent);
recyclerView.setAdapter(adapter);
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<jsonContent> jcontent;
private maghalat fragment;
public DataAdapter(Context context, List<jsonContent> jcontent, maghalat frag) {
this.context=context;
this.jcontent=jcontent;
this.fragment = frag;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view ;
if(i == R.layout.card_row) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
}else {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.button_card, viewGroup, false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder,int i) {
if(i == jcontent.size()) {
viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//try This
(fragment).asyncRun();
}
});
viewHolder.buttonprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
});
viewHolder.go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.pages.setText(Integer.toString(jcontent.get(i-1).pages));
}
else {
viewHolder.title.setText(jcontent.get(i).title);
Picasso.with(context).load(jcontent.get(i).imgurl).resize(300, 400).into(viewHolder.imageView);
}
}
#Override
public int getItemCount() {
return jcontent.size()+1;
}
#Override
public int getItemViewType(int position) {
return (position == jcontent.size()) ? R.layout.button_card : R.layout.card_row;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,pages;
private ImageView imageView;
private Button buttonnext,buttonprev,go;
private CardView cardView;
private EditText editText;
public ViewHolder(final View view) {
super(view);
title = (TextView)view.findViewById(R.id.post_title);
imageView=(ImageView)view.findViewById(R.id.img);
buttonnext =(Button)view.findViewById(R.id.next);
buttonprev=(Button)view.findViewById(R.id.prev);
go=(Button)view.findViewById(R.id.go);
editText=(EditText)view.findViewById(R.id.et_go_page);
cardView=(CardView)view.findViewById(R.id.cvv);
pages=(TextView)view.findViewById(R.id.number_pages);
}
}
}
Your Fragment
public class maghalat extends Fragment {
private RecyclerView recyclerView;
private DataAdapter adapter;
private View myFragmentView;
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private int numpage=0;
public int sag;
private String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(sag)+"/?json=get_posts";
List<jsonContent> listcontent=new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
if(isNetworkConnected()) {
asyncRun();
}else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
return myFragmentView;
}
public void asyncRun(){
new GetContacts().execute();
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
sag=numpage+1;
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(),listcontent,maghalat.this);
recyclerView.setAdapter(adapter);
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}

android AsyncTask stays hanging running

Hi and thanks for your attention !,
can somebody help me?, my app stays with the progressdialog active and the asynctask stays hanging in running. I try to cancel the asynctask after execution it, but does not work.
public class MttoBitacoraFragment extends Fragment {
ListView lv;
AutoCompleteTextView actEmpleado,actEstatus, actDepto;
List<Autcompletecls> listEmpelado= new ArrayList<Autcompletecls>();
List<Autcompletecls> listEstatus= new ArrayList<Autcompletecls>();
List<Autcompletecls> listDepto= new ArrayList<Autcompletecls>();
AutocompleteAdapter adpEmpleado, adpEstatus, adpDepto;
ProgressDialog dialog;
WS webservice;
public MttoBitacoraFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_mtto_bitacora, container, false);
String[][] para = new String[0][0];
actEmpleado = (AutoCompleteTextView)view.findViewById(R.id.actMttoProblemaEmpleado);
actEstatus =(AutoCompleteTextView)view.findViewById(R.id.actMttoProblemaEstatus);
actDepto=(AutoCompleteTextView)view.findViewById(R.id.actMttoProblemaDepto);
ansyWS call = new ansyWS("ConEmpleadoDLL", para);
call.execute();
call.cancel(true);
while(call.getStatus() == AsyncTask.Status.RUNNING)
{
call.cancel(true);
}
if(call.getStatus() != null || call.getStatus() == AsyncTask.Status.RUNNING) {
call.cancel(true);
ansyWS call2 = new ansyWS("ConEstatusDLL",para);
call2.execute();
call2.cancel(true);
}
else {
ansyWS call2 = new ansyWS("ConEstatusDLL",para);
call2.execute();
call2.cancel(true);
}
actEmpleado.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Autcompletecls item = listEmpelado.get(position);
Toast.makeText(getContext(), item.getId(), Toast.LENGTH_SHORT).show();
}
});
actEstatus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Autcompletecls item = listEstatus.get(position);
Toast.makeText(getContext(), item.getId(), Toast.LENGTH_SHORT).show();
}
});
return view;
}
class ansyWS extends AsyncTask<String,String,String>{
private volatile boolean running = true;
String[][] parametros;
String methodname;
SoapObject resultado;
public ansyWS(String _methodname, String[][] _parametros)
{
methodname = _methodname;
parametros = _parametros;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage(getResources().getString(R.string.dialog_message_save));
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
webservice = new WS();
resultado = webservice. LlamaWS(methodname,parametros);
dialog.dismiss();
if (resultado != null) {
for (int i = 0; i < resultado.getPropertyCount(); i++) {
SoapObject datos = (SoapObject) resultado.getProperty(i);
switch (methodname) {
case "ConEmpleadoDLL":
listEmpelado.add(new Autcompletecls(datos.getProperty(0).toString(), datos.getProperty(1).toString()));
break;
case "ConEstatusDLL":
listEstatus.add(new Autcompletecls(datos.getProperty(0).toString(), datos.getProperty(1).toString()));
break;
}
}
return methodname;
} else {
return "error";
}
}
#Override
protected void onPostExecute(String s) {
while(running) {
switch (s) {
case "ConEmpleadoDLL":
actEmpleado.setThreshold(0);
adpEmpleado = new AutocompleteAdapter(getContext(), R.layout.activity_main, R.id.tv_autocomplete_text, listEmpelado);
actEmpleado.setAdapter(adpEmpleado);
break;
case "ConEstatusDLL":
actEstatus.setThreshold(0);
adpEstatus = new AutocompleteAdapter(getContext(), R.layout.activity_main, R.id.tv_autocomplete_text, listEstatus);
actEstatus.setAdapter(adpEstatus);
break;
}
}
cancel(true);
dialog.dismiss();
}
#Override
protected void onCancelled() {
running = false;
super.onCancelled();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("SomeTag", System.currentTimeMillis() / 100L + " onDestory()");
}
}

Update ListView Record Duplicated Android

I put a limit of 15 records to be displayed in my listview. The 15 records successfully displayed but when i clicked on load more button, it add the previous 15 records and the new records too. Here is my async task where more records is being added. I use articlesAdapter.notifyDataSetChanged(); set too but the issue remains. i believe it has something to do with articlesFiltered.size()/15)+1.
public class ActusScreen extends BaseActivity implements OnClickListener {
private DisplayImageOptions options;
ImageLoader imageLoader;
String link;
//...
final int NONE=0;
final int THEME=1;
final int SEARCH=2;
final int THEME_TO_SEARCH=3;
final int SEARCH_RESULTS=4;
final int THEME_TO_SEARCH_RESULTS=5;
int MODE=NONE;
public ArrayList<Article> articles;
public ArrayList<Article> articlesFiltered;
public ArrayList<Theme> themes;
public ArrayList<Theme> themeFiltered;
public static int titleIndex=0;
static boolean original_view = false;
RelativeLayout adLayout;
ListView themesList;
RelativeLayout searchLayout;
EditText searchField;
Button back, theme;
StringBuilder builder;
ScrollView scrollme;
ThemesAdapter themeAdapter;
ArticlesAdapter articlesAdapter;
TextView header_text;
ActusScreen context;
ProgressDialog pd;
ImageView image_actus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actus);
context=this;
back=(Button)findViewById(R.id.envoye);
back.setOnClickListener(this);
back.setVisibility(View.GONE);
theme=(Button)findViewById(R.id.theme);
theme.setOnClickListener(this);
Button search=(Button)findViewById(R.id.search);
search.setOnClickListener(this);
header_text = (TextView)findViewById(R.id.text_titre);
header_text.setText(getResources().getText(R.string.actus).toString());
adLayout=(RelativeLayout)findViewById(R.id.adLayout);
themeAdapter=new ThemesAdapter(this);
themesList=(ListView)findViewById(R.id.themesList);
themesList.setAdapter(themeAdapter);
themesList.setVisibility(View.GONE);
SelectedArticle.mtypo=1;
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
searchLayout=(RelativeLayout)findViewById(R.id.searchLayout);
searchLayout.setVisibility(View.GONE);
searchField=(EditText)findViewById(R.id.keyword);
Button valid=(Button)findViewById(R.id.valid);
valid.setOnClickListener(this);
new GetAllArticlesTask().execute();
image_actus = (ImageView)findViewById(R.id.image);
image_actus.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = link;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
options = new DisplayImageOptions.Builder()
// .showStubImage(R.drawable.ic_launcher)
.displayer(new RoundedBitmapDisplayer(3))
.cacheInMemory()
.cacheOnDisc()
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
new backTask().execute("");
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//FavoriteScreen.flagx=1;
super.onStart();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.envoye:
back();
break;
case R.id.theme:
if(themesList.getVisibility()==View.VISIBLE)
themesList.setVisibility(View.GONE);
else
themesList.setVisibility(View.VISIBLE);
break;
case R.id.search:
search();
break;
case R.id.valid:
searchLayout.setVisibility(View.GONE);
if(MODE==SEARCH)
MODE=SEARCH_RESULTS;
else
MODE=THEME_TO_SEARCH_RESULTS;
filterArticles();
break;
}
}
public void search(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case NONE:
searchLayout.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
theme.setVisibility(View.GONE);
MODE=SEARCH;
break;
}
}
public void back(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
/*
*
Intent intent = getIntent();
finish();
startActivity(intent);
*/
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
//ActusScreen.titleIndex=0;
ArticlesAdapter.mode = true;
titleIndex=0;
new GetAllArticlesTask().execute();
header_text.setText(getResources().getText(R.string.actus).toString());
MODE=NONE;
break;
case SEARCH:
searchLayout.setVisibility(View.GONE);
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
MODE=NONE;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
case THEME_TO_SEARCH:
searchLayout.setVisibility(View.GONE);
MODE=THEME;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
}
}
private void copyArticles() {
if(articles!=null){
if(articlesFiltered==null)
articlesFiltered=new ArrayList<Article>();
else
articlesFiltered.clear();
for(Article a: articles)
articlesFiltered.add(a);
}
}
public void filterArticles(){
String key=searchField.getText().toString().toLowerCase();
if(key.length()>0){
if(articlesFiltered!=null){
articlesFiltered.clear();
System.gc();
}
for(Article a: articles){
if(a.name.toLowerCase().contains(key))
articlesFiltered.add(a);
}
articlesAdapter.notifyDataSetChanged();
}
}
private class GetAllArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
if(Globals.themes==null)
Globals.themes=HTTPFunctions.getThemesList();
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getAllArticles();
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
themeAdapter.notifyDataSetChanged();
}
}
private class GetThemeArticlesTask extends AsyncTask<String, Void, Void> {
#Override
public Void doInBackground(String... params) {
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getThemeArticles(params[0]);
//begin 06/03; articles.theme_id not set by HTTPFunctions when a specific theme is selected; need to set it explicitly
for (Article a : articles)
a.theme_id=params[0];
//end
System.out.println("theme article: "+ HTTPFunctions.getThemeArticles(params[0]));
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
private class GetMoreArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
if(moreArticles!=null){
articles.addAll(articles);
copyArticles();
}
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
public void articleSelected(int id){
Globals.copyArticles(articlesFiltered);
Intent i=new Intent(context, SelectedArticle.class);
i.putExtra("id", id);
//begin
//i.putExtra("title", ArticlesAdapter.selected);
if (titleIndex==0){
String title=Util.getTitleName(articlesFiltered.get(id).type, articlesFiltered.get(id).theme_id);
i.putExtra("title", title);
}
else{
String title=ArticlesAdapter.selected.toUpperCase();
i.putExtra("title", title);
}
//end
context.startActivity(i);
}
public void themeSelected(int id){
themesList.setVisibility(View.GONE);
MODE=THEME;
theme.setVisibility(View.GONE);
back.setVisibility(View.VISIBLE);
ArticlesAdapter.mode = false;
//begin 06/03
//ArticlesAdapter.selected=Globals.themes.get(id).name;
//header_text.setText(Globals.themes.get(id).name.toUpperCase());
Spanned name=Html.fromHtml(Globals.themes.get(id).name);
System.out.println("spanned name: "+ name);
ArticlesAdapter.selected=name.toString().toUpperCase();
header_text.setText(name.toString().toUpperCase());
//end
System.out.println("theme_name: "+ Globals.themes.get(id).name);
new GetThemeArticlesTask().execute(Globals.themes.get(id).id);
}
public void loadMore(){
new GetMoreArticlesTask().execute();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if (original_view==true){
new GetAllArticlesTask().execute();
theme.setVisibility(View.VISIBLE);
back.setVisibility(View.GONE);
header_text.setText(getResources().getText(R.string.actus).toString());
original_view=false;
}
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
SelectedReglementation.setview=true;
super.onPause();
}
class backTask extends AsyncTask<String, Void, ArrayList<Post>> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected ArrayList<Post> doInBackground(String... urls) {
ArrayList<Post> newpostarraylist=new ArrayList<Post>();
try{
URL url = new URL("");
BufferedReader reader = null;
builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
builder.append(line.trim());
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
System.out.println("Builder: "+ builder);
}catch(Exception ex){}
return newpostarraylist;
}
#Override
protected void onPostExecute(ArrayList<Post> result) {
String[] banner_image = builder.toString().split(";");
imageLoader.displayImage(banner_image[2], image_actus,options);
link = banner_image[1];
}
}
public int addOne(int i){
return i+1;
}
}
and My article adapter
public class ArticlesAdapter extends BaseAdapter {
ActusScreen main;
ImageLoader imageLoader;
String imageUrl="";
public static String selected="";
public static boolean mode=false;
int x=0;
//disable a.theme_id null pointer wh
public static int bine=0;
public ArticlesAdapter(ActusScreen m) {
main=m;
imageLoader=new ImageLoader(m);
}
public int getCount() {
if(main.articlesFiltered!=null)
return main.articlesFiltered.size();
return 0;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView==null) {
convertView=newView(position, parent);
holder = new ViewHolder();
holder.image=(ImageView)convertView.findViewById(R.id.image);
holder.remove=(ImageView)convertView.findViewById(R.id.remove);
holder.title=(TextView)convertView.findViewById(R.id.title);
holder.text_title=(TextView)convertView.findViewById(R.id.text_title);
holder.more=(RelativeLayout)convertView.findViewById(R.id.moreLayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Article a=main.articlesFiltered.get(position);
imageLoader.DisplayImage(String.format(imageUrl, a.image), holder.image);
String str = a.name;
int length = str.length();
String newStr = a.name;
if (length>65)
newStr = str.replaceAll("^(.{74})(.*)$","$1...");
holder.title.setText(Html.fromHtml(newStr));
holder.text_title.setText(selected.toUpperCase());
holder.remove.setVisibility(View.GONE);
if (holder.text_title.equals(null))
holder.text_title.setText("t");
if(position==main.articlesFiltered.size()-1 && main.articlesFiltered.size()<=45 && main.articlesFiltered.size()%15==0)
holder.more.setVisibility(View.VISIBLE);
else
holder.more.setVisibility(View.GONE);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.articleSelected(position);
SelectedArticle.mtypo=1;
}
});
holder.more.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.loadMore();
}
});
if (ActusScreen.titleIndex==0){
...
}
}
return(convertView);
}
private View newView(int position, ViewGroup parent) {
return(main.getLayoutInflater().inflate(R.layout.articles_row, parent, false));
}
class ViewHolder {
ImageView image, remove;
TextView title;
TextView text_title;
RelativeLayout more;
}
}
UPDATE
and the HttpFunction getMoreArticles()
public static ArrayList<Article> getMoreArticles(int page){
String url=LAST_ARTICLE_URL;
if(url.endsWith(".php"))
url+="?page="+page;
else
url+="&page="+page;
String response=getResponse(url);
if(!ERROR.equals(response)){
return JsonParsingFunctions.parseArticles(response);
}
return null;
}
What is happening is concatenation in the method call. articlesFiltered.size()/15 is giving 1, then the +1 is not ADDING 1, it is concatenating 1, i.e 1+1 = 11 NOT 2. You could create a method
public int addOne(int i){
return i+1;
}
and use
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
That should work providing the rest of the code is good
what variable is your adapter?
you notify your adapter but i don't see that you add datas to your articlesAdapter

Categories

Resources