Android Open Source - survey_sdk_android Messages Activity






From Project

Back to project page survey_sdk_android.

License

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.

Java Source Code

package com.survey.android.view.themed;
// w ww.j  a va2 s. c  o  m
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;

import android.app.AlertDialog;
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.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.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.Toiler;
import com.survey.android.util.FontUtil.Roboto;
import com.survey.android.util.Utility;
import com.survey.android.view.LocalizedFragmentActivity;
import com.survey.android.webclient.RestClient;

public class MessagesActivity extends LocalizedFragmentActivity {
  private static final int TIME_DELAYED = 500;
  private static final String TAG = "MessagesActivity";
  
  protected ImageView ivSettings;  
  protected TextView tvMessagesAvailable;
  protected TextView tvUserName;
  protected TextView tvMoreMessages;
  private ViewGroup mContainerMoreMessages;
  private LinearLayout llCheckingForMoreMessages;
  private LinearLayout llNoMessagesAvailable;
  private LinearLayout llMessages;
  
  String surveyEmpty[] = {};
  static List<SurveyModel> messages;
  static ResponseModel response;
  
  private ProgressDialog pd;
  
  private int messagesCompletedStored;
  private int messagesAvailableStored;
  Integer numberAttempts;

  private AlertDialog alert;
  private Runnable alertRunnable;
  private Handler handler;

  private Context context = MessagesActivity.this;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_messages);
    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 LoadMessagesTask()).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);
    messagesCompletedStored = prefs.getInt(context.getString(R.string.messages_completed_stored), 0);
    messagesAvailableStored = prefs.getInt(context.getString(R.string.messages_available_stored), 0);
    
    //FontUtil fu = new FontUtil(context);
    //fu.setRobotoFont(getWindow().getDecorView(), Roboto.NORMAL);
        
    llCheckingForMoreMessages = (LinearLayout) findViewById(R.id.llCheckingForMoreMessages);
    llNoMessagesAvailable = (LinearLayout) findViewById(R.id.llNoMessagesAvailable);
    llMessages = (LinearLayout) findViewById(R.id.llMessages);
    
    llCheckingForMoreMessages.setVisibility(View.VISIBLE);
    llNoMessagesAvailable.setVisibility(View.GONE);
    llMessages.setVisibility(View.GONE);
    
    tvMoreMessages = (TextView) findViewById(R.id.tvMoreMessages);
    tvMoreMessages.setVisibility(View.GONE);
    tvUserName = (TextView) findViewById(R.id.tvUserName);
    tvMessagesAvailable = (TextView) findViewById(R.id.tvMessagesAvailable);
    tvMessagesAvailable.setText(String.format(getResources().getString(R.string.messages_available), String.valueOf(messagesAvailableStored)));
    
    mContainerMoreMessages = (ViewGroup) findViewById(R.id.containerMoreMessages);
    
    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() {
    tvMessagesAvailable.setText(String.format(getResources().getString(R.string.messages_available), String.valueOf(messagesAvailableStored)));
  }
  
  /**
   * Adds message item to list view
   */  
  private void addSurveyItem(final SurveyModel survey) {
    DecimalFormat df = new DecimalFormat("0.00");
    double rewards = (survey.getReward_cents()*1.0000)/100;
    String rewards_s = df.format(rewards).toString();
        
    // Instantiate a new "row" view.
    final ViewGroup newView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.message_row, mContainerMoreMessages, false);
    ((TextView) newView.findViewById(R.id.tvMessageTitle)).setText(Utility.RestrictLength(survey.getTitle().toUpperCase(), 30));
    ((TextView) newView.findViewById(R.id.tvMessageContent)).setText(Utility.RestrictLength(Html.fromHtml(survey.getShortDescription()).toString(), 120));
    ((TextView) newView.findViewById(R.id.tvTime)).setText(String.format(getResources().getString(R.string.message_time), survey.getSurvey_time()));

    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.message_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)
        .putExtra("messages_available_stored", messagesAvailableStored));
      }
    });
    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);
                  mContainerMoreMessages.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_message_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 mContainerMoreMessages has android:animateLayoutChanges set to true,
    // adding this view is automatically animated.
    mContainerMoreMessages.addView(newView, 0);
  }
  
  /**
   * Removes message 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);
    }
    
  /**
   * Retrieves message list and loads into list view for display
   */    
  private class LoadMessagesTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {  
    }

    @Override
    protected Void doInBackground(Void... params) {
      messages = null;
      try {
        messages = SurveyModel.getMessagesOnly(context);
      } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.toString());
      }
      return null;
    }

    @Override
    protected void onPostExecute(Void result) {
      if (messages == 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 LoadMessagesTask()).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 : messages) {
          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));
          llCheckingForMoreMessages.setVisibility(View.GONE);
          llNoMessagesAvailable.setVisibility(View.VISIBLE);
          llMessages.setVisibility(View.GONE);
          // start with 0 views in container
          // added here to validate when remove messages from list
          if (mContainerMoreMessages.getChildCount() > 0) {
            mContainerMoreMessages.removeAllViews();        
          }

        } else {
          // start with 0 views in container
          if (mContainerMoreMessages.getChildCount() > 0) {
            mContainerMoreMessages.removeAllViews();        
          }          
          for (int i = messages.size()-1; i >= 0; i--) {
            addSurveyItem(messages.get(i));
          }
          
          // update survey available count
          Editor edit = prefs.edit();  
          messagesAvailableStored = messages.size();
          edit.putInt(context.getString(R.string.messages_available_stored), messagesAvailableStored);
          edit.commit();
          updateUI();
          
          llCheckingForMoreMessages.setVisibility(View.GONE);
          llMessages.setVisibility(View.VISIBLE);
        }
      }
    }
  }
  
  /**
   * Removes message item
   */    
  private class RemoveItemTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected Boolean doInBackground(String... surveyId) {
      boolean deleted = false;
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);   
      try {
        String userToken = prefs.getString(getString(R.string.token), "");
        deleted = RestClient.RemoveSurveyById(userToken, surveyId[0]);
      } catch (Exception e) {
        e.printStackTrace();
      }
      return deleted;
    }

    @Override
    protected void onPostExecute(Boolean result) {
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
      // update messages available count in shared preferences and display
      if (result) {
        if (messagesAvailableStored > 0) {
          messagesAvailableStored -= 1;
          Editor edit = prefs.edit();
          edit.putInt(context.getString(R.string.messages_available_stored), messagesAvailableStored);
          edit.commit();
          updateUI();
        }
      }      
    }
  }    

}




Java Source Code List

android.UnusedStub.java
com.google.android.gms.BuildConfig.java
com.google.android.gms.BuildConfig.java
com.survey.android.UnusedStub.java
com.survey.android.c2dm.C2DMRegistrationReceiver.java
com.survey.android.c2dm.C2DMTokenRefresher.java
com.survey.android.c2dm.GcmBroadcastReceiver.java
com.survey.android.c2dm.GcmNotificationReceiver.java
com.survey.android.c2dm.GcmRegistrationService.java
com.survey.android.c2dm.RegService.java
com.survey.android.common.PlacesAutoCompleteAdapter.java
com.survey.android.common.Themes.java
com.survey.android.containers.AppContainer.java
com.survey.android.containers.PollContainer.java
com.survey.android.custom_widgets.FontTextView.java
com.survey.android.custom_widgets.PollRatingsScaleLabeled.java
com.survey.android.custom_widgets.PollRatings.java
com.survey.android.custom_widgets.PollSelectionTable.java
com.survey.android.db.SerializationHelper.java
com.survey.android.db.SerializationManager.java
com.survey.android.fragment.AudioRecorderFragment.java
com.survey.android.geofence.GeofenceRemover.java
com.survey.android.geofence.GeofenceRequester.java
com.survey.android.geofence.GeofenceUtils.java
com.survey.android.geofence.LocationServiceErrorMessages.java
com.survey.android.geofence.ReceiveTransitionsIntentService.java
com.survey.android.geofence.SimpleGeofenceStore.java
com.survey.android.geofence.SimpleGeofence.java
com.survey.android.model.AnswerModel.java
com.survey.android.model.CategoryModel.java
com.survey.android.model.CurrentSectionModel.java
com.survey.android.model.Prefs.java
com.survey.android.model.QuestionModel.java
com.survey.android.model.ResponseModel.java
com.survey.android.model.SurveyModel.java
com.survey.android.model.UserModel.java
com.survey.android.services.BackgroundUploader.java
com.survey.android.services.DataBroadcastReceiver.java
com.survey.android.services.DeviceStartUpReceiver.java
com.survey.android.services.GeoSurveyPollService.java
com.survey.android.services.LocationTesterService.java
com.survey.android.services.ReferrerCatcher.java
com.survey.android.session.Configuration.java
com.survey.android.session.Session.java
com.survey.android.util.Base64.java
com.survey.android.util.ConstantData.java
com.survey.android.util.FontUtil.java
com.survey.android.util.GeoPush.java
com.survey.android.util.GeoTriggerBroadcastReceiver.java
com.survey.android.util.GeoTrigger.java
com.survey.android.util.LocationLog.java
com.survey.android.util.Log.java
com.survey.android.util.ScalingUtilities.java
com.survey.android.util.StrToIntMap.java
com.survey.android.util.StrToStrMap.java
com.survey.android.util.Toiler.java
com.survey.android.util.Utility.java
com.survey.android.util.WhiteLabel.java
com.survey.android.view.Gallery.java
com.survey.android.view.LocalizedFragmentActivity.java
com.survey.android.view.Main.java
com.survey.android.view.ThemeCustomizer.java
com.survey.android.view.themed.MainThemed.java
com.survey.android.view.themed.MessagesActivity.java
com.survey.android.view.themed.NotificationActivity.java
com.survey.android.view.themed.QuestionsActivity.java
com.survey.android.view.themed.RewardsActivity.java
com.survey.android.view.themed.SurveysActivity.java
com.survey.android.webclient.HttpRequest.java
com.survey.android.webclient.HttpsClient.java
com.survey.android.webclient.RestClient.java
com.survey.android.webclient.SurveyHttpClient.java
com.survey.android.webclient.SurveyRequest.java
com.survey.android.webclient.SurveySSLSocketFactory.java
com.survey.android.webclient.SurveyX509TrustManager.java
com.survey.android.widget.Widget.java
com.survey.androiddemo.AppContainer.java
com.survey.androiddemo.LoginActivity.java
com.survey.androiddemo.MainActivity.java
com.survey.androiddemo.SDKConfigSettings.java