In one of my project, I am using loopj asynchttpclient for communicating with my website.
The communication part working well and getting response as well
My activity looks like
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebRequest test=new WebRequest();
test.callService();
}
WebRequest Class as
public class WebRequest extends Activity {
public void callService(){
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://domain.com/dp/index.php", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.v("P",response);
}
#Override
public void onFailure(Throwable e, String response) {
Log.v("PS",e.toString());
}
});
}
}
I am confused how to return the response to the main activity, So that I can create the listview from that response.
I am new to this
Please help me
Thanks in advance
In your WebRequest class:
I don't think you want this class to extend Activity. You should only extend Activity when you're making a page to display in your app. You just want to execute some code, so extending Activity isn't needed.
Change your call service method to be static and take an AsyncHttpClient as a parameter.
Your WebRequest class should now look like this:
final class WebRequest {
private AsyncHttpClient mClient = new AsyncHttpClient();
public static void callService(AsyncHttpResponseHandler handler) {
mClient.post("http://domain.com/dp/index.php", handler);
}
}
In your main Activity:
Now all you have to do in your main activity is call the static method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebRequest.callService(new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// Initiated the request
}
#Override
public void onSuccess(String response) {
// Successfully got a response
}
#Override
public void onFailure(Throwable e, String response) {
// Response failed :(
}
#Override
public void onFinish() {
// Completed the request (either success or failure)
}
});
}
Do whatever you need to do with the Views in your activity in the above callbacks. Hope this Helps!
Related
I am using volley library and have made a callback but after getting the result in callback. How should I assign it to another variable and use in same activity.
IResult getResult = new IResult()
{ #Override
public void notifySuccess(String requestType, String response) {
}
#Override
public void notifyError(String requestType, VolleyError error) {
}
};
You can define variable in your activity and assign it from callback.
if you want to update view from this result you can call method from result callback.
String apiResult=null;
IResult getResult = new IResult()
{ #Override
public void notifySuccess(String requestType, String response) {
apiResult=response
//or call method for update UI
}
#Override
public void notifyError(String requestType, VolleyError error) {
//or call method for update UI
}
};
Hope this will help you.
I am learning MVP design for the Android , I am new to it so need your valuable time . I went to the basics of the MVP how it work , Now i got stuck so need your help , I have to post the data to the server , when i hard code the value in presenter then i get the response correct but i need the data that is in the LoginActivity view when user press then that value should pass to the presenter and presenter pass that value to the Retrofit and bring back the result . Here is my try :
My LoginActvity:
public class LoginActivity extends BaseActivity implements LoginView {
#BindView(R.id.company_name)
protected EditText companyName_et;
#BindView(R.id.email)
protected EditText email_et;
#BindView(R.id.password)
protected EditText password_et;
#BindView(R.id.submit)
protected Button submit_btn;
#Inject
LoginPresenter loginPresenter;
#Override
protected int getContentView() {
return R.layout.login_activity;
}
#Override
protected void onViewReady(Bundle savedInstanceState, Intent intent) {
super.onViewReady(savedInstanceState, intent);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String company=companyName_et.getText().toString();
String username=email_et.getText().toString();
String password=password_et.getText().toString();
/*
I have to put the above String data
to my model class then i have to post the data to the server
*/
loginPresenter.passLoginDataToServer();
}
});
}
#Override
public void onError(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(String s) {
}
#Override
public void onResponse(Login login) {
Log.e("-----",""+login.getUserId());
}
#Override
protected void resolveDaggerDependency() {
DaggerLoginComponent.builder().applicationComponent(getApplicationComponent()).loginModule(new LoginModule(this)).build().inject(this);
}
}
Here is Login Presenter :
public class LoginPresenter extends BasePresenter<LoginView> implements Observer<Login>{
#Inject
CreateApiService createApiService;
#Inject
public LoginPresenter(){};
public void passLoginDataToServer(){
/*
when i hard code the data , i get the successful response.Like :
String user="raj";
String check="true";
Map<String,String> headers=new HashMap();
headers,put("xyz","pqr");
Login loginObject = new Login("xyzs", "pqr","Qtch","mvp");
*/
/*
But I need the data here from my LoginActivity ? Dunno how to pass the data from LoginActivity to presenter
*/
Observable<Login> loginObservable=createApiService.loginUser(user, check, headers, loginObject);
subscribeToLogin(loginObservable,this);
}
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Login login) {
getmView().onResponse(login);
}
#Override
public void onError(Throwable e) {
getmView().onError("Error "+e);
Log.e("---",""+e);
}
#Override
public void onComplete() {
getmView().onSuccess("Successfully Loaded");
}
}
Here is My Interface :
public interface LoginView extends BaseView {
void onError(String s);
void onSuccess(String s);
void onResponse(Login login);
}
Could you add the parameters to the method?
In your activity:
#Override public void onClick(View view) {
String company=companyName_et.getText().toString();
String username=email_et.getText().toString();
String password=password_et.getText().toString();
loginPresenter.passLoginDataToServer(compay, username, password);
}
In your presenter:
public void passLoginDataToServer(String company, String username, String password){
// Now create your request from the dynamic parameters
Observable<Login> loginObservable=createApiService.loginUser(username, check, headers, loginObject);
subscribeToLogin(loginObservable,this);
}
In Activity, i called web service and getting json response. Now i need to send this json response in one of the fragment of Activity. Please anyone help me how to send the json response to fragment without null value.
Thank you in advance.
public class Gifts_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refereal_activtiy);
onSucceeded();
}
private void onSucceeded() {
ServiceClient serviceClient = ServiceUtil.getServiceClient();
JsonObject json = new JsonObject();
json.addProperty("user_id", "353");
json.addProperty("device_id", "433");
serviceClient.movie_quiz(json, callback);
}
Callback<JsonObject> callback = new Callback<JsonObject>() {
#Override
public void success(final JsonObject jsonObject, Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
///here i am getting response. i need this response in fragment .
}
});
}
#Override
public void failure(RetrofitError error) {
}
};
}
fragement:
public class Electronics_fragment extends Fragment {
Refeeral_Fragemnt.ShareAdapter adapter;
LinearLayout lay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
lay = (LinearLayout) inflater.inflate(R.layout.referralhistory, container, false);
return lay;
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//here i am getting response. i need this response in fragment .-->
//then here you can store(set) your json response value in SharedPreferences, please define SharedPreferences method globally
//and after when you call fragment retrieve(get) SharedPreferences Method in your Fragment.
}
});
I am using Retrofit connect electronic devices .but it responding with incorrect data.
Please suggest me some solution to this problem. Do you guys have any idea is it related to connect ?
myUrl :http://11.10.88.23/ajax_control&/
Interface Exapi
public interface ExApi {
#GET("/ajax_control&")
public void getFeed(Callback<Document> response);
}
Mainclass
public class MainActivity extends Activity implements RequestInterceptor{
Button mButton;
public static final String BASE_URL="http://11.10.88.23/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestData(BASE_URL);
}
});
}
private void requestData(String url){
RestAdapter adapter=new RestAdapter.Builder()
.setEndpoint(url).build();
ExApi api=adapter.create(ExApi.class);
api.getFeed(new Callback<Document>() {
#Override
public void success(Document document, Response response) {
Toast.makeText(getApplicationContext(), "value: " + document.getElementsByTagName("LED").item(0).getChildNodes().item(0).getNodeValue(), Toast.LENGTH_SHORT).show();
}
#Override
public void failure(RetrofitError retrofitError) {
Log.d("lai loi: ", retrofitError.getMessage());
}
});
}
#Override
public void intercept(RequestFacade requestFacade) {
final String author=encodeCredentialsForBasicAuthorization();
requestFacade.addHeader("Authorization", author);
}
private String encodeCredentialsForBasicAuthorization() {
final String userAndPassword = "user:admin";
return "Basic " + Base64.encodeToString(userAndPassword.getBytes(), Base64.NO_WRAP);
}
}
Error 401 unauthorized means request is denied due to invalid credentials. This kind of authentication is called Basic Authentication, and you can pass these parameters in an HTTP header as well.
Here's an article about how that can be done in Retrofit: https://futurestud.io/blog/android-basic-authentication-with-retrofit/
I've had an interview and I was given the following code, so that the UserAPI is a utility class for retrieving data from the network.
Assume it operate with its own threading mechanism with no respect to the caller thread.
And I had to find what's wrong with the code:
public class NetworkTestActvitiy extends Activity {
private TextView userNameTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chegg_test_layout);
userNameTextView = (TextView)findViewById(R.id.userName);
}
#Override
protected void onStart() {
super.onStart();
loadUserName();
}
private void loadUserName() {
UserAPI.getInstance().getUserName(new NetworkListener() {
#Override
public void onError(ErrorMessage error) {
Logger.e("Failed to get user use: " + error.getMessage());
}
#Override
public void onSuccess(String userName) {
userNameTextView.setText(userName);
}
});
}
}
My guess would be that the call to userNameTextView.setText can not be from UI thread and has to be marshalled.