I know that this question is asked 100 times, but for some reason i cannot find what is wrong in my code.
I am very new to android and java.
Basically i have a wordpress website from which I want to get the articles. I have installed the wp-rest-api v2 to get the data in json array format.
In my android app I have
MainActivity.java
package al.im.imp;
/*ALL THE IMPORTS*/
public class ImpHome extends AppCompatActivity implements View.OnClickListener {
ListView lstTest;
JSONAdapter mJSONAdapter;
Button search_Button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imp_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//Access Listview
lstTest = (ListView) findViewById(R.id.home_list);
search_Button = (Button) findViewById(R.id.button1);
search_Button.setOnClickListener(this);
mJSONAdapter = new JSONAdapter(this, getLayoutInflater());
lstTest.setAdapter(mJSONAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_impakt_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void queryImp() {
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/wp-json/wp/v2/posts",
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray jsonArray) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
mJSONAdapter.updateData(jsonArray);
}
#Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("Imp android", statusCode + " " + throwable.getMessage());
}
});
}
#Override
public void onClick(View v) {
queryImp();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
}
My article_list.xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp">
<TextView
android:id="#+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"/>
</RelativeLayout>
and my JSONAdapter.java class
package al.imp.imp;
/*IMPORTS*/
public class JSONAdapter extends BaseAdapter{
Context mContext;
LayoutInflater mInflater;
JSONArray mJsonArray;
public JSONAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
mJsonArray = new JSONArray();
}
#Override
public int getCount() {
return mJsonArray.length();
}
#Override
public Object getItem(int position) {
return mJsonArray.optJSONObject(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.article_list, null);
holder = new ViewHolder();
holder.titleTextView = (TextView) convertView.findViewById(R.id.text_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
JSONObject jsonObject = (JSONObject) getItem(position);
String articleTitle = "";
articleTitle = jsonObject.optJSONObject("title").optString("rendered");
holder.titleTextView.setText(articleTitle);
return convertView;
}
private static class ViewHolder {
public TextView titleTextView;
}
public void updateData(JSONArray jsonArray) {
// update the adapter's dataset
mJsonArray = jsonArray;
notifyDataSetChanged();
}
}
I dont know why this does not work. When i try to log the data like
for (int i = 1; i < jsonArray.length(); i++) {
Log.d("Title is:", jsonArray.optJSONObject(i).getJSONObject("title").getString("rendered").toString());
Log.d("Image Url is:", jsonArray.optJSONObject(i).getString("featured_image_thumbnail_url").toString());
}
it works perfectly, so I guess it is not a problem in getting the json response, but populating the listview.
Help me please
After updating the data, try something like refreshing the list view like lstTest.invalidateViews(); - so your queryImp() code will change into:
private void queryImp() {
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/wp-json/wp/v2/posts",
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray jsonArray) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
mJSONAdapter.updateData(jsonArray);
mJSONAdapter.notifyDataSetChanged();
//try refreshing the list-view like this:
lstTest.invalidateViews()
}
#Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("Imp android", statusCode + " " + throwable.getMessage());
}
});
}
Let me know if the changes help.
Related
Hi in the below code I am getting the below error for displaying a list using recyclerview .
When I am trying to display the list I am getting the below error.
java.lang.ClassCastException: java.lang.String cannot be cast to helper.GetBuildingList
at com.deepshikha.lightingsystem.SwipeRecyclerViewAdapter.onBindViewHolder(SwipeRecyclerViewAdapter.java:41)
at com.deepshikha.lightingsystem.SwipeRecyclerViewAdapter.onBindViewHolder(SwipeRecyclerViewAdapter.java:22)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
Response :
[{"ID":"1","Name":"Building1"},{"ID":"2","Name":"appexx"}]
In the below adapter displays the what are the item presents in the getbuildinglist pojo class.As well as Once user swiped from right to left .We are displaying two options for the list items to edit and delete the items.
SwipeAdapter:
public class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {
private Context mContext;
private List<GetBuildingList> buildingLists;
public SwipeRecyclerViewAdapter(Context context, List<GetBuildingList> strings) {
this.mContext = context;
this.buildingLists = strings;
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
final GetBuildingList item = buildingLists.get(position);
System.out.println ("item"+item);
viewHolder.tvName.setText((item.getName ()) + " - Row Position " + position);
System.out.println (item.getName ());
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
// Drag From Left
// viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));
// Drag From Right
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));
// Handling different events when swiping
viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
//when the SurfaceView totally cover the BottomView.
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
//you are swiping.
}
#Override
public void onStartOpen(SwipeLayout layout) {
}
#Override
public void onOpen(SwipeLayout layout) {
//when the BottomView totally show.
}
#Override
public void onStartClose(SwipeLayout layout) {
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
/*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
//Start your activity
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
}
});*/
viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, " onClick : " + item.getName () + " \n" + item.getID (), Toast.LENGTH_SHORT).show();
}
});
// viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
// }
// });
//
//
// viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
// Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
// }
// });
viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Edit " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
buildingLists.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, buildingLists.size());
mItemManger.closeAllItems();
Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
// mItemManger is member in RecyclerSwipeAdapter Class
mItemManger.bindView(viewHolder.itemView, position);
}
#Override
public int getItemCount() {
return buildingLists.size();
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
// ViewHolder Class
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
TextView tvName;
TextView tvDelete;
TextView tvEdit;
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
tvName = (TextView) itemView.findViewById(R.id.tvName);
// tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
// tvShare = (TextView) itemView.findViewById(R.id.tvShare);
// btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);
}
}
}
In the below code describes the without refreshing the activity I am getting the response from the server.
That response I am adding to arraylist then setting the adapter to the recyclerview to display the list of items with swipe options.
Add.java:
private void doTheAutoRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
progressDialog = new ProgressDialog (getActivity ());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Communicating...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client (client)
.build();
API service = retrofit.create (API.class);
Call<List<GetBuildingList>> userCall = service.getbuildinglist ();
userCall.enqueue(new Callback<List<GetBuildingList>> () {
#Override
public void onResponse(Call <List<GetBuildingList>> call, Response <List<GetBuildingList>> response) {
if(response.isSuccessful()) {
progressDialog.dismiss ( );
Log.d ("Response body", new Gson ( ).toJson (response.body ( )));
String Status = new Gson ( ).toJson (response.body ( ));
JSONArray jsonArray = null;
try {
JSONObject jsonObject=null;
jsonArray = new JSONArray (Status);
arrayList = new ArrayList <> ( );
for (int i=0;i<jsonArray.length ();i++) {
name=jsonArray.getJSONObject (i).getString ("Name");
arrayList.add (name);
}
// Creating Adapter object
SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter((Context) getActivity (), arrayList);
mAdapter.notifyDataSetChanged ();
mRecyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace ( );
}
}
else {
progressDialog.dismiss ();
Log.d("Response errorBody", String.valueOf(response.errorBody()));
}
}
#Override
public void onFailure(Call<List<GetBuildingList>> call, Throwable t) {
// lv.setAdapter (adapter);
System.out.println("onFailure");
System.out.println(t.fillInStackTrace());
progressDialog.dismiss();
Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();;
// progressDialog.dismiss();
}
});
}
}, 5000);
return ;
}
GetBuildingList.java:
public class GetBuildingList{
#SerializedName("ID")
private String ID;
#SerializedName("Name")
private String Name;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
In your onResponse() method you have these lines:
name=jsonArray.getJSONObject (i).getString ("Name");
...
arrayList.add (name);
Then you pass this list to your adapter. This list is assigned to the GetBuildingList field of your adapter. Then in your adapter you do:
final GetBuildingList item = buildingLists.get(position);
So you're trying to cast String type to GetBuildingList type, hence the exception.
Not really familiar with the library but you should try something like this:
for (int i=0;i<jsonArray.length ();i++) {
String name = jsonArray.getJSONObject (i).getString ("Name");
String id = jsonArray.getJSONObject (i).getString ("Id");
GetBuildingList gbl = new GetBuildingList();
gbl.setId(id);
gbl.setName(name);
arrayList.add(gbl);
}
I haven't used this library yet so if I'm wrong, someone please correct the above sample.
I have an app that displays my e-mail via microsoft graph api.
Everything but 1 things i working fine so far. When the list first loads in, all info is correctly displayed, but when i scroll down, then back up. The imageview of the attachement sits on the wrong rows. It just displays on rows without attachement. In the adapter i have an if clausule which says to only show the image in the row if the hasAttachement value is "true".. I really don't get why it is redrawin the image in the wrongs rows..
The method where i set the attachement is called:
setBijlage() in MessagesAdapter
EDIT: If i click the row in my app, that row displays correctly again (gains an icon if it has attachement, and deletes it if it doesn't)
MailActivity.java
public class MailActivity extends AppCompatActivityRest implements SwipeRefreshLayout.OnRefreshListener, MessagesAdapter.MessageAdapterListener {
private String currentFolder;
private String currentUser;
private List<Message> messages = new ArrayList<>();
private RecyclerView recyclerView;
private MessagesAdapter mAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private ActionModeCallback actionModeCallback;
private ActionMode actionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_mail);
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
currentFolder = getString(R.string.inbox);
currentUser = getIntent().getStringExtra("USER_EMAIL");
setActionBarMail(currentFolder, currentUser);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
actionModeCallback = new ActionModeCallback();
// show loader and fetch messages
swipeRefreshLayout.post(
new Runnable() {
#Override
public void run() {
getAllMails(15);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search...", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void processResponse(OutlookObjectCall outlookObjectCall, JSONObject response) {
switch (outlookObjectCall) {
case READUSER: {
System.out.println("reading user");
} break;
case READMAIL: {
messages.clear();
JSONObject list = response;
try {
JSONArray mails = list.getJSONArray("value");
Type listType = new TypeToken<List<Message>>() {
}.getType();
messages = new Gson().fromJson(String.valueOf(mails), listType);
for (Message message : messages) {
message.setColor(getRandomMaterialColor("400"));
}
System.out.println(messages.get(2).getFrom().getEmailAddress().getName());
mAdapter = new MessagesAdapter(this, messages, this);
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
break;
case SENDMAIL: {
System.out.println("Just send a mail." );
}
}
}
#Override
public void onRefresh() {
// swipe refresh is performed, fetch the messages again
getAllMails(15);
}
#Override
public void onIconClicked(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
#Override
public void onIconImportantClicked(int position) {
// Star icon is clicked,
// mark the message as important
Message message = messages.get(position);
message.setImportance("normal");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
}
#Override
public void onMessageRowClicked(int position) {
// verify whether action mode is enabled or not
// if enabled, change the row state to activated
if (mAdapter.getSelectedItemCount() > 0) {
enableActionMode(position);
} else {
// read the message which removes bold from the row
Message message = messages.get(position);
message.setIsRead("true");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: " + message.getBodyPreview(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRowLongClicked(int position) {
// long press is performed, enable action mode
enableActionMode(position);
}
private void enableActionMode(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
private void toggleSelection(int position) {
mAdapter.toggleSelection(position);
int count = mAdapter.getSelectedItemCount();
if (count == 0) {
actionMode.finish();
} else {
actionMode.setTitle(String.valueOf(count));
actionMode.invalidate();
}
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_action_mode, menu);
// disable swipe refresh if action mode is enabled
swipeRefreshLayout.setEnabled(false);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
// delete all the selected messages
deleteMessages();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mAdapter.clearSelections();
swipeRefreshLayout.setEnabled(true);
actionMode = null;
recyclerView.post(new Runnable() {
#Override
public void run() {
mAdapter.resetAnimationIndex();
// mAdapter.notifyDataSetChanged();
}
});
}
}
// deleting the messages from recycler view
private void deleteMessages() {
mAdapter.resetAnimationIndex();
List<Integer> selectedItemPositions =
mAdapter.getSelectedItems();
for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
mAdapter.removeData(selectedItemPositions.get(i));
}
mAdapter.notifyDataSetChanged();
}
private void setActionBarMail(String title, String subtitle) {
getSupportActionBar().setTitle(title);
getSupportActionBar().setSubtitle(subtitle);
}
private void getAllMails(int aantalMails) {
swipeRefreshLayout.setRefreshing(true);
try {
new GraphAPI().getRequest(OutlookObjectCall.READMAIL, this, "/inbox/messages?$top=" + aantalMails);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private int getRandomMaterialColor(String typeColor) {
int returnColor = Color.GRAY;
int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
MessagesAdapter.java
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MyViewHolder> {
private Context mContext;
private List<Message> messages;
private MessageAdapterListener listener;
private SparseBooleanArray selectedItems;
// array used to perform multiple animation at once
private SparseBooleanArray animationItemsIndex;
private boolean reverseAllAnimations = false;
// index is used to animate only the selected row
// dirty fix, find a better solution
private static int currentSelectedIndex = -1;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener {
public TextView from, subject, message, iconText, timestamp;
public ImageView iconImp, imgProfile, imgBijlage;
public LinearLayout messageContainer;
public RelativeLayout iconContainer, iconBack, iconFront;
public MyViewHolder(View view) {
super(view);
from = (TextView) view.findViewById(R.id.from);
subject = (TextView) view.findViewById(R.id.txt_primary);
message = (TextView) view.findViewById(R.id.txt_secondary);
iconText = (TextView) view.findViewById(R.id.icon_text);
timestamp = (TextView) view.findViewById(R.id.timestamp);
iconBack = (RelativeLayout) view.findViewById(R.id.icon_back);
iconFront = (RelativeLayout) view.findViewById(R.id.icon_front);
iconImp = (ImageView) view.findViewById(R.id.icon_star);
imgProfile = (ImageView) view.findViewById(R.id.icon_profile);
messageContainer = (LinearLayout) view.findViewById(R.id.message_container);
iconContainer = (RelativeLayout) view.findViewById(R.id.icon_container);
imgBijlage = (ImageView) view.findViewById(R.id.icon_attachement);
view.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(getAdapterPosition());
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
}
public MessagesAdapter(Context mContext, List<Message> messages, MessageAdapterListener listener) {
this.mContext = mContext;
this.messages = messages;
this.listener = listener;
selectedItems = new SparseBooleanArray();
animationItemsIndex = new SparseBooleanArray();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Message message = messages.get(position);
// displaying text view data
holder.from.setText(message.getFrom().getEmailAddress().getName());
holder.subject.setText(message.getSubject());
holder.message.setText(message.getBodyPreview());
System.out.println("EMAIL: " + position + " HAS ATTACHEMENT: " + message.getHasAttachments());
setBijlage(message, holder);
try {
setDate(message, holder);
} catch (ParseException e) {
e.printStackTrace();
}
// displaying the first letter of From in icon text
holder.iconText.setText(message.getFrom().getEmailAddress().getName().substring(0, 1));
// change the row state to activated
holder.itemView.setActivated(selectedItems.get(position, false));
// change the font style depending on message read status
applyReadStatus(holder, message);
// handle message star
applyImportant(holder, message);
// handle icon animation
applyIconAnimation(holder, position);
// display profile image
applyProfilePicture(holder, message);
// apply click events
applyClickEvents(holder, position);
}
private void setDate(Message message, MyViewHolder holder) throws ParseException {
String stringDate = message.getReceivedDateTime();
String COMPARE_FORMAT = "yyyy/MM/dd";
String OUTPUT_FORMAT_NOT_TODAY = "dd MMM";
String JSON_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat dateFormat = new SimpleDateFormat(COMPARE_FORMAT);
SimpleDateFormat formatter = new SimpleDateFormat(JSON_FORMAT);
SimpleDateFormat defaultFormat = new SimpleDateFormat(OUTPUT_FORMAT_NOT_TODAY);
//today date (check if today)
Date today = new Date();
String currentDate = dateFormat.format(today);
//hours (if today
Date date = formatter.parse(stringDate);
formatter.applyPattern(COMPARE_FORMAT);
String mailDate = formatter.format(date);
//dd/month (if not today)
boolean is24 = DateFormat.is24HourFormat(mContext);
if (mailDate.equals(currentDate)) {
if (is24) {
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm");
holder.timestamp.setText(outputFormat.format(date));
} else {
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a");
holder.timestamp.setText(outputFormat.format(date));
}
} else {
holder.timestamp.setText(defaultFormat.format(date));
}
}
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}
}
private void applyClickEvents(MyViewHolder holder, final int position) {
holder.iconContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconClicked(position);
}
});
holder.iconImp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconImportantClicked(position);
}
});
holder.messageContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onMessageRowClicked(position);
}
});
holder.messageContainer.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(position);
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
});
}
private void applyProfilePicture(MyViewHolder holder, Message message) {
holder.imgProfile.setImageResource(R.drawable.bg_circle);
holder.imgProfile.setColorFilter(message.getColor());
holder.iconText.setVisibility(View.VISIBLE);
}
private void applyIconAnimation(MyViewHolder holder, int position) {
if (selectedItems.get(position, false)) {
holder.iconFront.setVisibility(View.GONE);
resetIconYAxis(holder.iconBack);
holder.iconBack.setVisibility(View.VISIBLE);
holder.iconBack.setAlpha(1);
if (currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, true);
resetCurrentIndex();
}
} else {
holder.iconBack.setVisibility(View.GONE);
resetIconYAxis(holder.iconFront);
holder.iconFront.setVisibility(View.VISIBLE);
holder.iconFront.setAlpha(1);
if ((reverseAllAnimations && animationItemsIndex.get(position, false)) || currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, false);
resetCurrentIndex();
}
}
}
// As the views will be reused, sometimes the icon appears as
// flipped because older view is reused. Reset the Y-axis to 0
private void resetIconYAxis(View view) {
if (view.getRotationY() != 0) {
view.setRotationY(0);
}
}
public void resetAnimationIndex() {
reverseAllAnimations = false;
animationItemsIndex.clear();
}
#Override
public long getItemId(int position) {
return messages.get(position).getAutoId();
}
private void applyImportant(MyViewHolder holder, Message message) {
if (message.getImportance().toLowerCase().equals("high")) {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_selected));
} else {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_border_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_normal));
}
}
private void applyReadStatus(MyViewHolder holder, Message message) {
if (message.getIsRead().toLowerCase().equals("true")) {
holder.from.setTypeface(null, Typeface.NORMAL);
holder.subject.setTypeface(null, Typeface.NORMAL);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.message));
} else {
holder.from.setTypeface(null, Typeface.BOLD);
holder.subject.setTypeface(null, Typeface.BOLD);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.from));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
}
}
#Override
public int getItemCount() {
return messages.size();
}
public void toggleSelection(int pos) {
currentSelectedIndex = pos;
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
animationItemsIndex.delete(pos);
} else {
selectedItems.put(pos, true);
animationItemsIndex.put(pos, true);
}
notifyItemChanged(pos);
}
public void clearSelections() {
reverseAllAnimations = true;
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
public void removeData(int position) {
messages.remove(position);
resetCurrentIndex();
}
private void resetCurrentIndex() {
currentSelectedIndex = -1;
}
public interface MessageAdapterListener {
void onIconClicked(int position);
void onIconImportantClicked(int position);
void onMessageRowClicked(int position);
void onRowLongClicked(int position);
}
}
Change setBijlage to this..
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}else{
holder.imgBijlage.setVisibility(View.GONE);
}
}
That's occours because the recyclerView reuses the references of the rows and in your case, some rows doesnt have any reference in holder.imgBijlage, causing missbehavior.
To solve this, put holder.imgBijlage.setImageResource(R.drawable.ic_bijlage); inside onBindViewHolder and change setBijlage to:
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
}else {
holder.imgBijlage.setVisibility(View.INVISIBLE);
}
Your icon will be hidden when there is no attachement
I am developing an Android app that has the capability to sort movies by most popular or top rated from the moviedb.org api. The app is supposed to get new data from the server when the setting is changed. This is not working. Here is my code please help me through it:
//MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(savedInstanceState==null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment,new MainActivityFragment()).commit();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this,SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
//SettingsActivity.java
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_order_key)));
}
public void bindPreferenceSummaryToValue(Preference preference){
preference.setOnPreferenceChangeListener(this);
onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue=value.toString();
if(preference instanceof ListPreference){
ListPreference listPreference=(ListPreference)preference;
int prefIndex=listPreference.findIndexOfValue(stringValue);
if(prefIndex>=0){
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
}else {
preference.setSummary(stringValue);
}
return true;
}
//MainActivityFragment.java
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_main, container, false);
if (getActivity()!=null){
ArrayList<String>arrayList=new ArrayList<String>();
PosterAdapter imageAdapter=new PosterAdapter(getActivity(),arrayList,deviceWidth);
imageGridView=(GridView)rootView.findViewById(R.id.image_grid_view);
imageGridView.setColumnWidth(deviceWidth);
imageGridView.setAdapter(imageAdapter);
}
imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra("overview", overview.get(position))
.putExtra("poster", images.get(position))
.putExtra("title", title.get(position))
.putExtra("date", date.get(position))
.putExtra("rating", rating.get(position));
startActivity(intent);
}
});
return rootView;
}
private class PreferenceChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
imageGridView.setAdapter(null);
onStart();
}
}
#Override
public void onStart(){
super.onStart();
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
preferenceChangeListener=new PreferenceChangeListener();
sharedPreferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
if (sharedPreferences.getString(getString(R.string.pref_order_key),"").equals(R.string.pref_order_most_popular)){
sortByPopular=true;
}else if (sharedPreferences.getString(getString(R.string.pref_order_key),"").equals(R.string.pref_order_top_rated)){
sortByPopular=false;
}
ImageLoader imageLoader=new ImageLoader();
if (isInternetAvailable()) {
imageLoader.execute();
Log.v(LOG_TAG,"async task completed");
}else {
TextView textView=new TextView(getActivity());
RelativeLayout relativeLayout=(RelativeLayout)getActivity().findViewById(R.id.fragment_layout);
textView.setText("There is no Internet service");
if (relativeLayout.getChildCount()==1){
relativeLayout.addView(textView);
}
imageGridView.setVisibility(GridView.GONE);
}
}
public boolean isInternetAvailable(){
ConnectivityManager connectivityManager=(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return networkInfo !=null&&networkInfo.isConnected();
}
public class ImageLoader extends AsyncTask<Void,Void,ArrayList<String>>{
#Override
protected ArrayList<String> doInBackground(Void... params) {
while (true){
try {
images=new ArrayList<>(Arrays.asList(getPathsFromURL(sortByPopular)));
return images;
}catch (Exception e){
continue;
}
}
}
#Override
protected void onPostExecute(ArrayList<String>results){
if (results!=null&&getActivity()!=null){
PosterAdapter posterAdapter=new PosterAdapter(getActivity(),results,deviceWidth);
imageGridView.setAdapter(posterAdapter);
}
}
public String[] getPathsFromURL(boolean sorting){
while (true){
HttpURLConnection httpURLConnection=null;
BufferedReader bufferedReader=null;
String JSONResult;
try {
if (sortByPopular){
url = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=281ad0257e71bca17a21b42c9fee7304";
}else {
url="http://api.themoviedb.org/3/discover/movie?sort_by=vote_average.desc&vote_count.gte=500&api_key=281ad0257e71bca17a21b42c9fee7304";
}
URL url1=new URL(url);
httpURLConnection=(HttpURLConnection)url1.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream inputStream=httpURLConnection.getInputStream();
StringBuffer stringBuffer=new StringBuffer();
if (inputStream==null){
return null;
}
bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String data;
while ((data=bufferedReader.readLine())!=null){
stringBuffer.append(data+"\n");
}
if (stringBuffer.length()==0){
return null;
}
JSONResult=stringBuffer.toString();
Log.v(LOG_TAG,JSONResult);
try {
overview=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "overview")));
title=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "original_title")));
rating=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "vote_average")));
date=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "release_date")));
return getDataFromJSON(JSONResult);
}catch (JSONException e){
return null;
}
}catch (Exception e){
continue;
}finally {
if (httpURLConnection!=null){
httpURLConnection.disconnect();
}
if (bufferedReader!=null){
try {
bufferedReader.close();
}catch (final IOException e){
}
}
}
}
}
}
public String[] getStringsFromAPI(String JSONStringParameter,String parameter) throws JSONException{
JSONObject jsonObject=new JSONObject(JSONStringParameter);
JSONArray jsonArray=jsonObject.getJSONArray("results");
String[] results=new String[jsonArray.length()];
for (int i=0;i<jsonArray.length();i++){
JSONObject poster=jsonArray.getJSONObject(i);
if (parameter.equals("vote_average")){
Double decimalNumber=poster.getDouble("vote_average");
String userRating=Double.toString(decimalNumber)+"/10";
results[i]=userRating;
}
String posterPath=poster.getString(parameter);
results[i]=posterPath;
}
return results;
}
public String[] getDataFromJSON(String JSONStringParameter)throws JSONException{
JSONObject jsonObject=new JSONObject(JSONStringParameter);
JSONArray jsonArray=jsonObject.getJSONArray("results");
String[] results=new String[jsonArray.length()];
for (int i=0;i<jsonArray.length();i++){
JSONObject poster=jsonArray.getJSONObject(i);
String posterPath=poster.getString("poster_path");
results[i]=posterPath;
}
return results;
}
//PosterAdapter.java
private Context context;
private ArrayList<String> arrayList;
private int posterWidth;
public PosterAdapter(Context c,ArrayList<String> filePaths,int a){
context=c;
arrayList=filePaths;
posterWidth=a;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if (convertView==null){
image=new ImageView(context);
}else {
image=(ImageView)convertView;
}
String url = "http://image.tmdb.org/t/p/w185" + arrayList.get(position);
Picasso.with(context).load(url).into(image);
return image;
}
Thank you in advance
I spoke to another developer and it appears that my code is accurate and there is a bug that the other developer is trying to figure out. I'll keep you guys posted. Thank you for your help.
I have tested my app with the emulator and everything works as expected. now im debugging the app via usb debugging. This is when i get this issue. I have a ListView in my app. When the user press a List Item it starts a new activity. My issue is, after the user press the back button, the ListView is not generated again. I just a blank activity.Even if i restart the app, when i go to the activity that contains the ListView, it wont generate the ListView. The only way to fix this is to clear the data of my application via my phone settings. What is causing this issue? Why is it working well with the emulator and not with my phone? (Im using a Xiaomi Mi4) any help would be much appreciated.
CustomListAdapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Guide> guideItems;
public CustomListAdapter(Activity activity, List<Guide> guideItems) {
this.activity = activity;
this.guideItems = guideItems;
}
#Override
public int getCount() {
return guideItems.size();
}
#Override
public Object getItem(int location) {
return guideItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customrow, parent, false);
TextView ngno = (TextView) convertView.findViewById(R.id.txt_ListNgno);
TextView name = (TextView) convertView.findViewById(R.id.txt_ListName);
TextView email = (TextView) convertView.findViewById(R.id.txt_ListEmail);
// getting movie data for the row
Guide g = guideItems.get(position);
ngno.setText(g.getNgno());
name.setText(g.getName());
email.setText(g.getEmail());
return convertView;
}
}
This is the activity that implements the ListView.
public class ViewGuidesActivity extends AppCompatActivity {
private static final String TAG = ViewGuidesActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Guide> guideList = new ArrayList<Guide>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_guides);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, guideList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_GET_GUIDE_LIST,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Guide guide = new Guide();
guide.setNgno(obj.getString("ngno"));
guide.setEmail(obj.getString("email"));
guide.setName(obj.getString("name"));
// adding movie to movies array
guideList.add(guide);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Guide newGuide = guideList.get(position);
String email = newGuide.getEmail();
String ngno = newGuide.getNgno();
//System.out.println(email);
Intent i = new Intent(getApplicationContext(), GuideDetails.class);
i.putExtra("email", email);
i.putExtra("ngno", ngno);
startActivity(i);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.getItem(1).setVisible(false);
menu.getItem(2).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
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).