I need get var s (commnet) to onCreatView from onPostExecute (Async Task( in order to draw chart.
Here my code:
I try many solution but i cant do this.
String url;
HashMap<String, String> params;
int requestCode;
PerformNetworkRequest3(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject object = new JSONObject(s);
if (!object.getBoolean("error")) {
Toast.makeText(getContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
s = (object.getString("category")); //need var s -> oncreateview
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
Just make an callback interface. Final solution would be.
new PerformNetworkRequest3("", new HashMap<>(), 0, new PerformNetworkRequest3.OnResult() {
#Override
public void onSuccess(String s) {
// check response here.
}
#Override
public void onError() {
}
});
And replace below with your AsyncTask
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
/**
* Created by KHEMRAJ on 7/23/2018.
*/
public class PerformNetworkRequest3 extends AsyncTask<Void, Void, String> {
String url;
HashMap<String, String> params;
int requestCode;
private OnResult onResult;
private interface OnResult{
void onSuccess(String s); // you can change this String to any, like JsonObject
void onError();
}
PerformNetworkRequest3(String url, HashMap<String, String> params, int requestCode, OnResult onResult) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
this.onResult = onResult;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject object = new JSONObject(s);
onResult.onSuccess(s);
if (!object.getBoolean("error")) {
Toast.makeText(getContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
s = (object.getString("category")); //need var s -> oncreateview
}
} catch (JSONException e) {
e.printStackTrace();
onResult.onError();
}
}
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
}
It is just a implementation. You can change callback methods according to your need. Also manage onError() and onSucess() properly.
Try this:-
String url;
HashMap<String, String> params;
int requestCode;
public AsyncResponse delegate=null;
public interface AsyncResponse {
void processFinish(String output);
}
PerformNetworkRequest3(Context ctx, AsyncResponse asyncResponse) {
context = ctx;
delegate = asyncResponse;
}
PerformNetworkRequest3(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject object = new JSONObject(s);
if (!object.getBoolean("error")) {
Toast.makeText(getContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
s = (object.getString("category")); //need var s -> oncreateview
delegate.processFinish(s);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
In your main activity you should implements interface AsyncResponse and overrides its method to get the value.
MainActivity.java
PerformNetworkRequest3 performNetworkRequest3 = new PerformNetworkRequest3(this, new PerformNetworkRequest3 .AsyncResponse() {
#Override
public void processFinish(Boolean output)
{
Toast.makeText(MainActivity.this, "OUTPUT " + output, Toast.LENGTH_SHORT).show();
}
});
performNetworkRequest3.execute("url", "hash_map", "requestCode");
Related
This is my MainActivity, I am unable to understand and write the unit test code for this can someone help me by providing reference or the code for this problem.In the main activity I have created the methods to call the API how can I mock the API response and get the unit tests for this.
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private final String Url="https://dev-smartoffice-api.sharpb2bcloud.com/rmi/v1/checkVersion";
IResult mResultCallback = null;
public MainActivity(IResult iResult)
{
this.mResultCallback=iResult;
}
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService.getDataVolley("GETCALL",Url);
mVolleyService = new VolleyService(mResultCallback,this);
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
// mVolleyService.postDataVolley("POSTCALL", "http://localhost/androidphpmysql/registrationapi.php?apicall=login", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String request,JSONObject response) {
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
// return error;
}
};
}
}
These are my interfaces,here there are two interfaces notify-success and notify error with return type void I don't know how to use them for mocking please help me
public interface IResult {
public void notifySuccess(String requestType, JSONObject response);
public void notifyError(String requestType, VolleyError error);
}
This is my volleyservice class
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
JSONObject message;
public VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
})
{
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest( Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
message=response;
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
}){
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
e.printStackTrace();
}
}
}
I want to post an int to an https address and pass 3 JSON objects to text views and I can't get JSON results. I've tried to use methods in onResponse but it's not working. How can I POST an integer and parse some JSON objects to text views? I'm a beginner in Android developing and I don't know how to resolve this problem.
What's the problem? please help
if(isNetworkAvailable()){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://example.com/api";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response);
} catch (JSONException e) {
e.printStackTrace();
alertUserAboutError();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
mStoreName.setText("Error");
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("category_id", "28");
return params;
}
};
queue.add(postRequest);
}
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show(); }
private void updateDisplay() {
mStoreName.setText(mStoreDetails.getStoreName());
mInstagram.setText(mStoreDetails.getInstagram());
mTelegram.setText(mStoreDetails.getTelegram());
}
private StoreDetails getStoreDetails(String jsonData) throws JSONException {
JSONObject JSONRequest = new JSONObject(jsonData);
StoreDetails storeDetails = new StoreDetails();
storeDetails.setStoreName(JSONRequest.getString("store_name"));
storeDetails.setInstagram(JSONRequest.getString("instagram"));
storeDetails.setTelegram(JSONRequest.getString("telegram"));
return storeDetails;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
This works for me. Use an stringrequest to put the post data to the request. After onResponse was called I create an JSON-Object from the string:
public void doServerRequest(final Context context, final String url, final Map<String,String> postParameters, final HashMap<String,String> getParameters, final OnFinishTaskListener<String, JSONObject> listener){
Log.d(TAG,"Start new server request (" + url + ")");
StringRequest request = new StringRequest(Request.Method.POST, addParametersToUrl(url, getParameters), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
try {
JSONObject json = new JSONObject(response);
if (json.getInt(CODE_TAG) == 0){
listener.getResult(SUCCESS_TAG, json);
} else {
listener.getResult(ERROR_TAG, null);
}
} catch (Exception e){
e.printStackTrace();
listener.getResult(ERROR_TAG, null);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
listener.getResult(ERROR_TAG, null);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
if(postParameters == null){
return new HashMap<String, String>();
}
return postParameters;
}
};
requestQueue.add(request);
}
This adds the get-Paramters to the URL (if exist):
private String addParametersToUrl(String url, HashMap<String,String> getParameters){
if(getParameters == null || getParameters.size() == 0){
return url;
}
Log.d(TAG,"Preparing URL: "+url);
StringBuilder stringBuilder = new StringBuilder(url);
stringBuilder.append("?");
int i = 0;
for (String key : getParameters.keySet()) {
if(i>0) stringBuilder.append("&");
stringBuilder.append(key).append("=").append(getParameters.get(key));
i++;
}
url = stringBuilder.toString();
Log.d(TAG,"Prepared URL: "+url);
return url;
}
I use this listener interface:
public interface OnFinishTaskListener<S,J> {
public void getResult(S string, J json);
}
I'm sending the holder view to volley method in ArrayAdapter like
final ViewHolder finalHolder = holder;
holder.rlLike.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
userLikes(finalHolder);
}
});
private void userLikes(final ViewHolder finalHolder){
StringRequest request = new StringRequest(Request.Method.POST, user_likes_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response != null){
Log.e("LikeResponse", response);
try {
JSONObject jsonObject = new JSONObject(response);
//toastShort(activity, user_likes_obj.getString("data"));
if(jsonObject.getString("status").equals("success")){
finalHolder.userLikeImage.setImageResource(R.drawable.icon_pop_like);
finalHolder.tvLike.setText("Unlike");
}else {
}
} catch (JSONException e) {
e.getLocalizedMessage();
e.printStackTrace();
}
}else{
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
Log.e("action", user_likes);
params.put("action",user_likes);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
queue.getCache().remove(user_likes_url);
}
After getting the successful response from the server I'm changing the ImageView and TextView like
finalHolder.userLikeImage.setImageResource(R.drawable.icon_pop_like);
finalHolder.tvLike.setText("Unlike");
But I want to send the holder view to asynchronus task and bassed on the server response I want to change ImageView and TextView as above
My AsyncTask task code is
private void userLikes(String likeStatus){
class carRegAsynTask extends AsyncTask<String, Void, String>{
//ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String likeStatusParam = params[0];
BasicNameValuePair likeStatus = new BasicNameValuePair("action", likeStatusParam);
List<NameValuePair> listValuePairs = new ArrayList<NameValuePair>();
listValuePairs.add(likeStatus);
Log.e("listValuePairs", listValuePairs.toString());
String Url = user_likes_url;
Log.e("Url", Url);
String response = POST_METHOD(listValuePairs, Url);
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Log.e("LikeResult2", result);
try {
JSONObject jsonObject = new JSONObject(result);
if(jsonObject.getString("status").equals("success")){
userLikeImage.setImageResource(R.drawable.icon_pop_un_like);
tvLike.setText("Like");
}else {
}
} catch (JSONException e) {
e.getLocalizedMessage();
e.printStackTrace();
}
}
}
}
new carRegAsynTask().execute(likeStatus);
}
So please help me to send the holder view to Asynchronus task like in the volley method I discussed above, and don't forget it is an ArrayAdapter
Although this is not a good practice to hold strong references to views from asynchronous tasks, you can pass whatever you need to your carRegAsynTask. Just create a constructor and pass all the needed data as parameters.
UPDATE
Example:
class carRegAsynTask extends AsyncTask<String, Void, String>{
private final ViewHolder viewHolder;
public carRegAsynTask(ViewHolder viewHolder) {
this.viewHolder = viewHolder;
}
// omitted for brevity...
// Use your viewHolder in onPreExecute or onPostExecute
}
// Creating async task with your viewHolder:
new carRegAsynTask(viewHolder).execute(likeStatus);
I don't know whether it follow able or not, but i achieved it in this way
private void userLikes(final ViewHolder finalHolder) {
class userLikesAsynTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BasicNameValuePair userid = new BasicNameValuePair("action", user_likes);
List<NameValuePair> listValuePairs = new ArrayList<NameValuePair>();
listValuePairs.add(userid);
Log.e("listValuePairs", listValuePairs.toString());
String userLikesUrl = user_likes_url;
Log.e("userLikesUrl", userLikesUrl);
String response = POST_METHOD(listValuePairs, userLikesUrl);
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Log.e("userLikesUrlResult", result);
try {
JSONObject jsonObject = new JSONObject(result);
if(jsonObject.has("status")){
if(jsonObject.getString("status").equals("success")){
finalHolder.userLikeImage.setImageResource(R.drawable.icon_pop_like);
finalHolder.tvLike.setText("Unlike");
}else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
new userLikesAsynTask().execute();
}
I have an image and I want to upload this image to my web service using Volley library, the problem is I'm looking for a how to do it but still haven't found.
I found this, but doesn't work to me: http://develop-for-android.blogspot.com.br/2014/01/using-volley-in-your-application.html
How can I do this ?
I'm trying this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
fotoPerfil = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
UploadoImageToServer upload = new UploadoImageToServer();
ApplicationController app = new UsuarioDAO().insert(usuario, upload.upload(fotoPerfil, em[0]), new UsuarioAdapter(){
#Override
public void usuarioIsAdded(Boolean result){
Log.i("Adicionou: ", result + "");
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);
public class UploadoImageToServer {
public String upload(String image,String nomeImagem){
Bitmap bitmap = BitmapFactory.decodeFile(image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
return image_str;
}
}
/** add an user and upload your foto(image) */
public ApplicationController insert(Usuario u, String uploadFile, final UsuarioAdapter listener) {
boolean insert = false;
HashMap<String, String> params = new HashMap<String, String>();
params.put("nome", u.getNome());
params.put("email", u.getEmail());
params.put("senha", u.getSenha());
params.put("tipo", "usuarios");
params.put("acao", "add");
params.put("device_tipo", "android");
params.put("device", AndroidReturnId.getAndroidId());
params.put("uploadedfile", uploadFile);
Log.i("URL: ", urlPost.toString());
ApplicationController apc = new ApplicationController(Method.POST, urlPost.toString(), params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("cod").equals("999")){
listener.usuarioIsAdded(true);
}else{
listener.usuarioIsAdded(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "insert in UsuarioDAO: " + arg0.getLocalizedMessage());
}
});
return apc;
}
i am not much familier with volley, but give a try to the following code
//JSON Request
public MySampleImageUpload() {
JSONRequestResponse mResponse = new
JSONRequestResponse(mContext);
Bundle parms = new Bundle();
parms.putString("key_meail", "rojesh#demo.com");
parms.setFile("key_url", image_path);
mResponse.getResponse("sample_upload_data_url", REQUEST_CODE, this,
parms);
}
// In SetFile & getResponse code
package com.fartogram.utils;
import java.io.File;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.examples.toolbox.MultipartRequest;
import com.android.volley.examples.toolbox.MyVolley;
import com.android.volley.toolbox.JsonObjectRequest;
public class JSONRequestResponse {
public JSONRequestResponse(Context cntx) {
mContext = cntx;
}
private final Context mContext;
private int reqCode;
private IParseListener listner;
private boolean isFile = false;
private String file_path = "", key = "";
public void getResponse(String url, final int requestCode,
IParseListener mParseListener) {
getResponse(url, requestCode, mParseListener, null);
}
public void getResponse(String url, final int requestCode,
IParseListener mParseListener, Bundle params) {
this.listner = mParseListener;
this.reqCode = requestCode;
Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (listner != null) {
listner.SuccessResponse(response, reqCode);
}
}
};
Response.ErrorListener eListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (listner != null) {
listner.ErrorResponse(error, reqCode);
}
}
};
if (!isFile) {
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, sListener,
eListener);
MyVolley.getRequestQueue().add(jsObjRequest);
} else {
if (file_path != null) {
File mFile = new File(file_path);
MultipartRequest multipartRequest =
new MultipartRequest(url,eListener, sListener, key, mFile, params);
MyVolley.getRequestQueue().add(multipartRequest);
}
}
}
public boolean isFile() {
return isFile;
}
public void setFile(String param, String path) {
if (path != null && param != null) {
key = param;
file_path = path;
this.isFile = true;
}
}
}
If it works for you mark it as right :)
You have to extend Request and use MultipartEntityBuilder if you wanna upload your image as a file.
public class ImageUploadWithVolley<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File yourImageFile;
protected Map<String, String> headers;
public ImageUploadWithVolley(String url, ErrorListener errorListener, Listener<T> listener, File imageFile) {
super(Method.POST, url, errorListener);
mListener = listener;
yourImageFile = imageFile;
addImageEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("Accept", "application/json");
return headers;
}
private void addImageEntity() {
mBuilder.addBinaryBody("give your image name", yourImageFile, ContentType.create("image/jpeg"), yourImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String content = mBuilder.build().getContentType().getValue();
return content;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e){
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response){
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
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;
}
}
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);
}
});