Back to project page survey_sdk_android.
The source code is released under:
Apache License
If you think the Android project survey_sdk_android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.survey.android.view.themed; //from w ww .j a v a 2 s . c o m import java.io.IOException; import java.text.DecimalFormat; import java.util.LinkedList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.survey.android.R; import com.survey.android.c2dm.GcmRegistrationService; import com.survey.android.model.ResponseModel; import com.survey.android.model.SurveyModel; import com.survey.android.services.GeoSurveyPollService; import com.survey.android.session.Configuration; import com.survey.android.util.FontUtil; import com.survey.android.util.FontUtil.Roboto; import com.survey.android.util.Toiler; import com.survey.android.util.Utility; import com.survey.android.view.LocalizedFragmentActivity; import com.survey.android.webclient.RestClient; public class SurveysActivity extends LocalizedFragmentActivity { private static final int TIME_DELAYED = 750; private static final String TAG = "SurveysActivity"; protected ImageView ivSettings; protected TextView tvSurveysAvailable; protected TextView tvUserName; protected TextView tvMoreSurveys; private ViewGroup mContainerMoreSurveys; private LinearLayout llCheckingForMoreSurveys; private LinearLayout llNoSurveysAvailable; private LinearLayout llSurveys; String surveyEmpty[] = {}; static List<SurveyModel> surveys; static ResponseModel response; private ProgressDialog pd; private String currentBalanceStored; private String careerEarningsStored; private String pendingRewardsStored; private int surveysCompletedStored; private int surveysAvailableStored; Integer numberAttempts; private AlertDialog alert; private Runnable alertRunnable; private Handler handler; private Context context = SurveysActivity.this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_surveys); if(Configuration.isGeoPushEnabled()) { if (!Toiler.isServiceRunning(this, GeoSurveyPollService.class.getName())) { startService(new Intent(this, GeoSurveyPollService.class)); } } handler = new Handler(); alertRunnable = null; initUI(); } @Override public void onResume() { Log.d(TAG,"onResume called"); super.onResume(); try { (new BackgroundDataTask()).execute(); (new LoadSurveysTask()).execute(); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { if (alert != null && alert.isShowing()) { alert.dismiss(); } try { if (alertRunnable != null) handler.removeCallbacks(alertRunnable); } catch (Exception e) { e.printStackTrace(); } try { if (pd != null) { pd.dismiss(); } } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStart(); } @Override protected void initUI() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); currentBalanceStored = prefs.getString(context.getString(R.string.current_balance_stored), "0"); careerEarningsStored = prefs.getString(context.getString(R.string.career_earnings_stored), "0"); pendingRewardsStored = prefs.getString(context.getString(R.string.pending_rewards_stored), "0"); surveysCompletedStored = prefs.getInt(context.getString(R.string.surveys_completed_stored), 0); surveysAvailableStored = prefs.getInt(context.getString(R.string.surveys_available_stored), 0); //FontUtil fu = new FontUtil(context); //fu.setRobotoFont(getWindow().getDecorView(), Roboto.NORMAL); llCheckingForMoreSurveys = (LinearLayout) findViewById(R.id.llCheckingForMoreSurveys); llNoSurveysAvailable = (LinearLayout) findViewById(R.id.llNoSurveysAvailable); llSurveys = (LinearLayout) findViewById(R.id.llSurveys); llCheckingForMoreSurveys.setVisibility(View.VISIBLE); llNoSurveysAvailable.setVisibility(View.GONE); llSurveys.setVisibility(View.GONE); tvMoreSurveys = (TextView) findViewById(R.id.tvMoreSurveys); tvMoreSurveys.setVisibility(View.GONE); tvUserName = (TextView) findViewById(R.id.tvUserName); tvSurveysAvailable = (TextView) findViewById(R.id.tvSurveysAvailable); tvSurveysAvailable.setText(String.format(getResources().getString(R.string.surveys_available), String.valueOf(surveysAvailableStored))); mContainerMoreSurveys = (ViewGroup) findViewById(R.id.containerMoreSurveys); if (Configuration.isShowLogoutButtonActive()) { ivSettings = (ImageView) findViewById(R.id.ivSettings); ivSettings.setVisibility(View.VISIBLE); ivSettings.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showPopup(v); } }); } } private void updateUI() { tvSurveysAvailable.setText(String.format(getResources().getString(R.string.surveys_available), String.valueOf(surveysAvailableStored))); } /** * Adds message item to list view */ private void addSurveyItem(final SurveyModel survey) { String rewards_s = getRewardsCents(survey.getReward_cents()); // Instantiate a new "row" view. final ViewGroup newView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.survey_row, mContainerMoreSurveys, false); ((TextView) newView.findViewById(R.id.tvSurveyTitle)).setText(Utility.RestrictLength(survey.getTitle().toUpperCase(), 30)); ((TextView) newView.findViewById(R.id.tvSurveyContent)).setText(Utility.RestrictLength(Html.fromHtml(survey.getShortDescription()).toString(), 120)); ((TextView) newView.findViewById(R.id.tvTime)).setText(String.format(getResources().getString(R.string.survey_time), survey.getSurvey_time())); if (Configuration.isShowPointsActive()) { if(survey.getReward_cents() > 0) { ((ImageView) newView.findViewById(R.id.ivMoney)).setVisibility(View.VISIBLE); ((TextView) newView.findViewById(R.id.tvMoney)).setVisibility(View.VISIBLE); ((TextView) newView.findViewById(R.id.tvMoney)).setText(String.format(getResources().getString(R.string.survey_reward), rewards_s)); } } // // if(survey.getReward_noncash() != "") { // ((ImageView) newView.findViewById(R.id.ivNonCash)).setVisibility(View.VISIBLE); // ((TextView) newView.findViewById(R.id.tvNonCash)).setVisibility(View.VISIBLE); // ((TextView) newView.findViewById(R.id.tvNonCash)).setText(survey.getReward_noncash()); // } newView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //String survey_id = survey.getId(); //startActivity(new Intent(context, NotificationActivity.class).putExtra("survey_id", survey_id)); (new ResponseIdTask()).execute(survey); } }); newView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: try { String survey_id = survey.getId(); RemoveSurveyFromUserList(survey_id); mContainerMoreSurveys.removeView(newView); } catch (Exception e) { e.printStackTrace(); } break; case DialogInterface.BUTTON_NEGATIVE: // No button clicked, do nothing break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(getString(R.string.remove_survey_from_list_confirm)) .setPositiveButton(getString(R.string.confirm_yes), dialogClickListener) .setNegativeButton(getString(R.string.confirm_no), dialogClickListener).show(); return false; } }); //FontUtil fu = new FontUtil(context); //fu.setRobotoFont(newView, Roboto.NORMAL); // Because mContainerNewSurveys has android:animateLayoutChanges set to true, // adding this view is automatically animated. mContainerMoreSurveys.addView(newView, 0); } /** * Removes survey item from list */ private void RemoveSurveyFromUserList(String survey_id) { Log.d(TAG, "Removing survey_id from user: " + survey_id); // call api to remove survey item from user list (new RemoveItemTask()).execute(survey_id); } private String getRewardsCents(int rewardCents) { return Integer.toString(rewardCents); } /** * Retrieves summary data and stores in shared preferences */ private class BackgroundDataTask extends AsyncTask<Void, Void, JSONObject> { @Override protected void onPreExecute() { } @Override protected JSONObject doInBackground(Void... urls) { JSONObject result = null; SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); String userToken = prefs.getString(context.getString(R.string.token), null); String userId; try { if (userToken != null) { JSONObject tempUserIdJSON = RestClient.getUserIdByToken(userToken); if (tempUserIdJSON != null && tempUserIdJSON.has("user_id")) { userId = tempUserIdJSON.getString("user_id"); result = RestClient.getEarnings(userToken, userId); } } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(JSONObject result) { if (result != null) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); try { DecimalFormat twoDForm = new DecimalFormat("####.##"); twoDForm.setMinimumFractionDigits(2); String tempCurrentBalance = "0.00"; String tempCareerEarning = "0.00"; String tempPendingRewards = "0.00"; int tempSurveysCompleted = 0; int tempSurveysAvailable = 0; if (result.has("current_balance")) { tempCurrentBalance = result .getString("current_balance"); } if (result.has("career_earnings")) { tempCareerEarning = result.getString("career_earnings"); } if (result.has("pending_rewards")) { tempPendingRewards = result .getString("pending_rewards"); } if (result.has("surveys_completed")) { tempSurveysCompleted = result .getInt("surveys_completed"); } if (result.has("surveys_available")) { tempSurveysAvailable = result .getInt("surveys_available"); } if (!(tempCurrentBalance.equals(currentBalanceStored) && tempCareerEarning.equals(careerEarningsStored) && tempPendingRewards.equals(pendingRewardsStored) && tempSurveysCompleted == surveysCompletedStored && tempSurveysAvailable == surveysAvailableStored)) { Editor edit = prefs.edit(); if (!tempCurrentBalance.equals(currentBalanceStored)) { currentBalanceStored = tempCurrentBalance; edit.putString(context.getString(R.string.current_balance_stored),currentBalanceStored); } if (!tempCareerEarning.equals(careerEarningsStored)) { careerEarningsStored = tempCareerEarning; edit.putString(context.getString(R.string.career_earnings_stored),careerEarningsStored); } if (!tempPendingRewards.equals(pendingRewardsStored)) { pendingRewardsStored = tempPendingRewards; edit.putString(context.getString(R.string.pending_rewards_stored),pendingRewardsStored); } if (tempSurveysCompleted != surveysCompletedStored) { surveysCompletedStored = tempSurveysCompleted; edit.putInt(context.getString(R.string.surveys_completed_stored),surveysCompletedStored); } edit.commit(); updateUI(); } } catch (Exception exc) { exc.printStackTrace(); } // Register for GCM if option enabled in SDK Configuration if(Configuration.isGCMEnabled()){ Log.d(TAG, "starting GcmRegistrationService"); startService(new Intent(context, GcmRegistrationService.class)); } } } } /** * Retrieves survey list and loads into list view for display */ private class LoadSurveysTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { } @Override protected Void doInBackground(Void... params) { surveys = null; try { surveys = SurveyModel.getSurveysOnly(context); } catch (Exception e) { Log.e(TAG, "Exception: " + e.toString()); } return null; } @Override protected void onPostExecute(Void result) { if (surveys == null) { alertRunnable = new Runnable() { public void run() { alert = new AlertDialog.Builder(context) .setMessage(getResources().getString(R.string.connection_error_press_ok)) .setPositiveButton(R.string.ok,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int whichButton) { (new LoadSurveysTask()).execute(); } }) .setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int whichButton) { finish(); } }).create(); alert.show(); } }; handler.postDelayed(alertRunnable, TIME_DELAYED); } else { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final List<SurveyModel> filtSurveys = new LinkedList<SurveyModel>(); for (SurveyModel survey : surveys) { if (survey.getQuestionCount() > 0) filtSurveys.add(survey); } if (filtSurveys.size() == 0) {//== String userName = prefs.getString(getString(R.string.username),"").trim(); tvUserName.setText(String.format(getResources().getString(R.string.hi_user), userName)); llCheckingForMoreSurveys.setVisibility(View.GONE); llNoSurveysAvailable.setVisibility(View.VISIBLE); } else { // start with 0 views in container // Moved here to remove all views when the remote data is loaded if (mContainerMoreSurveys.getChildCount() > 0) { mContainerMoreSurveys.removeAllViews(); } for (int i = surveys.size()-1; i >= 0; i--) { addSurveyItem(surveys.get(i)); } // update survey available count Editor edit = prefs.edit(); surveysAvailableStored = surveys.size(); edit.putInt(context.getString(R.string.surveys_available_stored), surveysAvailableStored); edit.commit(); updateUI(); llCheckingForMoreSurveys.setVisibility(View.GONE); llSurveys.setVisibility(View.VISIBLE); } } } } /** * Initializes/Creates survey response for the selected survey */ private class ResponseIdTask extends AsyncTask<Object, Void, String> { SurveyModel survey = null; @Override protected void onPreExecute() { DialogFragment newFragment = NotificationDialogFragment.newInstance( getString(R.string.starting), getString(R.string.please_wait), NotificationDialogFragment.DIALOG_LOADING); newFragment.setCancelable(false); newFragment.show(getSupportFragmentManager(), "dialog"); } @Override protected String doInBackground(Object... objSurvey) { survey = (SurveyModel) objSurvey[0]; String responseId = null; try { responseId = ResponseModel.remote(context, survey.getId()).getId(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return responseId; } @Override protected void onPostExecute(String responseId) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog"); if (prev != null) { ft.remove(prev); } ft.commit(); if (responseId != null) { startActivity(new Intent(context,QuestionsActivity.class) .putExtra("response_id", responseId) .putExtra("question_count", survey.getQuestionCount()) .putExtra("survey_title", survey.getTitle()) .putExtra("survey_id", survey.getId()) .putExtra("survey_reward_noncash",survey.getReward_noncash()) .putExtra("survey_reward_cents", getRewardsCents(survey.getReward_cents())) .putExtra("survey_reward", survey.getReward_cents())); } } } /** * Removes survey item */ private class RemoveItemTask extends AsyncTask<String, Void, Boolean> { @Override protected void onPreExecute() { } @Override protected Boolean doInBackground(String... surveyId) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); try { String userToken = prefs.getString(getString(R.string.token), ""); boolean deleted = RestClient.RemoveSurveyById(userToken, surveyId[0]); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean result) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // update surveys available count in shared preferences and display if (result) { if (surveysAvailableStored > 0) { surveysAvailableStored -= 1; Editor edit = prefs.edit(); edit.putInt(context.getString(R.string.surveys_available_stored), surveysAvailableStored); edit.commit(); updateUI(); } } } } @SuppressLint("ValidFragment") private static class NotificationDialogFragment extends DialogFragment{ public static final int DIALOG_NO_INTERNET_CONNECTION = 0; public static final int DIALOG_LOADING = 1; protected static final int DIALOG_START_SURVEY_LOG_IN = 2; public static NotificationDialogFragment newInstance(String message, int tag) { NotificationDialogFragment frag = new NotificationDialogFragment(); Bundle args = new Bundle(); args.putString("message", message); args.putInt("tag", tag); frag.setArguments(args); return frag; } public static NotificationDialogFragment newInstance(String title, String message, int tag) { NotificationDialogFragment frag = newInstance(message, tag); frag.getArguments().putString("title", title); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = null; Bundle args = getArguments(); String message = args.getString("message"); int tag = args.getInt("tag"); AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); switch (tag) { case DIALOG_NO_INTERNET_CONNECTION: builder .setMessage(message) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int id) { ((NotificationActivity)getActivity()).retrieveSurveyInfoFromServer(); return; } }) .setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int id) { getActivity().finish(); return; } }); dialog = builder.create(); break; case DIALOG_START_SURVEY_LOG_IN: builder .setTitle(args.getString("title")) .setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int id) { return; } }); dialog = builder.create(); break; case DIALOG_LOADING: dialog = new ProgressDialog(getActivity()); ((ProgressDialog) dialog).setMessage(message); ((ProgressDialog) dialog).setTitle(args.getString("title")); break; default: dialog = null; } return dialog; } } }