How to pass data from activity to fragment class? - android

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

Related

How to sort recyclerView, Bold item if unread and unbold if item opened?

I have 2 Activities in my application.
activityMain contain 3 Fragments
The third fragment is a conversations list. This is a recylerView where each Item leads to a specific chat.
activityConversation contains a Chat.
First, i would like to sort the conversations in the the recyclerView in order of "Last actives". The most recent active should be displayed on top of the list, the second last active on second postition etc...
Secondly, each Item of the recyclerView contains a Textview. For each item, I would like to display the last message posted in the related chat in this Texview.
Finally, i would like to display these Item textViews in Bold since the conversation has not been opened until the last chat update.
Has anyone an Idea to help me achieve that?
Here my Chat Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
getWindow().setBackgroundDrawableResource(R.drawable._background_black_lchatxxxhdpi) ;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LinearLayout leftNav = (LinearLayout)findViewById(R.id.conv_left_nav);
LinearLayout helperAdmin = (LinearLayout) getLayoutInflater().inflate(R.layout.list_participant_admin, leftNav, false);
leftNav.addView(helperAdmin);
final EditText input_post = (EditText)findViewById(R.id.input_post);
context = this;
input_post.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageButton btn_submit = (ImageButton)findViewById(R.id.btn_submit);
btn_submit.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Intent intent = getIntent();
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
rpcHelper = new RPCHelper(context, this);
String unique_device_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Log.i("US", unique_device_id);
rpcHelper.loginOrRegister(unique_device_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
dbHelper = new DataBaseHelper(context, "us", null, Statics.DB_VERSION);
userInConv = dbHelper.dbReader.getUserInConversation(Integer.parseInt(conversationId));
storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
leftRecycler = (RecyclerView) helperAdmin.findViewById(R.id.conv_left_recycler);
//mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
leftLayoutManager = new LinearLayoutManager(this);
leftRecycler.setLayoutManager(leftLayoutManager);
leftAdapter = new ConvLeftAdapter(userInConv, storageDir, Integer.parseInt(conversationId));
leftRecycler.setAdapter(leftAdapter);
helpersImg = new View[3];
helpers = new DataBaseReader.User[3];
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(this, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
IntentFilter filter = new IntentFilter(Statics.ACTION_NEW_POST);
this.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.d("new", " message");
refreshConversation();
}
}, filter);
}
#Override
public void onNewIntent(Intent intent){
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversation, menu);
DataBaseReader.Conversation conversation = dbHelper.dbReader.getConversation(conversationId);
DataBaseReader.User owner = dbHelper.dbReader.getConversationOwner(conversationId);
final ImageView owner_img = (ImageView)findViewById(R.id.img_userprofilpic);
TextView owner_name = (TextView)findViewById(R.id.lbl_username_owner);
TextView owner_city = (TextView)findViewById(R.id.lbl_usercity_owner);
TextView conversation_question = (TextView)findViewById(R.id.question_text);
owner_name.setText(owner.name);
owner_city.setText(owner.city);
conversation_question.setText(conversation.question.text);
conversation_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView text = (TextView)findViewById(R.id.question_text);
int maxLines = TextViewCompat.getMaxLines(text);
if (maxLines==2){
text.setMaxLines(Integer.MAX_VALUE);
}
else{
text.setMaxLines(2);
}
}
});
rpcHelper.getPhoto(storageDir + "/", owner.photo, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
owner_img.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void refreshConversation(){
dbHelper.dbSyncer.syncPosts(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
DataBaseReader.Post[] posts = dbHelper.dbReader.getPosts(conversationId);
postsRecycler = (RecyclerView) findViewById(R.id.posts_recycler);
postsLayoutManager = new LinearLayoutManager(context);
postsRecycler.setLayoutManager(postsLayoutManager);
postsAdapter = new PostsAdapter(posts, storageDir, rpcHelper);
postsRecycler.setAdapter(postsAdapter);
postsRecycler.scrollToPosition(postsAdapter.getItemCount() - 1);
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
/*
rpcHelper.getPosts(conversationId, new AsyncResponseListener(){
#Override
public void onResponse(JSONArray response) throws JSONException {
LinearLayout posts_root = (LinearLayout) findViewById(R.id.posts_root);
posts_root.removeAllViews();
for (int i = 0; i < response.length(); i++){
Log.d("Conv refresh", response.get(i) + "");
final JSONObject jConversation = (JSONObject) response.get(i);
LinearLayout post;
if (jConversation.getString("userId") == rpcHelper.user_id) {
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_sent, posts_root, false);
}
else{
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_received, posts_root, false);
((TextView)post.findViewById(R.id.post_name_)).setText(jConversation.getString("name"));
}
((TextView)post.findViewById(R.id.lbl_message_chat)).setText(jConversation.getString("text"));
posts_root.addView(post);
}
hideProcessDialog();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});*/
}
public void onSubmit(View v){
final EditText input_post = (EditText)findViewById(R.id.input_post);
String post_text = input_post.getText().toString();
rpcHelper.post(conversationId, post_text, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
input_post.setText("");
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
Button no = (Button)alertDialog.findViewById(R.id.btn_cancel);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpersImg[0] = null;
helpersImg[1] = null;
helpersImg[2] = null;
helpers[0] = null;
helpers[1] = null;
helpers[2] = null;
alertDialog.dismiss();
}
});
}
public void onSelectUser(View v){
View vi = snapHelper.findSnapView(participantsLayoutManager);
if (helpersImg[0] == vi || helpersImg[1] == vi || helpersImg[2] == vi)
return;
Log.i("get helper Id", ""+ participantsAdapter.selectedUserId);
ImageView photo = (ImageView) vi.findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
Bitmap bmap = photo.getDrawingCache();
ImageView helperImage = null;
if (helpersImg[0] == null) {
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper0);
helpersImg[0] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[0] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[1] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper1);
helpersImg[1] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[2] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper2);
helpersImg[2] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else{
return;
}
}
/**private void showTipDialog(){
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
final View dialogView = inflater.inflate(R.layout.dialog_add_tip, null);
final EditText value = (EditText) dialogView.findViewById(R.id.tip_value);
final SeekBar sb = (SeekBar) dialogView.findViewById(R.id.seekBar);
sb.setMax(50);
sb.setProgress(5);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
progress = (Math.round(progress/5 ))*5;
seekBar.setProgress(progress);
value.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Convert text to integer. Do you already use editText.setInputType(InputType.TYPE_CLASS_NUMBER), don't you?
Integer enteredProgress = Integer.valueOf(s.toString());
sb.setProgress(enteredProgress);
}
#Override
public void afterTextChanged(Editable s) {}});
dialogBuilder.setView(dialogView);
alertDialog = dialogBuilder.create();
alertDialog.show();
Button ok = (Button)alertDialog.findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
Button no = (Button)alertDialog.findViewById(R.id.btn_no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}*/
public void removeHelper(View v){
int index = 0;
if (v == alertDialog.findViewById(R.id.reward_dialog_helper0)){
index = 0;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper1)){
index = 1;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper2)){
index = 2;
}
if (helpersImg[index] == null){
return;
}
ImageView photo = (ImageView) helpersImg[index].findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
photo.clearColorFilter();
helpersImg[index] = null;
helpers[index] = null;
ImageView imv = (ImageView)v;
imv.setImageResource(R.drawable.stroke_rounded_corners_white);
}
private void showProcessDialog(){
pd = new ProgressDialog(this);
pd.setTitle("Processing");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
private void hideProcessDialog(){
pd.hide();
}
#Override
public void onInternetConnectionLost() {
}
#Override
public void onInternetConnectionFound() {
}
public void onTakePicture(View v){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, Statics.REQUEST_IMAGE_CAPTURE);
}
}
public void onTakePictureFromGallery(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), Statics.REQUEST_PROFILE_IMAGE_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap imageBitmap;
if ((requestCode == Statics.REQUEST_IMAGE_CAPTURE || requestCode == Statics.REQUEST_IMAGE_CAPTURE_0
|| requestCode == Statics.REQUEST_IMAGE_CAPTURE_1 || requestCode == Statics.REQUEST_IMAGE_CAPTURE_2) && resultCode == RESULT_OK && data != null) {
Bundle extras = data.getExtras();
if (extras == null){
return;
}
imageBitmap = (Bitmap) extras.get("data");
addPhoto(imageBitmap);
}
else if (requestCode == Statics.REQUEST_PROFILE_IMAGE_GALLERY && resultCode == RESULT_OK){
try {
imageBitmap = getBitmapFromUri(data.getData());
addPhoto(imageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addPhoto(Bitmap image) {
DataBaseReader.Conversation c = dbHelper.dbReader.getConversation(conversationId);
String encodedImage = encodeBitmap(image);
rpcHelper.addPhotosToQuestion("" + c.question.id, encodedImage, null, null, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
dbHelper.dbSyncer.sync(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse() {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
private String encodeBitmap(Bitmap bitmap){
try{
bitmap = Bitmap.createScaledBitmap(bitmap, Statics.BITMAP_WIDTH, Statics.BITMAP_HEIGHT, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
final byte[] imageInByte = stream.toByteArray();
return Base64.encodeToString(imageInByte, Base64.DEFAULT);
}
catch(Exception e){
return "";
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
This is my Fragment with conversations List:
public class ConversationFragment extends Fragment {
private View v;
private OnFragmentInteractionListener mListener;
public ConversationFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment ConversationFragment.
*/
// TODO: Rename and change types and number of parameters
public static ConversationFragment newInstance() {
ConversationFragment fragment = new ConversationFragment();
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) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (v == null) {
v = inflater.inflate(R.layout.fragment_conversation, container, false);
}
final SwipeRefreshLayout swipeRefresh = (SwipeRefreshLayout)v.findViewById(R.id.swiperefreshconv);
swipeRefresh.post(new Runnable() {
#Override
public void run() {
swipeRefresh.setRefreshing(true);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mListener.syncDb();
}
});
return v;
}
#Override
public void onStart(){
super.onStart();
mListener.refreshConversations();
}
#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;
}
}
This is my Conversation Adapter:
public class ConversationsAdapter extends RecyclerView.Adapter {
private final File mStorageDir;
private final RPCHelper mRPCHelper;
private DataBaseReader.Conversation[] mDataset;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public ConversationsAdapter(DataBaseReader.Conversation[] myDataset, File storageDir) {
mDataset = myDataset;
mStorageDir = storageDir;
mRPCHelper = new RPCHelper();
}
// Create new views (invoked by the layout manager)
#Override
public ConversationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_conversations, parent, false);
ViewHolder vh = new ViewHolder(v);
context = parent.getContext();
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Log.d("recy", "bind called");
TextView username = (TextView)holder.mView.findViewById(R.id.lbl_username);
final TextView message = (TextView)holder.mView.findViewById(R.id.question_text);
TextView date_and_time = (TextView)holder.mView.findViewById(R.id.lbl_date_and_time);
ImageView status_pending = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_pending);
ImageView status_in = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_in);
TextView keyword0 = (TextView)holder.mView.findViewById(R.id.post_keywords0);
TextView keyword1 = (TextView)holder.mView.findViewById(R.id.post_keywords1);
TextView keyword2 = (TextView)holder.mView.findViewById(R.id.post_keywords2);
ImageView userprofilpic = (ImageView)holder.mView.findViewById(R.id.img_userprofilpic);
LinearLayout answer_info = (LinearLayout) holder.mView.findViewById(R.id.answer_info);
Button delete_coversation = (Button) holder.mView.findViewById(R.id.btn_confirm_delete);
userprofilpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("userId", mDataset[position].question.userId);
context.startActivity(i);
}
});
username.setText(mDataset[position].question.userName);
message.setText(mDataset[position].question.text);
keyword0.setText(mDataset[position].question.keywords[0]);
keyword1.setText(mDataset[position].question.keywords[1]);
keyword2.setText(mDataset[position].question.keywords[2]);
addImgToView(mDataset[position].question.photo, userprofilpic);
if (Integer.parseInt(mDataset[position].confirmed) == 1) {
status_pending.setEnabled(false);
status_pending.setVisibility(View.GONE);
status_in.setVisibility(View.VISIBLE);
answer_info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message.setTypeface(Typeface.DEFAULT);
message.onSaveInstanceState();
int convId = mDataset[position].id;
Intent i = new Intent(context, ConversationActivity.class);
i.putExtra("conversationId", "" + convId);
context.startActivity(i);
}
});
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
private void addImgToView(final String uri, final ImageView v){
mRPCHelper.getPhoto(mStorageDir + "/", uri, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
v.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
}
}
Thank you in advance for your time.
maintain a flag in data level to know is it read or unread,based on that you can apply the styles.
There is two way to do this.
First you can ask to backend to write server side to query to handle last activity bases of timestamp .In this case you have to send your particular timestamp to server when you open particular conversation .
Other you can make local database ex-(sql database) and handle it in your own code by updating query when you reading or undreading conversation.

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).

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

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.

Menu button lags a long time when pressed

I have a problem with a menu button called "Refresh" that lags for a long time when pressed. Basically, I'm running an async task that downloads xml from a web page and processes it and then finally updates the current list view. Is there some way to prevent this lag or refactor my code to make it more efficient?
Here is my activity where the refresh problem happens:
public class RouteView extends ListActivity implements ActivityUpdater {
private static ArrayList<String> mRouteNames;
private final String TAG = getClass().getName();
private TextView mTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.route_view);
ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, lv, false);
lv.addHeaderView(header, null, false);
mTv = (TextView) findViewById(R.id.refresh_status);
long start = System.nanoTime();
fetchFeed();
Log.i("MagicBusV2", "Time: " + (System.nanoTime() - start));
}
#Override
protected void onResume() {
super.onResume();
fetchFeed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, Constants.REFRESH_MENU_ID, 0, R.string.refresh).setIcon(R.drawable.refresh);
return result;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case Constants.REFRESH_MENU_ID:
long start = System.nanoTime();
fetchFeed();
Log.i("MagicBusV2", "Refresh time: " + (System.nanoTime() - start));
break;
}
return result;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i(TAG, "id: " + (int) id);
Log.i(TAG, "num_routes: " + mRouteNames.size());
String routeName = mRouteNames.get((int) id);
Intent intent = new Intent(this, StopView.class);
intent.putExtra(Constants.ROUTE_NAME, routeName);
intent.putExtra(Constants.STOP_VIEW_TYPE, Constants.STOPS_ROUTE);
startActivity(intent);
}
public void refreshUI() {
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mRouteNames));
getListView().setTextFilterEnabled(true); // allows users to type to filter results, need to inform them of this some way
mTv.setText("Refreshed!");
}
public static void setRouteNames(ArrayList<String> route_names) {
mRouteNames = route_names;
}
private void fetchFeed() {
mTv.setText("Refreshing...");
new RefreshFeedTask(this).execute("null");
}
And here is my AsyncTask code:
public class RefreshFeedTask extends AsyncTask<String, Integer, Void> {
private ArrayList<Route> routes;
private TimeFeed feed;
private ActivityUpdater updater;
private Context mCtx;
public RefreshFeedTask(Context ctx) {
mCtx = ctx;
updater = (ActivityUpdater) mCtx;
routes = new ArrayList<Route>();
try {
feed = new TimeFeed();
} catch (MBusDataException e) {
e.printStackTrace();
}
}
protected Void doInBackground(String... route_name) {
routes = feed.getRoutes();
int num_routes = routes.size();
if(route_name[0].equals("null")) {
ArrayList<String> route_names_list = new ArrayList<String>(num_routes);
for (int i = 0; i < num_routes; i++) {
route_names_list.add(routes.get(i).getName());
}
RouteView.setRouteNames(route_names_list);
} else if(route_name[0].equals("all_stops")) {
ArrayList<Stop> stops = new ArrayList<Stop>();
for (Route route : routes) {
for (Stop stop : route.getStops()) {
if(!stops.contains(stop)) {
stops.add(stop);
}
}
}
StopView.setStops(stops);
} else if(route_name.length > 1) {
Route route = feed.getRouteWithName(route_name[0]);
StopDetailsView.setStop(route.getStopWithName(route_name[1]));
} else if(route_name[0].equals("favorites")) {
ArrayList<Stop> fav_stops = new ArrayList<Stop>();
ArrayList<Favorite> allFavs = FavoritesStore.getInstance(mCtx).getAllFavorites();
for (Favorite fav : allFavs) {
Route route = feed.getRouteWithName(fav.getRouteName());
if (route != null) {
Stop stop = route.getStopWithName(fav.getStopName());
if (stop != null) {
fav_stops.add(stop);
}
}
}
StopView.setStops(fav_stops);
} else {
StopView.setStops(feed.getRouteWithName(route_name[0]).getStops());
}
return null;
}
protected void onPostExecute(Void ignore) {
updater.refreshUI();
}
Thanks for any help you can give. I apologize if I posted too much code; I wasn't sure how much was needed to find potential problems.
Look at the constructor of the TimeFeed class. Since you said, that you are downloading and parsing stuff, and I believe that you are perhaps doing those things in the constructor, it will obviously take some time to execute that statement.

Categories

Resources