Giter Site home page Giter Site logo

Comments (4)

OpenCodeJourney avatar OpenCodeJourney commented on April 28, 2024 1

Hi Amith,

I really appreciate you help and very thankful for this response. This answer give a kind of clear picture to me. can you please check whether it will work and is it a good practice to reuse the network class for all similar calls to return only success response on main theread.

package com.example.hp.hpdroid.webconnectionutil;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.androidnetworking.interfaces.ParsedRequestListener;
import com.example.hp.hpdroid.R;
import com.example.hp.hpdroid.utils.DialogUtils;
import com.example.hp.hpdroid.utils.NetworkUtil;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.HashMap;

// NetworkCall class
'
public abstract class NetworkCal<T>'{`

protected ProgressDialog pd;
private Context mContext;
 // your networking class
public NetworkCall(Context context){
    mContext = context;
}
protected Context getContext() {
    return mContext;
}

public void getResponseWithNoPriority(String url, HashMap<String,String> parameter, @Nullable final Boolean showProgressDialog){


        if(showProgressDialog){
            pd = ProgressDialog.show(mContext, null, mContext.getString(R.string.fetching_message));
        }
        AndroidNetworking.post(url)

                .addBodyParameter(parameter)
                .setTag("test")
                .build()
                .getAsParsed(new TypeToken<T>() {}, new ParsedRequestListener<T>() {
                    @Override
                    public void onResponse(Object response) {

                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });

    }


public void getResponseWithPrioritySync(String url, HashMap<String,String> parameter, Priority networkCallPriority ,@Nullable final Boolean showProgressDialog){


    if(showProgressDialog && showProgressDialog != null){
        pd = ProgressDialog.show(mContext, null, mContext.getString(R.string.fetching_message));
    }
    AndroidNetworking.post(url)

            .addBodyParameter(parameter)
            .setTag("test")
            .setPriority(networkCallPriority)
            .build()
            .getAsParsed(new TypeToken<T>() {}, new ParsedRequestListener<T>() {
                @Override
                public void onResponse(Object response) {
                    if(showProgressDialog && showProgressDialog != null) {
                        pd.dismiss();
                    }
                }

                @Override
                public void onError(ANError anError) {
                    if(showProgressDialog && showProgressDialog != null) {
                        pd.dismiss();
                    }
                    int errorCode = anError.getErrorCode();
                    if (errorCode == 401){
                        DialogUtils.showSimpleDialog(mContext, "Autharization Error", "Access Deny", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                    }
                    else{
                    DialogUtils.showSimpleDialog(mContext, "Error", "Error Discription", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            //positive action

                            }
                        }
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            //-Ve action

                            }
                        });
                    }
                }
            });
}

protected abstract void getResponseToActivity(T t);

}
`

And in activity to initiate call i am trying to follow this way

``NetworkCall loginResponseNetworkCall` = `new` `NetworkCall(getContext())` {
`@Override`
`protected` `void` `getResponseToActivity(LoginResponse` `loginResponse)` `{`

        }
    };
    loginResponseNetworkCall.getResponseWithMediumPriority(CConstants.HOST_URL,parameters, true);

`

from fast-android-networking.

amitshekhariitbhu avatar amitshekhariitbhu commented on April 28, 2024

You can make the sync call in doInBackground method of AsyncTask and then return the result in onPostExecute method to show that in UI

YourClass extends AsycnTask{
  @Override
  public Response doInBackground(){
    Response response = request.execute();
    return response
  }

  @Override
  public void onPostExecute(Response response){
    // use it in main thread.
  }
}

Anyway you can use the simple API like below without using async as it makes the network call in the background thread and returns the response in the main thread.

AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser")
                 .addBodyParameter("firstname", "Amit")
                 .addBodyParameter("lastname", "Shekhar")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response
                      // response comes in mainthread
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                     // error comes in mainthread
                    }
                });

from fast-android-networking.

OpenCodeJourney avatar OpenCodeJourney commented on April 28, 2024

Hi Amit,

Thank you so much for your valuable response, As I mentioned I am new to programming, I am not sure this is the right place to ask this question. I would like to keep separate all network related code from activity class and create one connection point to initiate all network calls from any activity to return different formatted of JSON data. I saw in retrofit we can Build an ApiInterface and have all urls and parameters for that specific service in it to supply the data at the time of Network Call. Retrofit is going to build the endpoint URL from this info. I was unable to figure out how to do this in FAN. As of my understanding I can't separate networking code because I have to initialize AndroidNetwoking only onCreate() and all .post .get will work from onCreate(). Can please provide me any sample app that is using FAN with a nice architecture. Most part of my app is relayed on data from server response. Until unless i receive the data user cannot interact with UI. Only some Activities have more than on network call. And I have to OAuth and get a new token by using refresh toke before expiration of existing access token. I am really thankful to you in advance for your valuable response.

from fast-android-networking.

amitshekhariitbhu avatar amitshekhariitbhu commented on April 28, 2024

You can do this in following way.

public class MyApplication extends Application{ // This is your application class

  @Override
  public void onCreate(){
    AndroidNetworking.initialization(getApplicationContext());
  }
}
public class Networking{ // your networking class
 public static void getMyResponse(JSONObjectRequestListener listener){

  AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser")
                 .addBodyParameter("firstname", "Amit")
                 .addBodyParameter("lastname", "Shekhar")
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONObject(listener);

}

}
public class MyActivity extends Activity{

   @Override
   public void onCreate(){
    Networking.getMyResponse(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                }
    );
   }
}

from fast-android-networking.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.