Android gestionar la clase constante -- java campo con android camp codereview Relacionados El problema

Android manage constant class


1
vote

problema

Español

He creado una clase constante, incluya mi constante de URL, My User Web Llamadas ... etc

Puse mi clase constante en el paquete utils

Aquí están mis preguntas, ¿es bueno insertar la clase constante en el paquete UTILS?

Segunda pregunta, ¿debería separar cada elemento crear un archivo constante para URL, usuario ... etc

  // url constants     /////////////////////////////////////////////////////////////////////////////////////     public static String BASE_URL = "mybaseurl";      public static final String LOGIN_URL           = "login.php";     public static final String FORGETPASS_URL      = "restpassword.php";     public static final String SINGUP_URL          = "signup.php";     public static final String ALLDIEASES_URL      = "alldisease.php";     public static final String QUESTIONS_URL       = "questions";     public static final String EDITPROF_URL        = "editprofile";     public static final String PROF_URL            = "profile";       public static final String APPLICATION_JSON ="application/json";     public static final String CONTENT_TYPE ="Content-Type";        // login activity constants     ////////////////////////////////////////////////////////////////////////////////////     public static final String IS_LOGGEDIN       = "isloggedin";     public static final String TAG_username      = "user_name";     public static final String TAG_useremail     = "user_mail";     public static final String TAG_userpassword  = "user_password";     public static final String TAG_REGID         = "regestration_id";     public static final String REMEMBER_ME       = "remember";      ////////////////////////////////////////////////////////////////////////////////////      public static final String TRUE          = "true";     public static final String FALSE         = "false";     public static final String RESULT        = "result";     public static final String RESPONSE      = "response";     public static final String TAG_USER      = "user";     public static final String TAG_SUCCESS   = "success";      ////////////////////////////////////////////////////////////////////////////////////      public static final String TAG_postImageiD                   = "imagepath";     public static final String TAG_postid                        = "post";     public static final String TAG_age                           = "age";     public static final String GeneralURL_TWO                    = "http://www.la3nyk.com/actions.php?Act=profilephoto&";     public static final String SharedPreferenceDataStoreKey      = "keyprefs";     public static final String TAG_user_photo                    = "user_photo";     public static final String Tag_DesaesID                      = "disease";     public static final String Tag_UPLOADURL                     = "http://la3nyk.com/servies/profilephoto.php/";     public static boolean REFRESH                                = false;       // user parser data      public static final String USER_ID         = "user_id";     public static final String USER_EMAIL      = "user_mail";     public static final String USER_AGE        = "user_age";     public static final String USER_NAME       = "user_name";     public static final String USER_PASSWORD   = "user_password";     public static final String USER_PHOTO      = "user_photo";     public static final String USER_POSTS      = "posts";     public static final String MESSAGE         = "message";     public static final String DATA            = "data";       // Diseases parser data     public static final String DISEASE_ID          = "disease_id";     public static final String DISEASE_NAME        = "disease_name";     public static final String DISEASE_DES         = "description";     public static final String DISEASE_REASONS     = "reasons";     public static final String DISEASE_SYSMPTOMS   = "symptoms";     public static final String DISEASE_DIAGNOSIS   = "diagnosis";     public static final String DISEASE_TRATMENT    = "tratment";     public static final String DISEASE_ADVICE      = "advice";     public static final String DISEASE_VIDEO       = "disease_vedio";     public static final String DISEASE_PHOTO       = "disease_photo";     public static final String DISEASE_REF         = "refrancesrefrances";     public static final String DISEASE_LINKS       = "links";      // user parser data     public static final String ALERT             = "alert";     public static final String DONTSHOWAGAIN     = "dontshowagain";       // question parser data     public static final String QUESTION_ID     = "quest_id";     public static final String QUESTION        = "quest";     public static final String CHOOSE_1        = "chose1";     public static final String CHOOSE_2        = "chose2";     public static final String CHOOSE_3        = "chose3";     public static final String CHOOSE_4        = "chose4";     public static final String G_ID            = "G_id";       // checks constants     public static final String EYE_DISTANCE          = "eye_distance";     public static final String COVER_EYE             = "cover_eye";     public static final String ASTIGMATISM           = "astigmatism";     public static final String RED                   = "red";     public static final String CENTRAL_VISION        = "central_vision";     public static final String VISION_ACUITY         = "vision_acuity";     public static final String CONTRAST_SENSITIVITY  = "contrast_sensitivity";     public static final String COLORBLIND            = "blind";       // checks postions constants      public static final int EYE_DISTANCE_INT         = 0;     public static final int COVER_EYE_INT            = 1;     public static final int ASTIGMATISM_INT          = 2;     public static final int RED_INT                  = 3;     public static final int CENTRAL_INT              = 4;     public static final int VISION_ACUITY_INT        = 5;     public static final int CONTRAST_SENSITIVITY_INT = 6;     public static final int COLOR_BLIND_INT          = 7;       // questions      public static final String QUESTION_ONE          = "q1";     public static final String QUESTION_TWO          = "q2";     public static final String QUESTION_THREE        = "q3";     public static final String QUESTION_FOUR         = "q4";     public static final String QUESTION_FIVE         = "q5";     public static final String QUESTION_SIX          = "q6";     public static final String QUESTION_SEVEN        = "q7";     public static final String QUESTION_EIGHT        = "q8";     public static final String QUESTION_NINE         = "q9";     public static final String QUESTION_TEN          = "q10";     public static final String QUESTION_ELEVEN       = "q11";     public static final String QUESTION_TWELVE       = "q12";     public static final String QUESTION_THIRTEEN     = "q13";       public static final String QUESTION_SIZE            = "question_size";     public static final String CURRENT_QUESTION_TAG     = "current_question";     public static final String CURRENT_QUESTION_POS     = "current_question_pos";     public static final String CURRENT_QUESTION_SCORE   = "test_res_score";      public static final String PASSED_BOOL_STATE        = "passed_result_state";     public static final String PASSED_MSG_STATE         = "passed_message_state";     public static final String PASSED_SCORE             = "passed_score";      public static final String PASSED_DISEASES          = "mard";  }   
Original en ingles

I create constant class , include my url constant , my user web calls .... etc

I put my constant class in Utils package

here is my questions , is it good to inset constant class in Utils package ?

second question , should I separate each element create constant file for url , user ... etc

// url constants     /////////////////////////////////////////////////////////////////////////////////////     public static String BASE_URL = "mybaseurl";      public static final String LOGIN_URL           = "login.php";     public static final String FORGETPASS_URL      = "restpassword.php";     public static final String SINGUP_URL          = "signup.php";     public static final String ALLDIEASES_URL      = "alldisease.php";     public static final String QUESTIONS_URL       = "questions";     public static final String EDITPROF_URL        = "editprofile";     public static final String PROF_URL            = "profile";       public static final String APPLICATION_JSON ="application/json";     public static final String CONTENT_TYPE ="Content-Type";        // login activity constants     ////////////////////////////////////////////////////////////////////////////////////     public static final String IS_LOGGEDIN       = "isloggedin";     public static final String TAG_username      = "user_name";     public static final String TAG_useremail     = "user_mail";     public static final String TAG_userpassword  = "user_password";     public static final String TAG_REGID         = "regestration_id";     public static final String REMEMBER_ME       = "remember";      ////////////////////////////////////////////////////////////////////////////////////      public static final String TRUE          = "true";     public static final String FALSE         = "false";     public static final String RESULT        = "result";     public static final String RESPONSE      = "response";     public static final String TAG_USER      = "user";     public static final String TAG_SUCCESS   = "success";      ////////////////////////////////////////////////////////////////////////////////////      public static final String TAG_postImageiD                   = "imagepath";     public static final String TAG_postid                        = "post";     public static final String TAG_age                           = "age";     public static final String GeneralURL_TWO                    = "http://www.la3nyk.com/actions.php?Act=profilephoto&";     public static final String SharedPreferenceDataStoreKey      = "keyprefs";     public static final String TAG_user_photo                    = "user_photo";     public static final String Tag_DesaesID                      = "disease";     public static final String Tag_UPLOADURL                     = "http://la3nyk.com/servies/profilephoto.php/";     public static boolean REFRESH                                = false;       // user parser data      public static final String USER_ID         = "user_id";     public static final String USER_EMAIL      = "user_mail";     public static final String USER_AGE        = "user_age";     public static final String USER_NAME       = "user_name";     public static final String USER_PASSWORD   = "user_password";     public static final String USER_PHOTO      = "user_photo";     public static final String USER_POSTS      = "posts";     public static final String MESSAGE         = "message";     public static final String DATA            = "data";       // Diseases parser data     public static final String DISEASE_ID          = "disease_id";     public static final String DISEASE_NAME        = "disease_name";     public static final String DISEASE_DES         = "description";     public static final String DISEASE_REASONS     = "reasons";     public static final String DISEASE_SYSMPTOMS   = "symptoms";     public static final String DISEASE_DIAGNOSIS   = "diagnosis";     public static final String DISEASE_TRATMENT    = "tratment";     public static final String DISEASE_ADVICE      = "advice";     public static final String DISEASE_VIDEO       = "disease_vedio";     public static final String DISEASE_PHOTO       = "disease_photo";     public static final String DISEASE_REF         = "refrancesrefrances";     public static final String DISEASE_LINKS       = "links";      // user parser data     public static final String ALERT             = "alert";     public static final String DONTSHOWAGAIN     = "dontshowagain";       // question parser data     public static final String QUESTION_ID     = "quest_id";     public static final String QUESTION        = "quest";     public static final String CHOOSE_1        = "chose1";     public static final String CHOOSE_2        = "chose2";     public static final String CHOOSE_3        = "chose3";     public static final String CHOOSE_4        = "chose4";     public static final String G_ID            = "G_id";       // checks constants     public static final String EYE_DISTANCE          = "eye_distance";     public static final String COVER_EYE             = "cover_eye";     public static final String ASTIGMATISM           = "astigmatism";     public static final String RED                   = "red";     public static final String CENTRAL_VISION        = "central_vision";     public static final String VISION_ACUITY         = "vision_acuity";     public static final String CONTRAST_SENSITIVITY  = "contrast_sensitivity";     public static final String COLORBLIND            = "blind";       // checks postions constants      public static final int EYE_DISTANCE_INT         = 0;     public static final int COVER_EYE_INT            = 1;     public static final int ASTIGMATISM_INT          = 2;     public static final int RED_INT                  = 3;     public static final int CENTRAL_INT              = 4;     public static final int VISION_ACUITY_INT        = 5;     public static final int CONTRAST_SENSITIVITY_INT = 6;     public static final int COLOR_BLIND_INT          = 7;       // questions      public static final String QUESTION_ONE          = "q1";     public static final String QUESTION_TWO          = "q2";     public static final String QUESTION_THREE        = "q3";     public static final String QUESTION_FOUR         = "q4";     public static final String QUESTION_FIVE         = "q5";     public static final String QUESTION_SIX          = "q6";     public static final String QUESTION_SEVEN        = "q7";     public static final String QUESTION_EIGHT        = "q8";     public static final String QUESTION_NINE         = "q9";     public static final String QUESTION_TEN          = "q10";     public static final String QUESTION_ELEVEN       = "q11";     public static final String QUESTION_TWELVE       = "q12";     public static final String QUESTION_THIRTEEN     = "q13";       public static final String QUESTION_SIZE            = "question_size";     public static final String CURRENT_QUESTION_TAG     = "current_question";     public static final String CURRENT_QUESTION_POS     = "current_question_pos";     public static final String CURRENT_QUESTION_SCORE   = "test_res_score";      public static final String PASSED_BOOL_STATE        = "passed_result_state";     public static final String PASSED_MSG_STATE         = "passed_message_state";     public static final String PASSED_SCORE             = "passed_score";      public static final String PASSED_DISEASES          = "mard";  } 
     

Lista de respuestas

4
 
vote
vote
La mejor respuesta
 

Usted está mezclando un número significativo de preocupaciones en esta clase. Intentaré revisarlos uno por uno, pero desde que no proporcionó ningún contexto en su pregunta, habrá algunas conjeturas involucradas ...


La primera sección de esta concatenación de constantes está dedicada a algunas URL.

  public static String BASE_URL = "mybaseurl";  public static final String LOGIN_URL           = "login.php"; public static final String FORGETPASS_URL      = "restpassword.php"; public static final String SINGUP_URL          = "signup.php"; public static final String ALLDIEASES_URL      = "alldisease.php"; public static final String QUESTIONS_URL       = "questions"; public static final String EDITPROF_URL        = "editprofile"; public static final String PROF_URL            = "profile";   

Estas deben ingresar a sus puntos de vista específicos en su aplicación, para que la aplicación sepa qué URL solicitará. Lo único que puede pertenecer a una clase central es el BASE_URL , y eso debería ser final y probablemente también una URL y no una cadena.


La siguiente sección está dedicada a la comunicación HTTP:

  Integer0  

Esto no es algo que toda su solicitud debe saber. Esto pertenece a una clase responsable del transporte de información. Algo así como un Integer1 o similar. Debido a que no tengo una descripción general de cuál es la estructura de su proyecto, no sé si una clase de este tipo ya existe o no.

Si no existe, parece que el tiempo lo hagas. Encapsule los detalles del transporte de información!


La siguiente sección se titula Integer2 ... Pregunta: ¿Por qué las constantes para el Integer3 no en la loginactividad? estos son ( De manera similar al Integer4 ) Internos necesarios para esta clase. No tiene sentido hacerlos generalmente disponibles. Si usted "los necesita" en otro lugar, su diseño es probablemente bastante jodido y debe revisarlo.

Luego hay una sección sobre ... Etiquetas. No tengo idea de cómo o dónde los usa, pero probablemente están mejor en una clase dedicada a estas etiquetas.

Luego está Integer5 ... lo mismo que para Integer6 no es necesario transmitir en toda la solicitud. Qué Integer7 Necesidades. Ese es un detalle de implementación, que su aplicación no necesita. Coloque estos campos en Integer8 en la clase dedicada a los usuarios de análisis.

mismo se aplica para Integer9 y int0 .


En general Todas estas constantes no tienen que estar disponibles para toda la solicitud. Solo son locales a partes específicas de su solicitud y deben mantenerse (y mantenerse) allí.

Ponerlos en una clase central lo hace innecesariamente difíciles de mantener una descripción general (¿vio que hay dos secciones de "datos de analizador de usuario"?) e innecesariamente complican el hallazgo de los nombres para nuevas constantes.

En general, toda esta clase parece un resultado de los errores de diseño en otros lugares de su solicitud.

 

You're mixing up a significant number of concerns in this class. I will try to go over them one by one, but since you provided no context in your question there will be some guesswork involved...


The first section of this concatenation of constants is dedicated to some URLs.

public static String BASE_URL = "mybaseurl";  public static final String LOGIN_URL           = "login.php"; public static final String FORGETPASS_URL      = "restpassword.php"; public static final String SINGUP_URL          = "signup.php"; public static final String ALLDIEASES_URL      = "alldisease.php"; public static final String QUESTIONS_URL       = "questions"; public static final String EDITPROF_URL        = "editprofile"; public static final String PROF_URL            = "profile"; 

These should go into your specific Views on your app, so that the app knows what URL to request. the only thing that may belong into a central class is the BASE_URL, and that should be final and probably also a URL and not a String.


The next section is dedicated to HTTP communication:

public static final String APPLICATION_JSON ="application/json"; public static final String CONTENT_TYPE ="Content-Type"; 

This is not something your whole application needs to know about. This belongs into a class responsible for information transport. Something like a RemoteDataFetcher or similar. Because I have no overview of what your project structure is, I don't know whether such a class already exists or not.

If it doesn't exist, it seems time to make it exist. Encapsulate the details of information transport!


The next section is titled login activity constants... Question: Why are the constants for the LoginActivity not in the LoginActivity? These are (similarly to the LOGIN_URL) internals necessary for this one class. There is no point in making them generally available. If you "need them" somewhere else, your design is probably quite screwed and you should revisit it.

Then there is a section about... Tags. I have no idea how or where you use them, but they're probably better off in a class dedicated to these Tags.

Then there's user parser data... the same as for login activity constants applies... There is no need to broadcast into the whole application what a UserParser needs. That's an implementation detail, that your application doesn't need. Put these into private static final fields in the class dedicated to parsing users.

Same applies for Diseases parser data and question parser data.


In general all of these constants don't have to be available to the whole application. They're just local to specific parts of your application and should be kept (and maintained) there.

Putting them into a central class makes it unnecessarily hard on you to keep an overview (did you see there's two "user parser data" secions?) and unnecessarily complicate finding of names for new constants.

Overall this whole class seems a result of design mistakes in other places of your application.

 
 
 
 

Relacionados problema

2  Cálculo del riesgo de los hombres de obtener la enfermedad coronaria  ( Calculating mens risk of getting coronary heart disease ) 
Me gustaría que alguien aquí me ayude a limpiar mi código. Se trata de calcular el riesgo de los hombres de obtener una enfermedad cardíaca coronaria. Aquí e...

2  Función para girar al cojinete solicitado  ( Function to turn to requested bearing ) 
He estado escribiendo una función: float turnToRequestedHeading(float initialHeading, float requiredHeading, float turnRate) Sigo pensando que debe hab...

2  Android Utils Class  ( Android utils class ) 
He creado una clase 99887766555443322 , que consta de progressDialog y AlertDialog : public class Utils { public static ProgressDialog dialog; ...

1  Clase HTTPRequest usando AsintsTask para la aplicación Android  ( Httprequest class using asynctask for android application ) 
Estoy usando la siguiente clase para recuperar una respuesta HTTP, que contiene datos para mi aplicación de Android. Todo funciona bien, pero hay un problema ...

1  Aplicación de Android que hace ciertas acciones en respuesta al estado de alternativa  ( Android app that makes certain actions in response to the state of toggles ) 
He escrito una aplicación de Android mediante un estudio Android que, cuando el interruptor principal está habilitado, al presionar otros interruptores o pres...

4  FindViewByID - en clase separada  ( Findviewbyid in separate class ) 
Soy nuevo en Android y quería crear una clase que cargaría un anuncio dentro del diseño actual. Todos los diseños tienen un 9988777665544336 de mi princip...

41  ¿Es mi código un singleton 'seguro'?  ( Is my code a safe singleton ) 
Me preguntaba si mi código producirá un verdadero Singleton. Estoy creando una aplicación de Android, y todas las actividades deben acceder a mi API a través ...

0  Quiero obtener días laborables para los juegos de tiempo común desde el siguiente hashmap  ( I want to get weekdays for common time sets from the following hashmap ) 
Tengo el siguiente HashMap : HashMap<String, String> days = new HashMap<String, String>(){ days.put("MON", "9-5"); days.put("TUE", "9-4"...

8  Widget de pantalla de inicio para mostrar números aleatorios  ( Home screen widget to display random numbers ) 
He creado un pequeño widget de inicio de sesión que muestra números aleatorios. Adjunto es el código. Por favor, hágamelo saber si el enfoque es bueno. htt...

2  Script de grado de Android en Proyecto Multi-Módulo  ( Android gradle script in multi module project ) 
Tengo un proyecto de Android Multi-Module Construido por Gradle con el nuevo Android-Plugin 0.10 +. Todos los módulos se configuran principalmente desde el ...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos