-1

In my project I am use 3 layers: Activity, DAO and Web Service Transaction, layer Web Service Transaction has HttpClient to execute Get and Post in my web service.

An example to understand: //structure send: Activity->DAO->WebService response: WebService->DAO->Activity

These works, but I'm using Threads and I don't want to use anymore threads. I want knows if there any way to create a generic AsyncTask that can return Boolean and List ?

Looking for a solution I founded this: Want to create a Generic AsyncTask but doesn't work to me, or I can't understand how this works.

How can I do to AsyncTask works in 3 layers as my project ?

So, here my real structure;

Activity

public class MainActivity extends ActionBarActivity {
    private EditText login, senha;
    private Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(android.os.Build.VERSION.SDK_INT > 9){
            StrictMode.ThreadPolicy pol = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(pol);
        }   

        login = (EditText)findViewById(R.id.usuario);
        senha = (EditText)findViewById(R.id.senha);
        btnLogin = (Button)findViewById(R.id.btnLogin);

        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //invoke methods of UsuarioDAO

            }
        });
    }

}

DAO

public class UsuarioDAO{    
    private HttpClientTransaction httpClient;

    /** constructor */
    public UsuarioDAO() {
        httpClient = new HttpClientTransaction();       

    }

    /** insert new object */
    public Boolean insert(Usuario u){
        boolean insert = false;
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("action", "add"));
        nameValuePairs.add(new BasicNameValuePair("nome", u.getNome()));
        nameValuePairs.add(new BasicNameValuePair("login", u.getLogin()));
        nameValuePairs.add(new BasicNameValuePair("senha", u.getSenha()));      

        String s = "http://192.168.1.102/android/login.php";
        String response = httpClient.post(nameValuePairs, s);

        try {
            JSONObject obj = new JSONObject(response);  
            if(obj.getString("erro").equals("1")){
                insert = true;          
            }
        } catch (JSONException e) {     
            e.printStackTrace();
        }

        return insert;
    }

    /** check if usuario has login */
    public Boolean isLogin(Usuario u){
        boolean login = false;
        String s = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";

        String response = httpClient.get(s);

        try {
            JSONObject obj = new JSONObject(response);  
            if(obj.getString("erro").equals("1")){
                login = true;           
            }
        } catch (JSONException e) {     
            e.printStackTrace();
        }   
        return login;
    }

    /** return a list with all usuarios */
    public List<Usuario> getAllUsuario(){
        List<Usuario> list = new ArrayList<Usuario>();
        String s = "http://192.168.1.102/android/login.php?action=getAll";
        String response = httpClient.get(s);

        try {           
            JSONObject obj = new JSONObject(response);  
            JSONArray jsArray = obj.getJSONArray("all");
            for(int x = 0; x < jsArray.length(); x++){
                JSONObject objArray = jsArray.getJSONObject(x);
                Usuario u = new Usuario();
                u.setNome(objArray.getString("nome"));
                u.setLogin(objArray.getString("login"));
            }
        } catch (JSONException e) {     
            e.printStackTrace();
        }   
        return list;
    }    

}

Web Service Transaction

public class HttpClientTransaction {

    private static HttpClient httpClient;   

    public HttpClientTransaction() {
        httpClient = HttpClientConnection.getHttpClient();
    }

    /** execute POST */
    public String post(List<NameValuePair> list, String url){
        String s = "";

        try {
            HttpPost httpPost = new HttpPost(url);          
            //httpPost.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse httpResponse = httpClient.execute(httpPost);           
            HttpEntity entity = httpResponse.getEntity();
            if(entity != null){
                s = EntityUtils.toString(entity);                
            }           
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return s;       
    }


    /** execute GET */
    public String get(String url){
        String s = "";

        try {
            //executa o get
            HttpGet httpGet = new HttpGet(url);         
            //httpGet.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());          
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            if(entity != null){
                s = EntityUtils.toString(entity);                
            }           
        } catch (ClientProtocolException e) {           
            e.printStackTrace();
        } catch (IOException e) {           
            e.printStackTrace();
        }

        return s;
    }


}
Community
  • 1
  • 1
FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118

1 Answers1

0

To my problem I resolved use Volley Library and now works.

I did this

Volley Singleton

public class CustomVolleySingleton extends Application{

    private static CustomVolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    public static final String TAG = "VolleyPatterns";

    private CustomVolleySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap>
                    cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public static synchronized CustomVolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new CustomVolleySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {            
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }


}

Application Controller

public class ApplicationController extends Request<JSONObject>{


        private Map<String, String> params;
        private Response.Listener<JSONObject> listener;

        //Construtores

        public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
            super(Method.GET, url, errorListener);
            this.listener = listener;
            this.params = params;
        }

        public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
            super(method, url, errorListener);
            this.listener = listener;
            this.params = params;
        }

        //método requerido.
        protected Map<String, String> getParams() throws AuthFailureError {
            return params;
        };

        //método requerido.
        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }

        //método requerido
        @Override
        protected void deliverResponse(JSONObject response) {
            listener.onResponse(response);
        }

}

UsuarioDAO

public class UsuarioDAO{    

    private String url = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";

    /** constructor */
    public UsuarioDAO() {       

    }


    public static ApplicationController isLogin(Usuario u, final UsuarioImp usuarioImp){
        String s = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";

        ApplicationController app = new ApplicationController(s, 
                                                              null, 
                                                              new Response.Listener<JSONObject>() {
                                                                @Override
                                                                public void onResponse(JSONObject obj) {
                                                                    try {
                                                                        if(obj.getString("erro").equals("1")){
                                                                            Usuario u = new Usuario();
                                                                            u.setNome("Fernando Paiva - Logado");
                                                                            usuarioImp.onLoginSuccess(u);
                                                                        }else{
                                                                            usuarioImp.onLoginFailure("Erro de login");
                                                                        }
                                                                    } catch (JSONException e) {                                                                     
                                                                        e.printStackTrace();
                                                                    }
                                                                }           
                                                              }, 
                                                              new Response.ErrorListener() {
                                                                @Override
                                                                public void onErrorResponse(VolleyError arg0) {
                                                                    //usuarioImp.onLoginFailure("erro de login");
                                                                }

                                                              });

        return app;
    }

Usuario Interface

public interface UsuarioImp {
    public void onLoginSuccess(Usuario u);
    public void onLoginFailure(String message);

}

Activity

btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ApplicationController app = UsuarioDAO.isLogin(new Usuario(), new UsuarioImp() {

                    @Override
                    public void onLoginSuccess(Usuario u) {
                        Log.i("USUARIO NOME: ", u.getNome());
                    }

                    @Override
                    public void onLoginFailure(String message) {
                        Log.i("ERROOOO: ", message);
                    }
                });         
                CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);      
                CustomVolleySingleton.getInstance(getApplicationContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
            }
        });
FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118