Custom View Async Task - android

ublic class SectionsList extends LinearLayout implements OnOffChangeListener,OnClickListener,MessageListener{
private Context mContext;
private Dialog dialog;
private List<TextView> tList = new ArrayList<TextView>();
private List<EditValueButton> editList = new ArrayList<EditValueButton>();
private List<OnOffButton> onOffList = new ArrayList<OnOffButton>();
private List<String> sectionNames = NewsReader.getInstance().getSectionNamesListWithFunStories();
private final int ChangeBannerDeliveryBetweenTimeDialog_ID = 1;
private final int ChangeBannerDeliveryBetweenDateTimeDialog_ID = 2;
private Handler mHandler;
private EditValueButton editButton;
private long startTime;
private View setView;
private OnOffButton Id;
private Boolean sectionOn = false;
private Boolean setOff;
private Boolean checkSection = false;
private String activeSection;
private OnOffButton onOff;
private boolean cancel;
private TextView sectionName;
private TableLayout table;
private Resources resources;
private int textNormalColor;
private HashMap<String, Time> getSectiontime;
private HashMap<String, Time> hm = new HashMap<String, Time>();
#Override
public boolean handleMessage(Message msg) {
boolean ret;
Bundle bundle = msg.getData();
switch ( msg.what)
{
case Constants.message_SetBannerTime:
startTime = bundle.getLong(Constants.KEY_ARG_1);
setDisplayDuringLabel(startTime, setView);
ret = true;
break;
case Constants.message_setOff:
cancel = bundle.getBoolean(Constants.KEY_ARG_1);
if(cancel){
setOff();
ret = true;
break;
}
default:
{
ret = false;
break;
}
}
return ret;
}
public SectionsList(Context context) {
super(context);
mContext = context;
init(context, null);
}
public SectionsList(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
//new CustomTask().execute();
Log.d("secnames", "section names" + sectionNames);
getSectiontime = PersistedScheduledBannerStore.getInstance().getScheduledBanners();
resources = context.getResources();
textNormalColor = resources.getColor(R.color.app_button_normal_text_color);
if(getSectiontime != null){hm = getSectiontime;}
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.sectiontable, this, true);
table = (TableLayout) findViewById(R.id.mainTable);
for(int i =0; i< sectionNames.size();i++){
TableRow tr = new TableRow(context);
View line = new View(context);
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
line.setBackgroundColor(textNormalColor);
line.setPadding(0, 10, 0, 10);
layoutInflater.inflate(R.layout.sectiontablerow, tr);
table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
table.addView(line);
setIds(tr);
setTagstoViews(i);
addViewstoList();
setListeners();
checkIfSectionIsOn(i);
tList.get(i).setText("sai ram");
}
}
private void loopThroughViews(Context context, LayoutInflater layoutInflater) {
}
private void checkIfSectionIsOn(int i) {
if(getSectiontime.containsKey(sectionNames.get(i))){
String key = sectionNames.get(i);
Time value = getSectiontime.get(key);
editList.get(i).setText(DateFormat.format("h:mm a", value).toString());
onOff.setOn(true);
}else{
editList.get(i).setText("-:-");
}
}
public void onOffChanged(OnOffButton button, boolean isOn) {
setView = button;
if(isOn){
sectionOn = true;
}
else if (!isOn){
sectionOn = false;
makeSectionActive(button);
hm.remove(activeSection);
getSectiontime.remove(activeSection);
}
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case ChangeBannerDeliveryBetweenTimeDialog_ID:
{
long curStartTime = 0;
dialog = new ChangeBannerTimeDialog(getContext(), curStartTime, mHandler,0);
break;
}
case ChangeBannerDeliveryBetweenDateTimeDialog_ID:
{
long curStartTime = 0;
dialog = new ChangeBannerdateTimeDialog(getContext(), curStartTime, mHandler, 0);
break;
}
default:
dialog = null;
}
return dialog;
}
private void setDisplayDuringLabel(long startTime, View v){
changeTimeText(v, DateFormat.format("h:mm a", startTime).toString());
Time time = new Time(startTime);
if(sectionOn){
hm.put(activeSection, time);
}
}
#Override
public void onClick(View v) {
setView = v;
if(v.getId() == R.id.sectionOnOff){
if(sectionOn){
TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
String secName = tt.getText().toString();
showDateTimeDialogIfHoroscopes(secName);
setOff = true;
Id = onOffList.get(Integer.parseInt(v.getTag().toString()));
Id.setOn(true);
makeSectionActive(v);
}
}
else if(v.getId() == R.id.editTime){
setView = v;
Id = onOffList.get(Integer.parseInt(v.getTag().toString()));
if(Id.isOn()){
TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
String secName = tt.getText().toString();
showDateTimeDialogIfHoroscopes(secName);
setOff = false;
Id.setOn(true);
makeSectionActive(v);
}
}
}
private void showDateTimeDialogIfHoroscopes(String secName) {
if(secName.equals("Horoscopes")){
onCreateDialog(ChangeBannerDeliveryBetweenDateTimeDialog_ID).show();
}else{
onCreateDialog(ChangeBannerDeliveryBetweenTimeDialog_ID).show();
}
}
private void setOff() {
if(setOff){
Id.setOn(false);
}
else if(!setOff){
Id.setOn(true);
}
}
private void setIds(TableRow tr){
onOff = (OnOffButton) tr.findViewById(R.id.sectionOnOff);
editButton = (EditValueButton) tr.findViewById(R.id.editTime);
sectionName = (TextView) tr.findViewById(R.id.sectionName);
}
private void setTagstoViews(int i){
onOff.setTag(""+i);
editButton.setTag(""+i);
}
private void setListeners(){
editButton.setOnClickListener(this);
onOff.setOnOffChangeListener(this);
onOff.setOnClickListener(this);
}
public HashMap<String, Time> getBannerSectionwithTime(){
return hm;
}
private void addViewstoList(){
onOffList.add(onOff);
editList.add(editButton);
tList.add(sectionName);
}
private void makeSectionActive(View v){
TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
activeSection = tt.getText().toString();
}
private void changeTimeText(View v, String text){
EditValueButton tt = editList.get(Integer.parseInt(v.getTag().toString()));
tt.setText(text);
}
public boolean checkSectionOn(){
return checkSection;
}
private class CustomTask extends AsyncTask<String, Void, Boolean>{
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=ProgressDialog.show(getContext(), "", "Loading...");
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected Boolean doInBackground(String... params) {
return null;
}
}
}
I want to use Async task to put all Ui in postexecute and loops in doinbackground?
In loop i have my table row which consumens 5secs to 8sec to load so can we somehow add the loop in do in background? Any help would be appreciated. Please provide code sample for better understanding

First define what is your time consuming task. If you want creation of your Table to be in asyncTask here is a hint how to do it. First you need to create entire Table off screen and then add it to your Layout
private TableLayout table;
private void init(){
new CustomTask().execute();
}
private class CustomTask extends AsyncTask<String, Void, Boolean>{
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=ProgressDialog.show(getContext(), "", "Loading...");
}
#Override
protected Boolean doInBackground(String... params) {
// Here is the part where you create your table and do extensive work
// For example
for(int i =0; i< sectionNames.size();i++){
TableRow tr = new TableRow(context);
View line = new View(context);
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
line.setBackgroundColor(textNormalColor);
line.setPadding(0, 10, 0, 10);
layoutInflater.inflate(R.layout.sectiontablerow, tr);
table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
table.addView(line);
setIds(tr);
setTagstoViews(i);
addViewstoList();
setListeners();
checkIfSectionIsOn(i);
tList.get(i).setText("sai ram");
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//And now add your tableLayout in your Layout
layout.addView(tableLayout);
// Adjust layout params per need
dialog.dismiss();
}
}
Adjust all of this according to your needs.
Hope this helps and enjoy your work.

Related

How to update the RecyclerView Items Using AsyncTask

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

RecyclerView filled with Objects from SharedPreferences is slow and laggy

I am building an app which has a RecyclerView which holds Objects that are retrieved from SharedPreferences.
Unfortunately the RecyclerView is lagging when it is binded.
This is my Adapter
public class ShiftAdapter extends RecyclerView.Adapter<ShiftAdapter.ViewHolder>{
private List<Shift> mDataSet;
private Context mContext;
private static final String TAG = "ShiftAdapter";
public int previousExpandedPosition = -1;
public int mExpandedPosition = -1;
private static SharedPreferences mPrefs;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Boolean isStart;
private Date shiftIn;
private Date shiftOut;
private Date mDate;
public EditText mshiftInText;
public EditText mshiftOutText;
public Date date;
public ShiftAdapter(Context context, List<Shift> list) {
mDataSet = list;
mContext = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mDate;
public TextView mTime;
public TextView mPay;
public RelativeLayout mRelativeLayout;
public LinearLayout mExepandableLayout;
public Date mshiftIn;
public Date mshiftOut;
public EditText mshiftInText;
public EditText mshiftOutText;
public Button mUpdateButton;
public Button mDeleteButton;
public ViewHolder(View v) {
super(v);
mDate = (TextView) v.findViewById(R.id.date_TV);
mTime = (TextView) v.findViewById(R.id.time_TV);
mPay = (TextView) v.findViewById(R.id.pay_TV);
mRelativeLayout = (RelativeLayout) v.findViewById(R.id.rel_layout);
mExepandableLayout = (LinearLayout) v.findViewById(R.id.expandableLayout);
mshiftInText = (EditText) v.findViewById(R.id.setShiftIn);
mshiftOutText = (EditText) v.findViewById(R.id.setShiftOut);
mUpdateButton = (Button) v.findViewById(R.id.updateButton);
mDeleteButton = (Button) v.findViewById(R.id.deleteButton);
}
}
#Override
public ShiftAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext)
.inflate(R.layout.shift, parent, false);
ViewHolder vh = new ViewHolder(itemView);
return vh;
}
//TODO:Bind all the view elements to Shift Properties
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
// Format double
String hours = new DecimalFormat("##.##").format(mDataSet.get(i).getHours());
String pay = new DecimalFormat("##.##").format(mDataSet.get(i).getPay());
//set the Text
holder.mTime.setText(hours);
holder.mDate.setText(mDataSet.get(i).dateToString());
holder.mPay.setText(pay);
Log.d(TAG, "onBindViewHolder: called");
// new AsyncTask<>().ex
//Expand mExapndableLayout
final int position = i;
final boolean isExpanded = position ==mExpandedPosition;
holder.mExepandableLayout.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
// //set shift Times
// shiftIn = mDataSet.get(position).getInDate();
// shiftOut = mDataSet.get(position).getInDate();
if (isExpanded)
previousExpandedPosition = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
//fill expandable layout
holder.mshiftInText.setText(mDataSet.get(position).fullTimeToString(0));
final EditText in = holder.mshiftInText;
final EditText out = holder.mshiftOutText;
//edit mShiftIn Text
holder.mshiftInText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =true;
timePickerDialog(in,out);
}
});
holder.mshiftOutText.setText(mDataSet.get(position).fullTimeToString(1));
//edit MshiftOut Text
holder.mshiftOutText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =false;
timePickerDialog(in,out);
}
});
//updateButton onClick
holder.mUpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
shiftIn = mDataSet.get(position).getInDate();
shiftOut = mDataSet.get(position).getOutDate();
if(Validate.getValidate().isDateValid(shiftIn,shiftOut)) {
SharedPrefs.getInstance(mContext).editShift(newShift(shiftIn, shiftOut),Integer.toString(position));
int length = SharedPrefs.getInstance(mContext).getLength() - 1;
if (SharedPrefs.getInstance(mContext).getShift(length) != null) {
Log.d(TAG, "Edit Shift onClick: Success");
SharedPrefs.getInstance(mContext).saveShiftList(SharedPrefs.getInstance(mContext).sortList(SharedPrefs.getInstance(mContext).getShiftList()));
ShiftsFragment.updateUI();
Toast.makeText(mContext, "success", Toast.LENGTH_SHORT).show();
}
} else {
mShiftOut.setBackgroundResource(R.drawable.red_border);
Toast.makeText(mContext, "error", Toast.LENGTH_SHORT).show(); }
} catch(Exception e){
Log.d(TAG, "onDateSelected: "+e.toString());
Toast.makeText(mContext,"update FAIL", Toast.LENGTH_SHORT).show();
}
// update the Shift
}
});
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
areYouSure(mExpandedPosition);
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public Date timePickerDialog(EditText in,EditText out) {
mshiftInText = in;
mshiftOutText = out;
new SingleDateAndTimePickerDialog.Builder(mContext)
.title(mContext.getResources().getString(R.string.choose_time))
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
#Override
public void onDisplayed(SingleDateAndTimePicker picker) {
if(!isStart) {
date = mDate;
}
}
}).defaultDate(returnDate(date))
.listener(new SingleDateAndTimePickerDialog.Listener() {
#Override
public void onDateSelected(Date date) {
mDate = date;
if (isStart) {
updateShiftIn(mDate);
mshiftInText.setText(dateToString(mDate));
} else {
updateShiftOut(mDate);
mshiftOutText.setText(dateToString(mDate));
}
}
}).display();
return mDate;
}
public String dateToString(Date date)
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String string = df.format(date);
return string;
}
private void updateShiftIn(Date date) {
shiftIn = date;
}
private void updateShiftOut(Date date) {
shiftOut = date;
}
private Date returnDate(Date date)
{
if(date!=null)
{
return date;
}
else return mDate;
}
private void areYouSure(int i)
{
final String position = Integer.toString(i);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Log.d(TAG, "onClick: isSure=true;");
SharedPrefs.getInstance(mContext).removeShift(position);
ShiftsFragment.updateUI();
case DialogInterface.BUTTON_NEGATIVE:
Log.d(TAG, "onClick: isSure= false");
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(mContext.getResources().getString(R.string.are_you_sure)).setPositiveButton(mContext.getResources().getString(R.string.confirm), dialogClickListener)
.setNegativeButton(mContext.getResources().getString(R.string.cancel), dialogClickListener).show();
}
private Shift newShift(Date start,Date stop)
{
int id = SharedPrefs.getInstance(mContext).getLength();
Shift shift = new Shift(dateToCalendar(start),dateToCalendar(stop),id);
return shift;
}
and this is the Fragment that has the RecyclerView
public class ShiftsFragment extends Fragment {
private Toolbar mToolbar;
private TimePicker timePicker1;
private List<Shift> shiftList = new ArrayList<>();
private RecyclerView recyclerView;
private RelativeLayout relativeLayout;
private RecyclerView.LayoutManager layoutManager;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Context mContext;
private ShiftAdapter mAdapter;
private MenuItem mAdd;
private Menu optionsMenu;
private LinearLayout mShiftAddLL;
private SharedPreferences mPrefs;
private static FragmentManager mFragmentManager;
private static final String TAG = "ShiftsFragment";
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG,"Clicked");
final View view = inflater.inflate(R.layout.shifts_layout,container,false);
mToolbar = view.findViewById(R.id.topbar);
mToolbar.inflateMenu(R.menu.toolbarmenu);
mShiftAddLL = view.findViewById(R.id.add_shiftLayout);
mAdd = mToolbar.getMenu().getItem(0);
timePicker1 = (TimePicker) view.findViewById(R.id.timePicker);
mFragmentManager = getFragmentManager();
//TODO:Add a summary bar on the bottom.
//get the context
mContext = getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.shift_list);
// Define a layout for RecyclerView
layoutManager = new GridLayoutManager(mContext,1);
recyclerView.setLayoutManager(layoutManager);
// Initialize a new Shift array
List<Shift> shiftList = initShifts();
Log.d(TAG,"shift array initiated");
// Initialize an array list from array
// Initialize a new instance of RecyclerView Adapter instance
mAdapter = new ShiftAdapter(mContext,shiftList);
// Set the adapter for RecyclerView
recyclerView.setAdapter(mAdapter);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
//Menu add button onClick
//Opens Add_Shift_Fragment
mAdd.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Fragment selectedFragment = new Add_Shift_Fragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return false;
}
});
return view;
}
//Initializes the Shift list from SharedPreferences and returns it.
private List<Shift> initShifts() {
return SharedPrefs.getInstance(mContext).getShiftList();
}
public static void updateUI()
{
Fragment selectedFragment = new ShiftsFragment();
mFragmentManager.beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
}
}
Everytime i launch the ShiftsFragment there are some frame skips, and the scrolling is choppy and laggy.
Maybe my SharedPreferences handling is what is slowing things down?
public class SharedPrefs {
private static SharedPrefs mSharedPrefs;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
protected Context mContext;
public static final String ID = "shiftList";
private SharedPrefs(Context context) {
mContext = context;
mPrefs = context.getSharedPreferences(ID, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
}
public static SharedPrefs getInstance(Context context) {
if (mSharedPrefs == null) {
mSharedPrefs = new SharedPrefs(context.getApplicationContext());
}
return mSharedPrefs;
}
public void saveShiftList(List<Shift> shiftList) {
Gson gson = new Gson();
String json = gson.toJson(shiftList);
mPrefsEditor.putString(ID, json);
mPrefsEditor.apply();
}
public void addShift (Shift shift)
{
List<Shift> shiftList= getShiftList();
shiftList.add(shift);
saveShiftList(shiftList);
}
//Replaced the shift#id with shift
public void editShift(Shift shift,String id)
{
removeShift(id);
addShift(shift);
}
public void removeShift(String id) {
List<Shift> shiftList = getShiftList();
int pos = Integer.parseInt(id);
shiftList.remove(pos);
saveShiftList(shiftList);
}
public void removeShift(int id) {
List<Shift> shiftList = getShiftList();
shiftList.remove(id);
saveShiftList(shiftList);
}
public Shift getShift(int id) {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
Shift shift = shiftList.get(id);
return shift;
}
public List<Shift> getShiftList() {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
if (shiftList!=null) {
return shiftList;
} else{
shiftList = new ArrayList<>();
return shiftList;
}
}
public List<Shift> sortList(List<Shift> shiftList)
{
Collections.sort(shiftList, new Comparator<Shift>() {
public int compare(Shift shift1, Shift shift2) {
if (shift1.getShiftStart() == null || shift2.getShiftStart() == null)
return 0;
return shift1.getShiftStart().compareTo(shift2.getShiftStart());
}
});
return shiftList;
}
public int getLength()
{
return getShiftList().size();
}
}
I have only found this problem with image loading, not just Strings from Object from SharedPrefs.

How to disable image view's click event?

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

Scrollview in Vertical View Pager

I am trying to create a vertical viewpager with scrollview in one of its fragment. The problem is when i am swiping up, i am not going into second fragment. I have uploaded my code in Github(https://github.com/RajuMandala/verticalviewpager). Please let me know, if i am doing anything wrong. Thanks for your time.
My FirstFragment.java code is below,
public class FirstFragment extends Fragment {
// Scrolling code
private LinearLayout verticalOuterLayout;
private ScrollView verticalScrollview;
private TextView verticalTextView;
private int verticalScrollMax;
private Timer scrollTimer = null;
private TimerTask clickSchedule;
private TimerTask scrollerSchedule;
private TimerTask faceAnimationSchedule;
private int scrollPos = 0;
private Boolean isFaceDown = true;
private Timer clickTimer = null;
private Timer faceTimer = null;
private Button clickedButton = null;
private String[] nameArray = {"Apple", "Banana", "Grapes", "Orange", "Strawberry","Apple", "Banana","Grapes"};
private String[] imageNameArray = {"apple", "banana", "grapes", "orange", "strawberry","apple", "banana","grapes"};
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag,container,false);
// Scrolling code
verticalScrollview = (ScrollView) v.findViewById(R.id.vertical_scrollview_id);
verticalOuterLayout = (LinearLayout) v.findViewById(R.id.vertical_outer_layout_id);
//addImagesToView();
addTextsToView();
ViewTreeObserver vto = verticalOuterLayout.getViewTreeObserver();
/*vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
verticalOuterLayout.getViewTreeObserver().re
getScrollMaxAmount();
startAutoScrolling();
}
});*/
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//
// mycode
//
if (Build.VERSION.SDK_INT<16) {
removeLayoutListenerPre16(verticalOuterLayout.getViewTreeObserver(),this);
} else {
removeLayoutListenerPost16(verticalOuterLayout.getViewTreeObserver(), this);
}
getScrollMaxAmount();
startAutoScrolling();
}
});
verticalOuterLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return true;
}
});
return v;
}
#SuppressWarnings("deprecation")
private void removeLayoutListenerPre16(ViewTreeObserver observer, ViewTreeObserver.OnGlobalLayoutListener listener){
observer.removeGlobalOnLayoutListener(listener);
}
#TargetApi(16)
private void removeLayoutListenerPost16(ViewTreeObserver observer, ViewTreeObserver.OnGlobalLayoutListener listener){
observer.removeOnGlobalLayoutListener(listener);
}
// Scrolling code
public void addTextsToView(){
for (int i=0;i<nameArray.length;i++){
final TextView textView = new TextView(getActivity());
textView.setText(nameArray[i]);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(256,256);
textView.setLayoutParams(params);
verticalOuterLayout.addView(textView);
}
}
public void getScrollMaxAmount(){
int actualWidth = (verticalOuterLayout.getMeasuredHeight()-(256*3));
verticalScrollMax = actualWidth;
}
public void startAutoScrolling(){
if (scrollTimer == null) {
scrollTimer = new Timer();
final Runnable Timer_Tick = new Runnable() {
public void run() {
moveScrollView();
}
};
if(scrollerSchedule != null){
scrollerSchedule.cancel();
scrollerSchedule = null;
}
scrollerSchedule = new TimerTask(){
#Override
public void run(){
getActivity().runOnUiThread(Timer_Tick);
}
};
scrollTimer.schedule(scrollerSchedule, 30, 30);
}
}
public void moveScrollView(){
scrollPos = (int) (verticalScrollview.getScrollY() + 1.0);
if(scrollPos >= verticalScrollMax){
scrollPos = 0;
}
verticalScrollview.scrollTo(0,scrollPos);
}
public void onDestroy(){
clearTimerTaks(clickSchedule);
clearTimerTaks(scrollerSchedule);
clearTimerTaks(faceAnimationSchedule);
clearTimers(scrollTimer);
clearTimers(clickTimer);
clearTimers(faceTimer);
clickSchedule = null;
scrollerSchedule = null;
faceAnimationSchedule = null;
scrollTimer = null;
clickTimer = null;
faceTimer = null;
super.onDestroy();
}
private void clearTimers(Timer timer){
if(timer != null) {
timer.cancel();
timer = null;
}
}
private void clearTimerTaks(TimerTask timerTask){
if(timerTask != null) {
timerTask.cancel();
timerTask = null;
}
}
}
Please see the screenshot of first fragment below,

How To Get Dynamically Created Imageview or textview clicked id or position in android?

i want to create dynamic imageview and button which in scrollview so i want to get the id for that clicked item which is created dynamically how can i get this here is my code
public class TestActivity extends Activity implements OnClickListener
{
private static final String TAG_DATA="data";
private static final String TAG_ADVERTISE="advertisments";
private static final String TAG_ADVERTISEID="advt_id";
String advertiseid;
private static final String TAG_SHOWTEXT="showtext";
String showtext;
private static final String TAG_PRODUCTINFO="product_info";
String productinfo;
private static final String TAG_THUMBIMAGE="thumbsrc";
String thumbimage;
private static final String TAG_DISTANCE="distance";
String distance;
private static final String TAG_STIPCIATED="stipciated";
String stipciated;
ArrayList<HashMap<String, String>> listadvertise = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String, String>> listadvertise1 = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String, String>> listadvertise2 = new ArrayList<HashMap<String,String>>();
// Webservice parameter for home advertise
String url;
String fbid;
String latitude;
String longitude;
String passdistance;
String offset;
// Webservice parameter for stipciated advertise
String userid;
String stipciate;
int screenheight;
int screenwidth;
AlertDialog alertDialog;
private ProgressDialog progressDialog;
ImageView imagemenu;
ScrollView scrollView3;
ImageView im;
LinearLayout homelistlayout1;
LinearLayout homelistlayout2;
public static final int img=50000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);
alertDialog = new AlertDialog.Builder(this).create();
DisplayMetrics screensize= new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(screensize);
screenheight=screensize.heightPixels;
screenwidth=screensize.widthPixels;
Log.e("Screen Height","---->"+screenheight);
Log.e("Screen Width ","---->"+screenwidth);
RelativeLayout headerlLayout = (RelativeLayout)findViewById(R.id.headerlayout);
headerlLayout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,((screenwidth*8)/100)+10));
if(CheckConnection.getInstance(this).isOnline(this))
{
// new HomeAsyncTask().execute("");
}
else
{
alert();
}
imagemenu=(ImageView)findViewById(R.id.imagemenu);
imagemenu.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(TestActivity.this,HorizontalActivity.class);
startActivity(i);
}
});
scrollView3=(ScrollView)findViewById(R.id.scrollview3);
scrollView3.post(new Runnable() {
public void run()
{
scrollView3.scrollTo(0, 200);
}
});
homelistlayout1=(LinearLayout)findViewById(R.id.homelistlayout1);
homelistlayout1.setPadding(0, 100, 0, 0);
homelistlayout2=(LinearLayout)findViewById(R.id.homelistlayout2);
for(int i=0;i<12;i++)
{
im= new ImageView(TestActivity.this);
im.setLayoutParams(new LinearLayout.LayoutParams(200, 200));
if(i%2==0)
{
im.setImageResource(R.drawable.adv);
im.setId(i);
homelistlayout1=(LinearLayout)findViewById(R.id.homelistlayout1);
homelistlayout1.addView(im);
}
else
{
im.setImageResource(R.drawable.adv2);
im.setId(i);
homelistlayout2=(LinearLayout)findViewById(R.id.homelistlayout2);
homelistlayout2.addView(im);
}
}
im.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ImageView iv=(ImageView) v;
Log.e("sfas","-->"+iv.getId());
}
});
}
}
public void onClick(View v) {
Log.e("Clicked","----->"+v.getId());
switch (v.getId())
{
case img:
Log.e("Clicked","----->"+v.getId());
break;
default:
break;
}
}
}
Just required changes on your code,
You have to add im.setOnClickListener(this); in for loop of ImageView.
Remove below method
im.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ImageView iv=(ImageView) v;
Log.e("sfas","-->"+iv.getId());
}
});
Override onClick() As you have already implement onClickcListener in your Activity.
Look at below code, (And match with your code to know actual problem)
public class TestActivity extends Activity implements OnClickListener
{
private static final String TAG_DATA="data";
private static final String TAG_ADVERTISE="advertisments";
private static final String TAG_ADVERTISEID="advt_id";
String advertiseid;
private static final String TAG_SHOWTEXT="showtext";
String showtext;
private static final String TAG_PRODUCTINFO="product_info";
String productinfo;
private static final String TAG_THUMBIMAGE="thumbsrc";
String thumbimage;
private static final String TAG_DISTANCE="distance";
String distance;
private static final String TAG_STIPCIATED="stipciated";
String stipciated;
ArrayList<HashMap<String, String>> listadvertise = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String, String>> listadvertise1 = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String, String>> listadvertise2 = new ArrayList<HashMap<String,String>>();
// Webservice parameter for home advertise
String url;
String fbid;
String latitude;
String longitude;
String passdistance;
String offset;
// Webservice parameter for stipciated advertise
String userid;
String stipciate;
int screenheight;
int screenwidth;
AlertDialog alertDialog;
private ProgressDialog progressDialog;
ImageView imagemenu;
ScrollView scrollView3;
private ListView listViewLeft;
private ListView listViewRight;
int[] leftViewsHeights;
int[] rightViewsHeights;
ImageView im;
LinearLayout homelistlayout1;
LinearLayout homelistlayout2;
public static final int img=50000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);
alertDialog = new AlertDialog.Builder(this).create();
DisplayMetrics screensize= new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(screensize);
screenheight=screensize.heightPixels;
screenwidth=screensize.widthPixels;
Log.e("Screen Height","---->"+screenheight);
Log.e("Screen Width ","---->"+screenwidth);
RelativeLayout headerlLayout = (RelativeLayout)findViewById(R.id.headerlayout);
headerlLayout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,((screenwidth*8)/100)+10));
if(CheckConnection.getInstance(this).isOnline(this))
{
// new HomeAsyncTask().execute("");
}
else
{
alert();
}
imagemenu=(ImageView)findViewById(R.id.imagemenu);
imagemenu.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(TestActivity.this,HorizontalActivity.class);
startActivity(i);
}
});
scrollView3=(ScrollView)findViewById(R.id.scrollview3);
scrollView3.post(new Runnable() {
public void run()
{
scrollView3.scrollTo(0, 200);
}
});
homelistlayout1=(LinearLayout)findViewById(R.id.homelistlayout1);
homelistlayout1.setPadding(0, 100, 0, 0);
homelistlayout2=(LinearLayout)findViewById(R.id.homelistlayout2);
for(int i=0;i<12;i++)
{
im= new ImageView(TestActivity.this);
im.setLayoutParams(new LinearLayout.LayoutParams(200, 200));
im.setOnClickListener(this);
if(i%2==0)
{
im.setImageResource(R.drawable.adv);
im.setId(i);
homelistlayout1=(LinearLayout)findViewById(R.id.homelistlayout1);
homelistlayout1.addView(im);
}
else
{
im.setImageResource(R.drawable.adv2);
im.setId(i);
homelistlayout2=(LinearLayout)findViewById(R.id.homelistlayout2);
homelistlayout2.addView(im);
}
}
}
}
#Override
public void onClick(View v) {
Log.e("Clicked","----->"+v.getId());
switch (v.getId())
{
case 1:
Log.e("Clicked","----->"+v.getId());
break;
case 2:
break;
.
.
.
default:
break;
}
}
You can setId() when you create the view and then that's his ID.
http://developer.android.com/reference/android/view/View.html#setId(int)
You are setting the ID's for the ImageView with im.setId(i);. So the ID's would be the value of i. You can keep track of this somewhere.
Also, please post only the relevant pieces of the code and not the whole class

Categories

Resources