android AsyncTask stays hanging running - android

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()");
}
}

Related

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;
}
}

Updating data in a recyclerview

In my project a read data from a CMS I created through a JSON response. My problem is when I click the refresh button the data are read twice!. Here is my fragment's code.
public class FootballNews extends Fragment {
public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "http://xxx//manucms/football_news_images/" ;
private List<FootballNewsObject> listItemsList;
private RecyclerView mRecyclerView;
private FootballNewsAdapter adapter;
public FootballNews() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View v = inflater.inflate(R.layout.fragment_football_news, container, false);
// Inflate the layout for this fragment
listItemsList = new ArrayList<FootballNewsObject>();
mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
//mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateList();
}
public void updateList() {
//declare the adapter and attach it to the recyclerview
adapter = new FootballNewsAdapter(getActivity(), listItemsList);
mRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Clear the adapter because new data is being added from a new subreddit
//adapter.clearAdapter();
//showPD();
// Request a string response from the provided URL.
JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FOOTBALL_NEWS, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
//hidePD();
// Parse json data.
// Declare the json objects that we need and then for loop through the children array.
// Do the json parse in a try catch block to catch the exceptions
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = response.getJSONObject(i);
FootballNewsObject item = new FootballNewsObject();
item.setTitle(post.getString("title"));
item.setImage(IMAGE_URL + post.getString("news_image"));
item.setArticle(post.getString("article"));
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Update list by notifying the adapter of changes
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//hidePD();
}
});
jsObjRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
queue.add(jsObjRequest);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.refresh){
if(isOnline()) {
updateList();
}else{
Toast.makeText(getActivity(),"There is no internet connection",Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Basically I am running the updateList method twice. Once in the onActivityCreated(...) method,and secondly inside the onOptionsItemSelected(...).
Finally here is my adapter.
public class FootballNewsAdapter extends RecyclerView.Adapter<FootballNewsRowHolder>{
private List<FootballNewsObject> footballNewsObjectList;
private Context mContext;
private ImageLoader mImageLoader;
private int focused = 0;
public FootballNewsAdapter(Activity activity, List<FootballNewsObject> footballNewsObjectList){
this.footballNewsObjectList = footballNewsObjectList;
this.mContext = activity;
}
#Override
public FootballNewsRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.football_news_row,null);
final FootballNewsRowHolder holder = new FootballNewsRowHolder(v);
return holder;
}
#Override
public void onBindViewHolder(FootballNewsRowHolder holder, int position) {
final FootballNewsObject listItems = footballNewsObjectList.get(position);
holder.itemView.setSelected(focused==position);
holder.getLayoutPosition();
mImageLoader = AppController.getInstance().getImageLoader();
holder.thumbnail.setImageUrl(listItems.getImage(),mImageLoader);
holder.thumbnail.setDefaultImageResId(R.drawable.reddit_placeholder);
holder.name.setText(Html.fromHtml(listItems.getTitle()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = listItems.getTitle();
String article = listItems.getArticle();
String image = listItems.getImage();
Intent i = new Intent(mContext, Extras.class);
i.putExtra("title",title);
i.putExtra("article",article);
i.putExtra("image",image);
mContext.startActivity(i);
//Toast.makeText(mContext,"You clicked",Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(mContext,WebActivity.class);
//intent.putExtra("url",postUrl);
// mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null != footballNewsObjectList?footballNewsObjectList.size() :0 );
}
}
Any ideas?
Thanks
You are adding to your list in your refresh method, instead of updating. Add
listItemsList.clear();
at the beginning of your refresh function (updateList).

PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type

am building an open source project, here is its link
http://slidese.github.io/slidese/2013/11/25/update_listview_item.html
I've imported all library projects which it is using into eclipse. All are fine except PullToRefresh library. it is giving me the error "PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type" where fragment implements it
2nd error is at
mPullToRefreshAttacher.addRefreshableView(mListview, this);
it says "The method addRefreshableView(View, ViewDelegate) in the type PullToRefreshAttacher is not applicable for the arguments (ListView, ContentFragment)"
3rd error is at
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
It is asking me to remove override annotation. here is complete code of fragment.
public class ContentFragment extends Fragment implements PullToRefreshAttacher.OnRefreshListener {
private final String TAG = "ContentFragment";
public static final String CONTENT_MODE = "content_mode";
public static final int MODE_ADFREE = 0;
public static final int MODE_PREMIUM = 1;
private StartActivity mListener;
private PullToRefreshAttacher mPullToRefreshAttacher;
private UpdaterAsyncTask mUpdater;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
ListView mListview;
Button mPlayButton;
ContentAdapter mAdapter;
int mMode;
Map<String, UpdateHolder> mUpdates = new HashMap<String, UpdateHolder>();
public ContentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (StartActivity) activity;
Log.d(TAG, "Attached podcast list fragment");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must be the StartActivity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, null);
mListview = (ListView) view.findViewById(android.R.id.list);
mListview.setEmptyView(view.findViewById(R.id.empty_list_view));
mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_menu_content, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
SparseBooleanArray checked = mListview.getCheckedItemPositions();
Content[] params = new Content[checked.size()];
int index = 0;
int first = mListview.getFirstVisiblePosition();
int last = mListview.getLastVisiblePosition();
for (int i = 0; i < mListview.getCount(); i++) {
if (checked.get(i)) {
params[index++] = (Content)mListview.getItemAtPosition(i);
if (i >= first && i <= last) {
View view = mListview.getChildAt(i-first);
Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right);
animation.setDuration(200);
//animation.setFillAfter(true);
animation.setStartOffset(100 * (index) );
view.startAnimation(animation);
}
}
}
new AsyncTask<Content, Void, Void>() {
#Override
protected Void doInBackground(Content... params) {
for (Content content : params) {
File file = Utils.getFilepath(content.getFilename());
file.delete();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
mode.finish();
return true;
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
});
mListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Content content = mAdapter.getItem(position);
mListener.showContentDetails(content);
}
});
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
mPullToRefreshAttacher = ((StartActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mListview, this);
mMode = getArguments().getInt(CONTENT_MODE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
if (mUpdater != null)
mUpdater.stop();
}
#Override
public void onResume() {
super.onResume();
updateAdapter();
mUpdater = new UpdaterAsyncTask();
mUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
public void refresh() {
updateAdapter();
}
public void replaceCurrentlyPlayingContent() {
GlobalContext.INSTANCE.replaceCurrentlyPLayingContent(mAdapter.getObjects(), mListener.getCurrentTrack());
}
private void updateAdapter() {
Log.d(TAG, "updateAdapter");
//new FetchContentAsyncTask(mMode).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final String mp3 = mListener.getSavedStateMp3();
final boolean isPlaying = mListener.getSavedStateIsPlaying();
final boolean isPaused = mListener.getSavedStateIsPaused();
List<Content> listOfContent = GlobalContext.INSTANCE.getCachedContent(mMode, mp3, isPlaying, isPaused);
mAdapter = new ContentAdapter(getActivity(), R.layout.list_item_card, listOfContent);
mListview.setAdapter(mAdapter);
}
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
boolean isRunning = true;
public void stop() {
isRunning = false;
}
#Override
protected Void doInBackground(Void... params) {
while (isRunning) {
/*
Map<String, UpdateHolder> map = gatherMetadata();
publishProgress(map);
*/
updateCurrentAdapterContent();
publishProgress();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... params) {
super.onProgressUpdate();
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row
int start = mListview.getFirstVisiblePosition();
for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
View view = mListview.getChildAt(i-start);
if (((Content)mListview.getItemAtPosition(i)).dirty) {
Log.v(TAG, "Content is dirty");
mListview.getAdapter().getView(i, view, mListview);
}
}
}
}
}
private void updateCurrentAdapterContent() {
List<Content> listOfContent = mAdapter.getObjects();
Map<String, UpdateHolder> map = new HashMap<String, UpdateHolder>();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
try {
Cursor cursor = ContentDownloadManager.INSTANCE.query(q);
while (cursor.moveToNext()) {
//long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
int downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
float progress = (float)downloaded/(float)total;
UpdateHolder holder = new UpdateHolder();
holder.progress = progress;
holder.status = status;
map.put(uri, holder);
}
cursor.close();
final Content currentContent = mListener.getCurrentTrack();
final boolean isPlaying = mListener.isPlaying();
final boolean isPaused = mListener.isPaused();
for (Content content : listOfContent) {
// First update any download progress we might have for this specific content item
UpdateHolder holder = map.get(content.mp3);
if (holder != null) {
if (content.downloadProgress != holder.progress) {
content.downloadProgress = holder.progress;
content.dirty = true;
}
if (content.downloadStatus != holder.status) {
content.downloadStatus = holder.status;
content.dirty = true;
}
}
else {
if (content.downloadProgress != 0f) {
content.downloadProgress = 0f;
content.dirty = true;
}
if (content.downloadStatus != -1) {
content.downloadStatus = -1;
content.dirty = true;
}
}
// Update with elapsed (to be done)
// File exists?
File file = Utils.getFilepath(content.getFilename());
if (content.exists != file.exists()) {
content.exists = file.exists();
content.dirty = true;
}
// Is this the currently playing content
if (currentContent != null && content.mp3.equals(currentContent.mp3)) {
if (content.isPlaying != isPlaying) {
content.isPlaying = isPlaying;
content.dirty = true;
}
if (content.isPaused != isPaused) {
content.isPaused = isPaused;
content.dirty = true;
}
}
else {
if (content.isPlaying != false) {
content.isPlaying = false;
content.dirty = true;
}
if (content.isPaused != false) {
content.isPaused = false;
content.dirty = true;
}
}
if (content.dirty) {
DatabaseManager.getInstance().createOrUpdateContent(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class UpdateHolder {
public String mp3;
public int status;
public boolean played;
public float progress;
public boolean exists = false;
public boolean isPlaying = false;
public boolean isPaused = false;
//public int elapsed;
//public int duration;
}
}
I couldn't find the issue in it. I'm stuck here for last 40 hours. Please help. Thank you!
Maybe you are using old version of the library. I found that PullToRefreshAttacher doesn't contain OnRefreshListener. (https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/library/src/main/java/uk/co/senab/actionbarpulltorefresh/library/PullToRefreshAttacher.java)
Try to import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; and use it instead of PullToRefreshAttacher.OnRefreshListener.

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