I'm trying to update the recyclerview Items from the data in SQLite database which in turn gets updated with data fetched from API from time to time.
I have a TabLayout which contain three fragments.
Now in one fragment, I show the games played by the users in form of a recyclerView. Each item of the recyclerView contains the User Name, his high score and the no. of other users who have beaten his high score.
Now in the fragment, I'm calling an API to update a database inside AsyncTask then again using the same database in the RecyclerView Adapter Class to retrieve data in another AsyncTask. The AsyncTask is called periodically using TimerTask and Handler.
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class PerformBackgroundTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... gameID) {
try{
SQLiteDatabase challengeDatabase = mContext.openOrCreateDatabase("Challenge", Context.MODE_PRIVATE, null);
challengeDatabase.execSQL("CREATE TABLE IF NOT EXISTS DISPLAY_MESSAGE (gameID VARCHAR, highestScorer VARCHAR, count INT)");
Cursor d = challengeDatabase.rawQuery("SELECT * FROM DISPLAY_MESSAGE WHERE gameID", null);
int gameCode = d.getColumnIndex("gameID");
int highestScorer = d.getColumnIndex("highestScorer");
int count = d.getColumnIndex("count");
d.moveToFirst();
while(d!=null&&d.getCount()>0){
if((d.getString(gameCode)).equals(gameID)){
int k = Integer.parseInt(d.getString(count));
if(k>0)
{
return d.getString(highestScorer) + " and " + k + " others have beaten your highscore.";
}else if(k==0){
return d.getString(highestScorer) + " has beaten your highscore.";
}
else{
return "Yay! you have beaten all your opponents!";
}
}
d.moveToNext();
}
challengeDatabase.close();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
public GridAdapterChallenge(Context c, List<CardContainer> listCards, Vector<Object> cardDetails, String sname) {
//selectedCards = new HashSet<Integer>();
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = c;
this.listCards = listCards;
this.sname = sname;
cards = cardDetails;
//notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private int viewType;
private ImageView imageView;
private Button increaseScore, challengeFriend;
private TextView challengeDetails, points, name, challengeCode;
private ImageView nativeAdIcon;
private TextView nativeAdTitle;
private TextView nativeAdBody;
private MediaView nativeAdMedia;
private TextView nativeAdSocialContext;
private Button nativeAdCallToAction;
private ProgressBar detailProgress;
public ViewHolder(#NonNull View itemView, int viewType) {
super(itemView);
view = itemView;
this.viewType = viewType;
if (viewType == 1) {
this.imageView = (ImageView) itemView.findViewById(R.id.thumb);
this.name = (TextView) itemView.findViewById(R.id.gameName);
this.challengeCode = itemView.findViewById(R.id.challengeCode);
this.points = itemView.findViewById(R.id.points);
this.challengeDetails = itemView.findViewById(R.id.challengeDetail);
this.increaseScore = itemView.findViewById(R.id.increaseScore);
this.challengeFriend = itemView.findViewById(R.id.challengeFriend);
this.challengeDetails = itemView.findViewById(R.id.challengeDetail);
this.detailProgress = itemView.findViewById(R.id.detailProgressBar);
} else {
this.nativeAdIcon = (ImageView) itemView.findViewById(R.id.native_ad_icon);
this.nativeAdTitle = (TextView) itemView.findViewById(R.id.native_ad_title);
this.nativeAdBody = (TextView) itemView.findViewById(R.id.native_ad_body);
this.nativeAdMedia = (MediaView) itemView.findViewById(R.id.native_ad_media);
this.nativeAdSocialContext = (TextView) itemView.findViewById(R.id.native_ad_social_context);
this.nativeAdCallToAction = (Button) itemView.findViewById(R.id.native_ad_call_to_action);
}
}
}
public void updateDetails(final TextView challengeDetails, final String gameId) {
final Handler handler;
handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
challengeDetails.setText((CharSequence) performBackgroundTask.execute(gameId));
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 4000, 5000); //execute in every 1000 ms
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
if (viewHolder.viewType == 0) {
if (adList != null && adList.size() > (i+1)/5 - 1 && adList.get((i+1)/5 - 1) != null) {
NativeAd ad = adList.get((i+1)/5 - 1);
viewHolder.nativeAdSocialContext.setText(ad.getAdSocialContext());
viewHolder.nativeAdCallToAction.setText(ad.getAdCallToAction());
viewHolder.nativeAdCallToAction.setVisibility(View.VISIBLE);
viewHolder.nativeAdTitle.setText(ad.getAdHeadline());
viewHolder.nativeAdBody.setText(ad.getAdBodyText());
ad.registerViewForInteraction(viewHolder.itemView, viewHolder.nativeAdMedia, viewHolder.nativeAdIcon, Arrays.asList(viewHolder.nativeAdCallToAction, viewHolder.nativeAdMedia));
NativeAd.Image adCoverImage = ad.getAdCoverImage();
int bannerWidth = adCoverImage.getWidth();
int bannerHeight = adCoverImage.getHeight();
DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
int mediaWidth = viewHolder.itemView.getWidth() > 0 ? viewHolder.itemView.getWidth() : metrics.widthPixels;
viewHolder.nativeAdMedia.setLayoutParams(new LinearLayout.LayoutParams(mediaWidth, Math.min(
(int) (((double) mediaWidth / (double) bannerWidth) * bannerHeight), metrics.heightPixels / 3)));
ad.registerViewForInteraction(viewHolder.itemView, viewHolder.nativeAdMedia, Arrays.asList(viewHolder.nativeAdCallToAction, viewHolder.nativeAdMedia));
ad.registerViewForInteraction(viewHolder.itemView, viewHolder.nativeAdMedia);
}
} else{
viewHolder.name.setText(((CardContainer)cards.get(i)).name);
challengeCode = getChallengeCode(i);
viewHolder.challengeCode.setText(challengeCode);
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
if(getHighScore(((CardContainer)cards.get(i)).gameId)>0){
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
viewHolder.challengeDetails.setText(performBackgroundTask.execute(gameId).toString());
//updateDetails(viewHolder.challengeDetails, ((CardContainer)cards.get(i)).gameId);
}
else{
viewHolder.challengeDetails.setText("Press Increase Score To Play the Game");
}
viewHolder.detailProgress.setVisibility(View.GONE);
int width = displayMetrics.widthPixels;
try {
final String uri = ((CardContainer) cards.get(i)).imageurl;
if (uri != null) {
Picasso.get().load(uri)
.placeholder(R.mipmap.place)
.error(R.mipmap.place)
.resize(width / 2, width / 2)
.centerCrop()
.into(viewHolder.imageView);
}
}
catch (Exception e){
final String uri = null;
}
viewHolder.points.setText(String.valueOf(getHighScore(((CardContainer)cards.get(i)).gameId)));
viewHolder.increaseScore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (((CardContainer) cards.get(i)).link.contains("play.google.com")) {
openAppRating(mContext,((CardContainer) cards.get(i)).link.split("id=", 2)[1]);
}
else{
name = ((CardContainer) cards.get(i)).name;
link = ((CardContainer) cards.get(i)).link;
imageurl = ((CardContainer) cards.get(i)).imageurl;
type = ((CardContainer) cards.get(i)).type;
packageName = ((CardContainer) cards.get(i)).packageName;
gameId = ((CardContainer)cards.get(i)).gameId;
challengeNames.add(name);
updateDatabase(name, gameId, Config.uid+"#"+gameId, 0, viewHolder.points);
//String gameName, String gameId, String mychCode, int myHighScore
}
}
});
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
String name = ((CardContainer) cards.get(i)).name;
String link = ((CardContainer) cards.get(i)).link;
String imageurl = ((CardContainer) cards.get(i)).imageurl;
String type = ((CardContainer) cards.get(i)).type;
String packageName = ((CardContainer) cards.get(i)).packageName;
Bitmap bitmap = null;
Integer xyz = android.os.Build.VERSION.SDK_INT;
#Override
public boolean onLongClick(View view) {
bitmap = ((BitmapDrawable) viewHolder.imageView.getDrawable()).getBitmap();
if (sname.equals("fav")) {
// Toast.makeText(mContext, "in fav", Toast.LENGTH_SHORT).show();
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
TextView dialogText=dialog.findViewById(R.id.txt_dia);
dialogText.setText("Do you want to remove "+name+" from your favorites?");
dialog.show();
Button yes_button = (Button) dialog.findViewById(R.id.btn_yes);
yes_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
favf = new FavFunction(mContext);
int resultFav=favf.removeFromFavorite(link);
if (resultFav>=0){
cards.remove(resultFav);
notifyDataSetChanged();
}
dialog.dismiss();
}
});
Button no_button = (Button) dialog.findViewById(R.id.btn_no);
no_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
return true;
}
else{
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
TextView dialogText=dialog.findViewById(R.id.txt_dia);
dialogText.setText("Adding "+name+" to favorites... Do you also want to create it's homescreen shortcut?");
dialog.show();
Button yes_button = (Button) dialog.findViewById(R.id.btn_yes);
yes_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
favf = new FavFunction(mContext);
Boolean favstatus=favf.addToFavorite(imageurl, link ,name,type,packageName);
favf.addShortcut(name, link , imageurl,type,packageName,bitmap);
if(favstatus){
((Activity) mContext).recreate();
}
dialog.dismiss();
}
});
Button no_button = (Button) dialog.findViewById(R.id.btn_no);
no_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
favf = new FavFunction(mContext);
Boolean favstatus=favf.addToFavorite(imageurl, link, name,type,packageName);
if(favstatus){
((Activity) mContext).recreate();
}
dialog.dismiss();
}
});
return true;
}
}
});
viewHolder.challengeFriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey! I challenge you to beat my highscore " + getHighScore(gameId) + " in this awesome game. Enter my challenge code " + challengeCode + " in the \"Challenges\" Tab of 101 Game Store App. You can download the app from bit.ly/101gamestore");
sendIntent.setType("text/plain");
mContext.startActivity(sendIntent);
}
});
}
}
I want to update the no. of high scorer inside each item of the recyclerView. However what is happening is the UI get frozen as soon as the TimerTask starts. The data is being fetched successfully. Any solution approach better than mine would be appreciated.
For update your adapter, you should do it in main thread. AsyncTask provides onPostExecute method.
Do not replace adapter, instead you should replace data in the adapter.
class MyAsyncTask extends AsyncTask<Void, Void, List<String>> {
MyAdapter myAdapter;
ArrayList<String> values = new ArrayList<>();
public MyAsyncTask(MyAdapter adapter) {
this.myAdapter = myAdapter;
}
#Override
protected List<String> doInBackground(String... params) {
ArrayList<String> result = new ArrayList<>();
// long operation, for example: get results from url
return result;
}
#Override
protected void onPostExecute(List<String> list) {
myAdapter.setNewList(list);
}
}
class MyAdapter {
private List<String> list;
............
void setNewList(List<String> list) {
this.list = list;
notifyDataSetChanged();
}
............
}
Just have a look here ....
class MyAsyncTask extends AsyncTask<String, Void, String> {
Context mContext;
ArrayList<String> values= new ArrayList<String>();
public MyAsyncTask(Context context) {
mContext = context;
}
#Override
protected String doInBackground(String... params) {
// do your all database operation here and try to stroe in arraylist
values.add("Data comes from database");
return "";
}
#Override
protected void onPostExecute(String list) {
// Do your View update here.
// All your Recycle View here
yourRecycleView.setAdapter(new MyAdapter(context,values))
}
}
Note:- In AsynTask do all bind work in onPreExecute() method , do all database or long thread work in doInBackground() method (such as fetching data from database, download files or upload files ,etc) and update your Views in onPostExecute() method.
How to update the RecyclerView Items Using AsyncTask?
Follow the same process get your data in doInBackground() method and notify your adapter in onPostExecute() method. Do this opertion in other AsynTask
Related
I have Recycler view where I am displaying the items with Item name, Item rate and quantity of the items which is increased and decreased by +/- buttons respectively. now, i want to get all the values from each item of the Recycler view and send it over the server or save it to local database so how to achieve this.?
TeaListAdapter.java
public class TeaListAdapter extends RecyclerView.Adapter<TeaListAdapter.MyViewHolder> {
PlaceOrderActivity.DataTransferInterface dtInterface;
//private int num=0;
private List<TeaListPOJO> teaItemList;
private Context mContext;
private Cursor cursor;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tvitemName, tvitemRate,tvcount; //number
public ImageView ivItemImg,ivPlus,ivMinus;
public Button btnIncrease,btnDecrease;
RecyclerView.ViewHolder holder;
public MyViewHolder(View view) {
super(view);
tvitemName = (TextView) view.findViewById(R.id.txt_item_name);
tvitemRate = (TextView) view.findViewById(R.id.txt_item_price);
ivItemImg= (ImageView) view.findViewById (R.id.iv_item);
ivPlus=(ImageView) view.findViewById (R.id.row_view_final_order_iv_plus);
ivMinus=(ImageView) view.findViewById (R.id.row_view_final_order_iv_minus);
tvcount=(TextView) view.findViewById (R.id.row_view_final_order_tv_count);
}
}
public TeaListAdapter(List<TeaListPOJO> teaItemList) {
this.mContext=mContext;
this.cursor=cursor;
this.teaItemList = teaItemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_placeorder_items, parent, false);
return new MyViewHolder (itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final TeaListPOJO tealist = teaItemList.get(position);
holder.tvitemName.setText(tealist.getItemName ());
holder.tvitemRate.setText(AppConstants.INDIAN_RUPEE_SIGN.concat (tealist.getItemRate ()));
holder.ivPlus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
//count++;
count = Integer.parseInt(holder.tvcount.getText().toString());
holder.tvcount.setText(String.valueOf(count+ 1));
tealist.setCount (count);
Log.e ("count", String.valueOf (count));
}
});
holder.ivMinus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
if(count>0) {
//count--;
count = Integer.parseInt (holder.tvcount.getText ().toString ());
holder.tvcount.setText (String.valueOf (count - 1));
tealist.setCount (count);
}
}
});
byte[] decodedString = new byte[0];
try {
decodedString = Base64.decode(tealist.getImageStr(), Base64.DEFAULT);
// tenantModelPOJO.setLogo(decodedString);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivItemImg.setImageBitmap(Bitmap.createScaledBitmap(bmp, 50, 50,false));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return teaItemList.size();
}
}
PlaceOrderActivity.java
public class PlaceOrderActivity extends AppCompatActivity implements AppConstants, View.OnClickListener, WLAPIcalls.OnAPICallCompleteListener {
private List<TeaListPOJO> teaList = new ArrayList<> ();
private RecyclerView recyclerView;
private TeaListAdapter mAdapter;
private View view;
private Button btnPlaceorder;
EditText edtmsg;
public String str;
private Context mContext = PlaceOrderActivity.this;
private int itemCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_place_order);
setRecyclerView (view);
getallTeaItems ();
}
List<TeaListPOJO> getTeaItemList(String str) {
Gson gson = new Gson ();
Type listType = new TypeToken<List<TeaListPOJO>> () {
}.getType ();
List<TeaListPOJO> myModelList = gson.fromJson (str, listType);
return myModelList;
}
private List<TeaListPOJO> getallTeaItems() {
if (new AppCommonMethods (mContext).isNetworkAvailable ()) {
WLAPIcalls mAPIcall = new WLAPIcalls (mContext, getString (R.string.getTeaItem), this);
mAPIcall.GetTeaItemList ();
} else {
Toast.makeText (mContext, R.string.no_internet, Toast.LENGTH_SHORT).show ();
}
return null;
}
void setRecyclerView(View view) {
recyclerView = (RecyclerView) findViewById (R.id.recycler_view);
mAdapter = new TeaListAdapter (teaList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager (getApplicationContext ());
recyclerView.setLayoutManager (mLayoutManager);
recyclerView.setItemAnimator (new DefaultItemAnimator ());
recyclerView.setAdapter (mAdapter);
}
#Override
public void onClick(View view) {
}
#Override
public void onAPICallCompleteListner(Object item, String flag, String result) throws JSONException {
if (getString (R.string.getTeaItem).equals (flag)) {
Log.e ("Result", result);
teaList = getTeaItemList (result);
setRecyclerView (view);
}
}
}
So you are already passing the arraylist (teaItemList) in your constructor of your adapter. Since the reference is same you can use the same array list for saving or sending it to the database.
Since name and price of items are same, You need to get the value only like for if user clicks + = String.valueOf(count+ 1) and for (-) = String.valueOf(count - 1)
So add one more field like (int count) in teaPOJO and
whenever user clicks + :
Do this
holder.ivPlus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
TeaPojo teaPojo = teaItemList.get(getAdapterPosition);
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
//count++;
count = Integer.parseInt(holder.tvcount.getText().toString());
holder.tvcount.setText(String.valueOf(count+ 1));
teaPojo.setCount(count);
Log.e ("count", String.valueOf (count));
}
});
User clicks - :
holder.ivMinus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
TeaPojo teaPojo = teaItemList.get(getAdapterPosition);
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
if(count>0) {
//count--;
count = Integer.parseInt(holder.tvcount.getText().toString ());
holder.tvcount.setText (String.valueOf (count - 1));
teaPojo.setCount(count);
tealist.setCount (count);
}enter code here
}
});
// if you want to save in db from activity itself only
saveToDb(teaItemList);
// if you want to send to server from activity itself only
handleSendToServer(teaItemList);
I am implementing a local chat_box like page, I have two Vectors queued_messages and messages. I remove items from queued list and add to the messages and wait in the asynctask to add other items.three kind of messages sent received and multiple choice questions.multiple choice questions have the problems in the title.(especially if you scroll to top page while they get loading)
1.I have already set has fixed size to true
2.tried making custom view directly in adapter instead of inflating a view containing it
3.set is recyclable to off and implemented both selected and unselected mode in onbindviewholder
4.tried different kind of notifies.
5.disabled scroll to last position
my Adapter:
public class MessageListAdapter extends RecyclerView.Adapter {
private List<Message> messages;
MessageListAdapter(List<Message> messages) {
this.messages = messages;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view;
if (i == Message.RECEIVED_MESSAGE) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recieved_message, viewGroup, false);
return new Received_Message_Holder(view);
} else if (i == Message.MULTIPLE_CHOICE) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.multiple_choice_item, viewGroup, false);
return new Multiple_Choice_Holder(view);
} else if (i == Message.SENT_MESSAGE) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.sent_message, viewGroup, false);
return new Sent_Message_Holder(view);
}else
return null;
}
#Override
public int getItemViewType(int position) {
Message message = messages.get(position);
return message.getType();
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
Message msg = messages.get(i);
if (msg.getType() == Message.RECEIVED_MESSAGE)
((Received_Message_Holder) viewHolder).bind(msg);
else if (msg.getType() == Message.MULTIPLE_CHOICE) {
//viewHolder.setIsRecyclable(false);
((Multiple_Choice_Holder) viewHolder).bind((Question) msg);
}
else if (msg.getType() == Message.SENT_MESSAGE)
((Sent_Message_Holder) viewHolder).bind(msg);
}
#Override
public int getItemCount() {
return messages.size();
}
}
class Received_Message_Holder extends RecyclerView.ViewHolder {
TextView messageText, timeText, nameText;
ImageView profileImage;
Received_Message_Holder(View itemView) {
super(itemView);
messageText = itemView.findViewById(R.id.text_message_body);
timeText = itemView.findViewById(R.id.text_message_time);
nameText = itemView.findViewById(R.id.text_message_name);
profileImage = itemView.findViewById(R.id.image_message_profile);
}
void bind(Message message) {
messageText.setText(message.getMessage());
timeText.setText(message.get_date());
nameText.setText(message.getSender().getNickname());
// Insert the profile image from the URL into the ImageView.
profileImage.setImageResource(R.drawable.male);
}
}
class Sent_Message_Holder extends RecyclerView.ViewHolder {
TextView name, text, time;
ImageView profile_image;
public Sent_Message_Holder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.text_message_name);
text = itemView.findViewById(R.id.text_message_body);
time = itemView.findViewById(R.id.text_message_time);
profile_image = itemView.findViewById(R.id.image_message_profile);
}
void bind(Message message) {
text.setText(message.getMessage());
time.setText(message.get_date());
name.setText(message.getSender().getNickname());
// Insert the profile image from the URL into the ImageView.
profile_image.setImageResource(R.drawable.male);
}
}
class Multiple_Choice_Holder extends RecyclerView.ViewHolder {
Collection_Picker picker;
Multiple_Choice_Holder(View itemView) {
super(itemView);
picker = itemView.findViewById(R.id.collection_picker);
}
void bind(Question question) {
List<Choice_Item> items = new ArrayList<>();
for (int i = 0; i < question.getOptions().size(); i++) {
items.add(new Choice_Item(String.valueOf(i), question.getOptions().get(i)));
}
if(question.getAnsPosition() != -1)
{
Log.wtf("TAg","redraw");
picker.draw_fixed(items.get(question.getAnsPosition()));
}else {
Log.wtf("TAg","drwing from zero");
picker.setItems(items);
picker.setListener(question.getListener());
}
}
}
And the Activity which uses this:
public class Chat_activity extends AppCompatActivity implements questionListener{
Vector<Message> queued_messages = new Vector<>();
List<Message> messages = new ArrayList<>() ;
RecyclerView recyclerView ;
MessageListAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_page_activity);
recyclerView = findViewById(R.id.reyclerview_message_list);
init_messages();
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(false);
adapter = new MessageListAdapter(messages);
recyclerView.setAdapter(adapter);
start_chat_show();
//edit text also add sent message to messages
}
int evaluate_message_size(Message message){
return message.getMessage().length()*50;
}
void start_chat_show(){
new async_task(evaluate_message_size(queued_messages.get(0))).execute();
}
#Override
public void onQuestionAnswered(int ansPosition) {
afterQuestion(ansPosition);
}
class async_task extends AsyncTask<Void,Void,Void> {
int time_interval = 200;
public async_task(int time_interval){
super();
this.time_interval = time_interval;
}
#Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(time_interval);
}catch (InterruptedException e){
Log.d("Tavak", "real errors!");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
next_message();
}
}
private void next_message(){
if(queued_messages.size()>0) {
messages.add(queued_messages.get(0));
queued_messages.remove(0);
Log.wtf("tag", String.valueOf(messages.size()));
adapter.notifyItemInserted(messages.size()-1);
if (messages.get(messages.size() - 1).getType() == Message.MULTIPLE_CHOICE) {
lastQuestionPosition = messages.size() - 1;
}
if (queued_messages.size() > 0 && messages.get(messages.size() - 1).getType() != Message.MULTIPLE_CHOICE && !messages.get(messages.size() - 1).isHas_input())
new async_task(evaluate_message_size(messages.get(messages.size() - 1))).execute();
// recyclerView.scrollToPosition(adapter.getItemCount());
}
}
public void afterQuestion(int ansPosition){
((Question)messages.get(lastQuestionPosition)).setAnsPosition(ansPosition);
((Question)messages.get(lastQuestionPosition)).actOnAnswer();
if(queued_messages.size()>0)
next_message();
}
private void questionChild(int position){
User user = new User();
user.setNickname("us");
Message msg4 = new Message();
msg4.setSender(user);
msg4.setMessage("what kind are you?");
msg4.setHas_input(true);
queued_messages.add(position+1,msg4);
Message msg5 = new Message();
msg5.setSender(user);
msg5.setMessage("whats up?");
msg5.setHas_input(true);
queued_messages.add(position+2,msg5);
Message msg5_5 = new Message();
msg5_5.setSender(user);
msg5_5.setMessage("repeat process?");
queued_messages.add(msg5_5);
Question msg6 = new Question();
msg6.setSender(user);
msg6.setQuestion("repeat process?");
Vector<String> options0 = new Vector<>();
options0.add("yes");
options0.add("no");
msg6.setOptions(options0);
msg6.setListener(this);
msg6.setItem_listener(new questionListener() {
#Override
public void onQuestionAnswered(int ansPosition) {
if(ansPosition == 0){
questionChild(-1);
}
}
});
queued_messages.add(position+3,msg6);
}
private void init_messages(){
final User user = new User();
user.setNickname("us");
Message msg = new Message();
msg.setSender(user);
msg.setMessage("hello");
queued_messages.add(msg);
Message msg2 = new Message();
msg2.setSender(user);
msg2.setMessage("welcome to your place");
queued_messages.add(msg2);
Message msg3 = new Message();
msg3.setSender(user);
msg3.setMessage("good luck");
queued_messages.add(msg3);
Message msg4 = new Message();
msg4.setSender(user);
msg4.setMessage("what kind is it?");
msg4.setHas_input(true);
queued_messages.add(msg4);
Message msg5 = new Message();
msg5.setSender(user);
msg5.setMessage("how old؟");
msg5.setHas_input(true);
queued_messages.add(msg5);
Message msg5_5 = new Message();
msg5_5.setSender(user);
msg5_5.setMessage("any other one?");
queued_messages.add(msg5_5);
Question msg6 = new Question();
msg6.setSender(user);
msg6.setQuestion("any other one?");
Vector<String> options0 = new Vector<>();
options0.add("yes");
options0.add("no");
msg6.setOptions(options0);
msg6.setListener(this);
msg6.setItem_listener(new questionListener() {
#Override
public void onQuestionAnswered(int ansPosition) {
if(ansPosition == 0){
questionChild(-1);
}
}
});
queued_messages.add(msg6);
Message msg6_5 = new Message();
msg6_5.setSender(user);
msg6_5.setMessage("your problem?");
queued_messages.add(msg6_5);
Question q = new Question();
q.setQuestion("your problem?");
Vector<String> options = new Vector<>();
options.add("Im feeling bad");
options.add("stuck in my room");
options.add("kidnapped");
options.add("none of above");
q.setOptions(options);
q.setListener(this);
q.setItem_listener(new questionListener() {
#Override
public void onQuestionAnswered(int ansPosition) {
if(ansPosition == 0){
next_message();
}
}
});
queued_messages.add(q);
Message msg9 = new Message();
msg9.setSender(user);
msg9.setMessage("Its natural");
queued_messages.add(msg9);
Message msg10 = new Message();
msg10.setSender(user);
msg10.setMessage("easilly solvabe.");
queued_messages.add(msg10);
Message msg11 = new Message();
msg11.setSender(user);
msg11.setMessage("join us and learn.");
queued_messages.add(msg11);
Message msg12 = new Message();
msg12.setSender(user);
msg12.setMessage("wanna join us؟");
queued_messages.add(msg12);
Question q2 = new Question();
q2.setQuestion("wanna join us?");
Vector<String> options1 = new Vector<>();
options1.add("yes");
options1.add("no");
q2.setOptions(options1);
q2.setListener(this);
q2.setItem_listener(new questionListener() {
#Override
public void onQuestionAnswered(int ansPosition) {
if(ansPosition == 0){
Toast.makeText(Chat_activity.this,"we;re set to go",Toast.LENGTH_SHORT).show();
Intent mintent = new Intent(Chat_activity.this,Khans_activity.class);
startActivity(mintent);
finish();
}
}
});
queued_messages.add(q2);
}
}
I wish that recyclerview works correctly(without any disappearing , repeated values or swaped items).
Please inform me if you need any further detail.
AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private String serialNumber;
private Integer totalPrice;
public AmountCartModel() {
this.testName = testName;
this.testPrice = testPrice;
this.serialNumber = serialNumber;
this.totalPrice = totalPrice;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPrice() {
return testPrice;
}
public void setTestPrice(String testPrice) {
this.testPrice = testPrice;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
AmountCartActivity.java
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.total_price)
TextView totalPriceDisplay;
SharePreferenceManager<LoginModel> sharePreferenceManager;
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
Bundle extras ;
String testName="";
String testPrice="";
String totalPrice= "";
int counting = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("test_name");
testPrice = extras.getString("test_price");
totalPrice = String.valueOf(extras.getInt("total_price"));
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
mydataList.add(mydata);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
}
}
AmountCartAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class));
finish();
}
}
HealthCartActivity
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imlogo;
private TextView Date;
private TextView Time;
private TextView Day;
private ImageView settingsButton;
#BindView(R.id.back_to_add_patient)
TextView backToDashboard;
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice = "";
int count = 0;
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> mydataList;
private RecyclerAdapter madapter;
private ArrayList<TestListModel> mydb;
private Button submitButton;
private TextView deviceModeName;
private TextView centerId;
SharePreferenceManager<LoginModel> sharePreferenceManager;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
imlogo=(ImageView) findViewById(R.id.action_bar_logo);
Day=(TextView) findViewById(R.id.day);
Date=(TextView) findViewById(R.id.date);
Time=(TextView)findViewById(R.id.time);
//backButton=(Button) findViewById(R.id.back_button);
centerId=(TextView)findViewById(R.id.center_id);
deviceModeName=(TextView)findViewById(R.id.device_mode_name);
settingsButton=(ImageView)findViewById(R.id.settings);
submitButton=(Button) findViewById(R.id.submit_button);
dayTimeDisplay();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(HealthServicesActivity.this, settingsButton);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.common_navigation_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id==R.id.home){
startActivity(new Intent(getApplicationContext(), DashBoardActivity.class));
finish();
}
if (id==R.id.my_profile){
startActivity(new Intent(getApplicationContext(), MyProfileActivity.class));
finish();
}
if (id==R.id.change_password){
startActivity(new Intent(getApplicationContext(), ChangePasswordActivity.class));
finish();
}
Toast.makeText(HealthServicesActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT
).show();
return true;
}
});
popup.show(); //showing popup menu
}
});
progressDialog = new ProgressDialog(HealthServicesActivity.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
//registerOnline();
initViews();
submitButton.setOnClickListener(this);
backToDashboard.setOnClickListener(this);
}
/*
* Action Bar DATE N TIME
* */
private void dayTimeDisplay(){
SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE");
java.util.Date d = new Date();
String dayOfTheWeek = sdf1.format(d);
Day.setText(dayOfTheWeek);
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
Date.setText(currentDateTimeString);
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
String time1 = sdf.format(dt);
Time.setText(time1);
}
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
AtomicInteger sharedOutput = new AtomicInteger(0);
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
//testListId = testListId+ "\n" + singleStudent.getTestlist_id().toString();
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
//count = singleStudent.setSerial_number("\n" +i);
//singleStudent.getSerial_number(count);
count ++;
/* count = sharedOutput.get() + 1;
System.out.println(count);
sharedOutput.incrementAndGet();*/
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serial_number", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/** show center Id in action bar
* */
#Override
protected void onResume() {
super.onResume();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
}
private void showcenterid(LoginModel userLoginData) {
centerId.setText(userLoginData.getResult().getGenCenterId());
centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
}
private void initViews() {
recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
// .baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mydataList = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(mydataList);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
I am trying to display serial number to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to get the serial number.
Well, you can work-around. And you won't have to keep serialNumber variable in model just to track it's position.
You can use position parameter variable of onBindViewHolder() for serial number and counting.
i.e.
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//here position is unique for every item in the list, so, you can use it as a serial number
// also, since it's starting from 0, you should add 1 with it, in case you wanna start from 1
// holder.textView2.setText(myDataList.get(position).getSerialNumber());
holder.textView2.setText("S.No. "+(position+1));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
holder.id.setText(String.valueOf(" "+(position+1)));
Use above method.
You have to add serialNumber to your AmountCartModel.This will fix your problem
Put an id in your AmountCartModel as below;
public class AmountCartModel {
private int serialNumber; // add this line
private String testName;
private String testPrice;
private Integer totalPrice;
public AmountCartModel() {
this.serialNumber= serialNumber; // add this line
this.testName = testName;
this.testPrice = testPrice;
this.totalPrice = totalPrice;
}
public int getSerialNumber (){
} // add this line
public void setSerialNumber(int serialNumber) {
}// add this line also
Then retrieve this serialNumber from each view.
Since you are sending the intent form onBackPressed(); attach the list as an extra to the intent as follows,
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class).putParcelableArrayList("the list", mDataList));
finish();
}
Please ensure the object (AmountCarModel) you are making a list from extends Parcelable, and catch it in the HealthServiceActivity in onResume()
Alternatively, and probably the best way, is to attach the serialNumber inside the HealthServiceActivity in the Retrofit onResponse() method as below;
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
if (data != null){
for (int i = 0; i<data.size(); i++) {
data.setSerialNumber(i);}}
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}
In AmountCartModel serialNumber is of String datatype
and while putting object you are setting
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
and you are storing it in ArrayList without for loop so every time only one object will get inclued in your arraylist
try this way
int count = 0;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
//AmountCartModel serialNumber = stList.get(i);
if (singleStudent.isSelected() == true) {
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
count++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serialNumber", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
I found the answer. I have done code for serial number like below. Here I am getting serial number in front of the elements. In this code I took one int variable and initialized with value 1. After that I call srNo variable in for loop then incremented at the end of the for loop.
int srNo = 1;
List < TestListModel > stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
testListId = testListId + "\n" + Integer.parseInt(String.valueOf(srNo));
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice + "\n" + singleStudent.getTest_price().toString();
srNo++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm currently having trouble restoring my fragment to it's previous state after clicking into a detail activity from my recyclerview adapter. The back button within the detail activity returns me to an empty fragment with no data.
Here's the detail activity class
**
* Provides UI for the Detail page with Collapsing Toolbar.
*/
public class DetailActivity extends AppCompatActivity implements View.OnClickListener {
public static final String EXTRA_POSITION = "position";
private Boolean isFabOpen = false;
private FloatingActionButton fab,fab1,fab2;
private Animation fab_open,fab_close,rotate_forward,rotate_backward;
private CollapsingToolbarLayout collapTool;
private LinearLayout linLayout;
private boolean isFavorited;
private boolean isIgnored;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
fab = (FloatingActionButton)findViewById(R.id.fab);
fab1 = (FloatingActionButton)findViewById(R.id.fab1);
fab2 = (FloatingActionButton)findViewById(R.id.fab2);
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_backward);
fab.setOnClickListener(this);
fab1.setOnClickListener(this);
fab2.setOnClickListener(this);
//Getting the details passed from the last activity to parse proper detail display
Intent intent = getIntent();
Bundle bd = intent.getExtras();
String titleText = (String) bd.get("titleText");
String descriptionText = (String) bd.get("description");
String locations = (String) bd.get("locations");
String assetTypes = (String) bd.get("assetTypes");
String propertyStatuses = (String) bd.get("propertyStatuses");
String buyerId = (String) bd.get("buyer_id") + "";
//Buyer ID testing if proper ID is passed through
//Toast.makeText(getApplicationContext(),buyerId,Toast.LENGTH_SHORT).show();
isFavorited = (Boolean) bd.get("favorited");
isIgnored = (Boolean) bd.get("ignored");
//If item was favorited from previous page, adjust accordingly
if(isFavorited) {
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
isFavorited = true;
isIgnored = false;
}
//If item was ignored from previous page, adjust accordingly
if(isIgnored) {
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
isIgnored = true;
isFavorited = false;
}
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
linLayout = (LinearLayout) findViewById(R.id.linLay);
collapTool = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
linLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
}
}
});
collapTool.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
}
}
});
locations = locations.replace("Locations | ", "");
assetTypes = assetTypes.replace("Asset Types | ", "");
propertyStatuses = propertyStatuses.replace("Property Statuses | ", "");
// Set Collapsing Toolbar layout to the screen
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// Set title of Detail page
// collapsingToolbar.setTitle(getString(R.string.item_title));
assert fab2 != null;
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isFavorited) {
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
//Snackbar.make(v, "Favorited...",Snackbar.LENGTH_LONG).show();
isFavorited = true;
isIgnored = false;
} else {
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
/*Snackbar.make(v, "Unfavorited...",
Snackbar.LENGTH_LONG).show();
*/
isFavorited = false;
}
}
});
assert fab1 != null;
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isIgnored) {
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
isIgnored = true;
isFavorited = false;
} else {
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
/*Snackbar.make(v, "Unfavorited...",
Snackbar.LENGTH_LONG).show();
*/
isIgnored = false;
}
}
});
int postion = getIntent().getIntExtra(EXTRA_POSITION, 0);
Resources resources = getResources();
String[] places = resources.getStringArray(R.array.city_array);
collapsingToolbar.setTitle(titleText);
String[] placeDetails = resources.getStringArray(R.array.city_array);
TextView placeDetail = (TextView) findViewById(R.id.place_detail);
placeDetail.setText(descriptionText);
String[] placeLocations = resources.getStringArray(R.array.city_array);
TextView placeLocation = (TextView) findViewById(R.id.place_location);
placeLocation.setText(locations);
TextView assetDetails = (TextView) findViewById(R.id.asset_details);
assetDetails.setText(assetTypes);
TextView propertyDetails = (TextView) findViewById(R.id.status_details);
propertyDetails.setText(propertyStatuses);
/*
TextView investmentDetails = (TextView) findViewById(R.id.investment_details);
investmentDetails.setText(investmentRangeMin);
*/
/*
TypedArray placePictures = resources.obtainTypedArray(R.array.city_array);
ImageView placePicutre = (ImageView) findViewById(R.id.image);
placePicutre.setImageDrawable(placePictures.getDrawable(postion % placePictures.length()));
placePictures.recycle();
*/
}
And here is my recyclerView adapter that has an onclicklistener for the item view which creates the detail activity.
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private Activity activity;
private LayoutInflater inflater;
private static List<BuyerProfile> profileItems;
private static boolean itemFavorited;
RVAdapter(List<BuyerProfile> profiles) {
this.profileItems = profiles;
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView description;
TextView locations;
TextView id;
TextView investmentRange;
TextView investmentRangeMax;
TextView assetTypes;
TextView propertyStatuses;
TextView profileId;
ImageView headerImage;
Button favoriteButton;
Button ignoreButton;
CardView cardView;
private ImageView spacer;
private boolean favorited = false;
private boolean ignored = false;
PersonViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.titleText);
description = (TextView) itemView.findViewById(R.id.descriptionText);
investmentRange = (TextView) itemView.findViewById(R.id.investment);
//investmentRangeMax = (TextView) itemView.findViewById(R.id.investmentRangeMax);
locations = (TextView) itemView.findViewById(R.id.locations);
id = (TextView) itemView.findViewById(R.id.profileNumber);
headerImage = (ImageView) itemView.findViewById(R.id.imgBillionaire);
assetTypes = (TextView) itemView.findViewById(R.id.assetTypes);
propertyStatuses = (TextView) itemView.findViewById(R.id.propertyStatuses);
favoriteButton = (Button) itemView.findViewById(R.id.action_button);
ignoreButton = (Button) itemView.findViewById(R.id.ignore_button);
cardView = (CardView) itemView.findViewById(R.id.cv);
profileId = (TextView) itemView.findViewById(R.id.buyer_id);
spacer = (ImageView) itemView.findViewById(R.id.spacerImage);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = getAdapterPosition();
Context context = v.getContext();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
intent.putExtra("titleText", name.getText());
intent.putExtra("description", description.getText());
intent.putExtra("locations", locations.getText());
intent.putExtra("assetTypes", assetTypes.getText());
intent.putExtra("propertyStatuses", propertyStatuses.getText());
intent.putExtra("favorited", favorited);
intent.putExtra("ignored", ignored);
HomeFragment homeReturn = new HomeFragment();
// intent.putExtra("buyer_id", profileId.getText());
//intent.putExtra("investmentRangeMin", investmentRangeMin.getText());
context.startActivity(intent);
}
});
/*
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!favorited) {
spacer.setVisibility(View.VISIBLE);
headerImage.setBackgroundColor(Color.parseColor("#7E57C2"));
favorited = true;
ignored = false;
} else {
spacer.setVisibility(View.INVISIBLE);
favorited = false;
headerImage.setBackgroundColor(Color.parseColor("#42A5F5"));
}
}
});
*/
ignoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!ignored) {
spacer.setVisibility(View.VISIBLE);
headerImage.setBackgroundColor(Color.parseColor("#EF5350"));
favorited = false;
ignored = true;
} else {
ignored = false;
spacer.setVisibility(View.INVISIBLE);
headerImage.setBackgroundColor(Color.parseColor("#133253"));
}
}
});
}
}
#Override
public int getItemCount() {
return profileItems.size();
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
final PersonViewHolder selectedCard = personViewHolder;
selectedCard.name.setText(profileItems.get(i).getBuyerProfTitle());
selectedCard.description.setText(profileItems.get(i).getDescription());
selectedCard.locations.setText("Locations | " + profileItems.get(i).parseLocations());
selectedCard.assetTypes.setText("Asset Types | " + profileItems.get(i).getAssetTypes());
selectedCard.propertyStatuses.setText("Property Statuses | " + profileItems.get(i).getPropertyStatuses());
selectedCard.investmentRange.setText("Investment Range | $125,000 - $250,000");
final int position = i;
personViewHolder.ignoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profileItems.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
}
});
selectedCard.favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!selectedCard.favorited) {
profileItems.get(position).favoriteItem();
selectedCard.spacer.setVisibility(View.VISIBLE);
selectedCard.spacer.setBackgroundColor(Color.parseColor("#FFF176"));
selectedCard.headerImage.setBackgroundColor(Color.parseColor("#7E57C2"));
selectedCard.favorited = true;
selectedCard.ignored = false;
} else {
profileItems.get(position).unfavoriteItem();
selectedCard.favorited = false;
selectedCard.headerImage.setBackgroundColor(Color.parseColor("#133253"));
}
}
});
//personViewHolder.profileId.setText(profileItems.get(i).getProfileId() + "");
//personViewHolder.investmentRangeMin.setText(profileItems.get(i).getInvestmentRangeMin());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public long getItemId(int position) {
return position;
}
}
And finally here is my main fragment which holds the recyclerview.
public class HomeFragment extends Fragment {
private CustomListAdapter listAdapter;
//private static final String profileUrl = "http://172.16.98.152:3000/apip/buyers/profiles";
private static final String matchesUrl = "http://172.16.98.152:3000/apip/sellers/profiles/1/matches";
private String matched = "http://172.16.98.152:3000/apip/sellers/profiles/";
private ProgressDialog pDialog;
private ListView listView;
private List<BuyerProfile> buyersProfiles = new ArrayList<BuyerProfile>();
private View root;
private TextView noItems;
private TextView search;
private TextView searchSecondLine;
private LinearLayoutManager llm;
private String profileUrlString;
private String KEY_RECYCLER_STATE = "recycleSave";
private Bundle viewState;
private Bundle arguments;
private RecyclerView rv;
private int mStackLevel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
noItems = (TextView) root.findViewById(R.id.empty_view);
search = (TextView) root.findViewById(R.id.search);
searchSecondLine = (TextView) root.findViewById(R.id.matchesSecondLine);
rv = (RecyclerView) root.findViewById(R.id.rv);
rv.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setItemAnimator(new DefaultItemAnimator());
final RVAdapter recyclerAdapter = new RVAdapter(buyersProfiles);
rv.setAdapter(recyclerAdapter);
rv.setHasFixedSize(true);
RequestQueue mRequestQueue;
arguments = getArguments();
if(savedInstanceState != null) {
matched = matched + savedInstanceState.getString("profileArgs") + "/matches";
} else {
if(arguments != null && arguments.containsKey("profileId")) {
matched = matched + arguments.getString("profileId") + "/matches";
search.setText("Search: " + arguments.getString("locations") + " " + arguments.getString("assetTypes"));
searchSecondLine.setVisibility(View.VISIBLE);
searchSecondLine.setText(arguments.getString("propertyStatuses"));
} else {
matched = "http://172.16.98.152:3000/apip/sellers/profiles/1/matches";
noItems.setVisibility(View.VISIBLE);
searchSecondLine.setVisibility(View.INVISIBLE);
rv.setVisibility(View.INVISIBLE);
search.setVisibility(View.INVISIBLE);
}
}
Cache cache = new DiskBasedCache(getActivity().getCacheDir(), 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
JsonArrayRequest profileRequest = new JsonArrayRequest(matched,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
BuyerProfile parsedProfile = new BuyerProfile();
parsedProfile.setBuyerProfTitle(obj.getString("title"));
parsedProfile.setDescription(obj.getString("description"));
parsedProfile.setLocations(obj.getString("location"));
parsedProfile.setAssetTypes(obj.getString("asset_type"));
//parsedProfile.setProfileId(obj.getString("id"));
parsedProfile.setPropertyStatuses(obj.getString("property_status"));
//parsedProfile.setProfileId(obj.getInt("buyer_profile_id"));
parsedProfile.unfavoriteItem();
buyersProfiles.add(parsedProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
recyclerAdapter.notifyDataSetChanged();
// notifying list adapter about data changes
// so that it renders the list view with updated data
//hidePDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(selectBuyerProfile.this,"Error",Toast.LENGTH_LONG).show();
}
});
mRequestQueue.add(profileRequest);
/*
if(buyersProfiles.isEmpty()) {
rv.setVisibility(View.GONE);
noItems.setVisibility(View.VISIBLE);
}
*/
return root;
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(arguments != null && arguments.containsKey("profileId")) {
outState.putString("profileArgs", arguments.getString("profileId"));
}
}
}
I'm not sure which of these classes I need to be restoring and how I can restore the previous details and images in HomeFragment after clicking back from the detail activity. I would be able to just describe a parent activity in my manifest but the main class holding everything is a fragment and android doesn't let you choose parent fragments! Any ideas or help would be appreciated.
Try to remove initialization of List from declaration.
private List buyersProfiles = new ArrayList();
And make initialization in onCreateView method if List is null.
I am getting image array in response,and show it in fullscreen and swipe it,but if my image array is null I need to disable click event and prevent it to go to next activity,I tried lot but do not know what is mistake in my code..follow this for my code..https://stackoverflow.com/questions/27458980/how-to-send-response-to-next-activity/27498613?noredirect=1#comment43428525_27498613
public class Profile extends Activity{
private ProgressDialog pDialog;
AQuery androidAQuery=new AQuery(this);
private static final String USER_NAME="name";
private static final String USER_AGE="age";
private static final String USER_LOCATION="location";
private static final String USER_MOTHER_TONGE="mother_tounge";
private static final String USER_OCCU="occupation";
private static final String USER_INCOM="income";
private static final String USER_HEIGHT="height";
private static final String USER_CAST="cast";
private static final String USER_MARRAGE="marital_status";
private static final String USER_RELIGION="religion";
private static final String USER_GOTRA="gotra";
private static final String USER_MANGLIK="manglik";
private static final String USER_RASHI="rashi";
private static final String USER_EDUCATION="education";
private static final String USER_EAT="eating";
private static final String USER_DRINK="drink";
private static final String USER_SMOKE="smoke";
private static final String USER_ABOUT="about_me";
private static final String USER_PIC="profile_pic";
private static final String USER_IMG="user_image";
private static String USER_URL="";
private ImageView btnedit;
private TextView uname;
private TextView fdetail;
private TextView sdetail;
private TextView tdetail;
private TextView ocdetail;
private TextView incomedetail;
private TextView uheight;
private TextView umrg;
private TextView ureligion;
private TextView ugotra;
private TextView umanglik;
private TextView urashi;
private TextView udegree;
private TextView ueat;
private TextView udrink;
private TextView usmoke;
private TextView uabout;
private ImageView ucover;
private TextView occu_second;
private TextView place_second;
String user_name;
String user_age;
String user_location;
String user_mothertong;
String user_occupation;
String user_income;
String user_height;
String user_cast;
String user_marg;
String user_religion;
String user_gotra;
String user_manglik;
String user_rashi;
String user_education;
String user_eat;
String user_drink;
String user_smoke;
String user_about;
String user_pro;
private TextView age_sceond;
private TextView ucast;
String marital;
String user_img;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_edit);
String matchId=this.getIntent().getStringExtra("id");
USER_URL=""+matchId;
//Toast.makeText(ProfilePage.this,"match id blank",Toast.LENGTH_LONG).show();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
JSONObject jsonObj = new JSONObject(jsonStr);
user_name = jsonObj.getString(USER_NAME);
user_age = jsonObj.getString(USER_AGE);
user_location = jsonObj.getString(USER_LOCATION);
user_mothertong = jsonObj.getString(USER_MOTHER_TONGE);
user_occupation = jsonObj.getString(USER_OCCU);
user_income = jsonObj.getString(USER_INCOM);
user_height = jsonObj.getString(USER_HEIGHT);
user_cast=jsonObj.getString(USER_CAST);
user_marg = jsonObj.getString(USER_MARRAGE);
user_religion = jsonObj.getString(USER_RELIGION);
user_gotra = jsonObj.getString(USER_GOTRA);
user_manglik = jsonObj.getString(USER_MANGLIK);
user_rashi = jsonObj.getString(USER_RASHI);
user_education = jsonObj.getString(USER_EDUCATION);
user_eat = jsonObj.getString(USER_EAT);
user_drink = jsonObj.getString(USER_DRINK);
user_smoke = jsonObj.getString(USER_SMOKE);
user_about = jsonObj.getString(USER_ABOUT);
user_pro = jsonObj.getString(USER_PIC);
user_img=jsonObj.getString(USER_IMG);
user_img = "";
JSONArray picarray = (JSONArray) jsonObj.get("user_image");
for(int i=0;i< picarray.length();i++)
{
user_img+= picarray.getString(i);
Log.d("mylog", "curent pro pic = " + user_img);
}
Log.d("mylog", "all images = " + user_img);
uname = (TextView)findViewById(R.id.namedetail);
fdetail = (TextView)findViewById(R.id.firstdetail);
sdetail = (TextView)findViewById(R.id.seconddetail);
tdetail = (TextView)findViewById(R.id.thirddetail);
ocdetail=(TextView)findViewById(R.id.txtoccupationdetail);
incomedetail = (TextView)findViewById(R.id.incomedetaile);
uheight = (TextView)findViewById(R.id.txtheightprofile);
ucast=(TextView)findViewById(R.id.usercast);
umrg = (TextView)findViewById(R.id.txtmrgprofile);
ureligion = (TextView)findViewById(R.id.prohindu);
ugotra = (TextView)findViewById(R.id.gothraa);
umanglik = (TextView)findViewById(R.id.usermanglik);
urashi = (TextView)findViewById(R.id.rashi);
udegree = (TextView)findViewById(R.id.userdegree);
ueat = (TextView)findViewById(R.id.txteatprofile);
udrink = (TextView)findViewById(R.id.txtdrinkprofile);
usmoke = (TextView)findViewById(R.id.txtsmokeprofile);
uabout = (TextView)findViewById(R.id.txtabouther);
ucover = (ImageView)findViewById(R.id.coverimage);
age_sceond=(TextView)findViewById(R.id.txtageprofile);
occu_second=(TextView)findViewById(R.id.txtworkingprofile);
place_second=(TextView)findViewById(R.id.txtplaceprofile);
if(user_name.equals(""))
{
uname.setText("Not willing to specify");
}
else
{
uname.setText(user_name);
}
if(user_age.equals(""))
{
fdetail.setText("Not willing to specify");
age_sceond.setText("Not willing to specify");
}
else
{
fdetail.setText(user_age+" years");
age_sceond.setText(user_age+" years");
}
if(user_location.equals(""))
{
sdetail.setText("Not willing to specify");
place_second.setText("Not willing to specify");
}
else
{
sdetail.setText(user_location);
place_second.setText(user_location);
}
if(user_mothertong.equals(""))
{
tdetail.setText("Not willing to specify");
}
else
{
tdetail.setText(user_mothertong);
}
if(user_occupation.equals(""))
{
ocdetail.setText("Not willing to specify");
occu_second.setText("Not willing to specify");
}
else
{
ocdetail.setText(user_occupation);
occu_second.setText(user_occupation);
}
if(user_income.equals(""))
{
incomedetail.setText("Not willing to specify");
}
else
{
incomedetail.setText(user_income);
}
if(user_height.equals(""))
{
uheight.setText("Not willing to specify");
}
else
{
uheight.setText(user_height);
}
if(user_cast.equals(""))
{
ucast.setText("Not willing to specify");
}
else
{
ucast.setText(user_cast);
}
if(user_marg.equals(""))
{
umrg.setText("Not willing to specify");
}
else
{
umrg.setText(user_marg);
}
if(user_religion.equals(""))
{
ureligion.setText("Not willing to specify");
}
else
{
ureligion.setText(user_religion);
}
if(user_gotra.equals(""))
{
ugotra.setText("Not willing to specify");
}
else
{
ugotra.setText(user_gotra);
}
if(user_manglik.equals(""))
{
umanglik.setText("Not willing to specify");
}
else
{
umanglik.setText(user_manglik);
}
if(user_rashi.equals(""))
{
urashi.setText("Not willing to specify");
}
else
{
urashi.setText(user_rashi);
}
if(user_education.equals(""))
{
udegree.setText("Not willing to specify");
}
else
{
udegree.setText(user_education);
}
if(user_eat.equals(""))
{
ueat.setText("Not willing to specify");
}
else
{
ueat.setText(user_eat);
udrink.setText(user_drink);
usmoke.setText(user_smoke);
}
if(user_about.equals(""))
{
uabout.setText("Not willing to specify");
}
else
{
uabout.setText(user_about);
}
androidAQuery.id(ucover).image(user_pro, true, true);
} catch (JSONException e) {
e.printStackTrace();
}
ucover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Fullimage.class);
i.putExtra("images", USER_IMG);
startActivity(i);
}
});
btnedit=(ImageView)findViewById(R.id.editprofilebutton);
btnedit.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View arg0)
{
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileEdit.this);
builder.setTitle(R.string.title_alertbox)
.setIcon(R.drawable.ic_launcher)
.setMessage(R.string.chek)
.setCancelable(true)
.setNegativeButton(R.string.okalert, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog welcomeAlert = builder.create();
welcomeAlert.show();
// Make the textview clickable. Must be called after show()
((TextView)welcomeAlert.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
/*// Creating alert Dialog with one Button
AlertDialog alertDialog = new AlertDialog.Builder(
ProfileEdit.this).create();
// Setting Dialog Title
alertDialog.setTitle("Edit Profile");
// Setting Dialog Message
alertDialog.setMessage("Please log on to gujjumatch.com desktop site to edit your profile " +
"and also set other details or call on 91 281 3054120");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_launcher);
// Setting OK Button
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Write your code here to execute after dialog
// closed
Toast.makeText(getApplicationContext(),
"Thank You", Toast.LENGTH_SHORT)
.show();
}
});
// Showing Alert Message
alertDialog.show();*/
}
});
}
fullimageview
public class FuLLimage extends Activity{
private String strtd;
String[] imgStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image_view);
strtd=this.getIntent().getStringExtra("images");
System.out.println("imagess..........." + strtd);
imgStr = strtd.split(",");
System.out.println("Image String Array : " + imgStr);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
}
public class ImageAdapter extends PagerAdapter {
Context context;
ImageAdapter(Context context)
{
this.context=context;
}
#Override
public int getCount() {
return imgStr.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageBitmap(BitmapFactory.decodeFile(imgStr[position]));
//imageView.setImageURI(Uri.parse(imgStr[position]));
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
You can set listener to null to disable the onclick event
ucover.setOnClickListener(null)
If you want to resume the click event simply call
ucover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Fullimage.class);
i.putExtra("images", USER_IMG);
startActivity(i);
}
});
Hops this help.
you can check the lenght of your arraylist and then according the that set a message to user
if(picarray.length()!=0)
{
ucover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Fullimage.class);
i.putExtra("images", USER_IMG);
startActivity(i);
}
});
}
else
{//show your message here
}
Check your array length and if it is non zero enable the onclick listner..
if(picarray.length != 0)
{
ucover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Fullimage.class);
i.putExtra("images", USER_IMG);
startActivity(i);
}
});
}