myCall.enqueue(new Callback() ){.....} is not giving any response - android

I am making one adforest classified alike app in my android studio and
below is the splash screen activity which executes first when i click on app icon but after that next activity does not open...progress bar on splash screen keeps on rotating but it is not openning next activity !!
SplashScreen.java
public class SplashScreen extends AppCompatActivity {
Activity activity;
SettingsMain setting;
JSONObject jsonObjectSetting;
boolean isRTL = false;
public static JSONObject jsonObjectAppRating, jsonObjectAppShare;
public static boolean gmap_has_countries = false, app_show_languages = false;
public static JSONArray app_languages;
public static String languagePopupTitle, languagePopupClose, gmap_countries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Configuration configuration = getResources().getConfiguration();
configuration.fontScale = (float) 1; //0.85 small size, 1 normal size, 1,15 big etc
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.fontScale * metrics.density;
getBaseContext().getResources().updateConfiguration(configuration, metrics);
activity = this;
setting = new SettingsMain(this);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
setting.setUserLogin("0");
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.apply();
}
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.call4site.nearhaat",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (PackageManager.NameNotFoundException e)
{
e.printStackTrace();
}
if (SettingsMain.isConnectingToInternet(this)) {
adforest_getSettings(this);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(SplashScreen.this);
alert.setTitle(setting.getAlertDialogTitle("error"));
alert.setCancelable(false);
alert.setMessage(setting.getAlertDialogMessage("internetMessage"));
alert.setPositiveButton(setting.getAlertOkText(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
SplashScreen.this.recreate();
}
});
alert.show();
}
}
public void adforest_getSettings(final Context context) {
RestService restService =
UrlController.createService(RestService.class);
Call<ResponseBody> myCall = restService.getSettings(UrlController.AddHeaders(this));
myCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObj) {
try {
if (responseObj.isSuccessful()) {
Log.d("info settings Responce", "" + responseObj.toString());
JSONObject response = new JSONObject(responseObj.body().string());
Log.d("info settings object", "" + response.getJSONObject("data"));
if (response.getBoolean("success")) {
jsonObjectSetting = response.getJSONObject("data");
setting.setMainColor(jsonObjectSetting.getString("main_color"));
isRTL = jsonObjectSetting.getBoolean("is_rtl");
setting.setRTL(isRTL);
setting.setAlertDialogTitle("error", jsonObjectSetting.getJSONObject("internet_dialog").getString("title"));
setting.setAlertDialogMessage("internetMessage", jsonObjectSetting.getJSONObject("internet_dialog").getString("text"));
setting.setAlertOkText(jsonObjectSetting.getJSONObject("internet_dialog").getString("ok_btn"));
setting.setAlertCancelText(jsonObjectSetting.getJSONObject("internet_dialog").getString("cancel_btn"));
setting.setAlertDialogTitle("info", jsonObjectSetting.getJSONObject("alert_dialog").getString("title"));
setting.setAlertDialogMessage("confirmMessage", jsonObjectSetting.getJSONObject("alert_dialog").getString("message"));
setting.setAlertDialogMessage("waitMessage", jsonObjectSetting.getString("message"));
setting.setAlertDialogMessage("search", jsonObjectSetting.getJSONObject("search").getString("text"));
setting.setAlertDialogMessage("catId", jsonObjectSetting.getString("cat_input"));
setting.setAlertDialogMessage("location_type", jsonObjectSetting.getString("location_type"));
setting.setAlertDialogMessage("gmap_lang", jsonObjectSetting.getString("gmap_lang"));
setting.setGoogleButn(jsonObjectSetting.getJSONObject("registerBtn_show").getBoolean("google"));
setting.setfbButn(jsonObjectSetting.getJSONObject("registerBtn_show").getBoolean("facebook"));
JSONObject alertDialog = jsonObjectSetting.getJSONObject("dialog").getJSONObject("confirmation");
setting.setGenericAlertTitle(alertDialog.getString("title"));
setting.setGenericAlertMessage(alertDialog.getString("text"));
setting.setGenericAlertOkText(alertDialog.getString("btn_ok"));
setting.setGenericAlertCancelText(alertDialog.getString("btn_no"));
setting.isAppOpen(jsonObjectSetting.getBoolean("is_app_open"));
setting.checkOpen(jsonObjectSetting.getBoolean("is_app_open"));
setting.setGuestImage(jsonObjectSetting.getString("guest_image"));
JSONObject jsonObjectLocationPopup = jsonObjectSetting.getJSONObject("location_popup");
Log.d("info location_popup obj", "" + jsonObjectLocationPopup);
setting.setLocationSliderNumber(jsonObjectLocationPopup.getInt("slider_number"));
setting.setLocationSliderStep(jsonObjectLocationPopup.getInt("slider_step"));
setting.setLocationText(jsonObjectLocationPopup.getString("text"));
setting.setLocationBtnSubmit(jsonObjectLocationPopup.getString("btn_submit"));
setting.setLocationBtnClear(jsonObjectLocationPopup.getString("btn_clear"));
JSONObject jsonObjectLocationSettings = jsonObjectSetting.getJSONObject("gps_popup");
setting.setShowNearby(jsonObjectSetting.getBoolean("show_nearby"));
Log.d("info gps_popup obj", "" + jsonObjectLocationSettings);
setting.setGpsTitle(jsonObjectLocationSettings.getString("title"));
setting.setGpsText(jsonObjectLocationSettings.getString("text"));
setting.setGpsConfirm(jsonObjectLocationSettings.getString("btn_confirm"));
setting.setGpsCancel(jsonObjectLocationSettings.getString("btn_cancel"));
setting.setAdsPositionSorter(jsonObjectSetting.getBoolean("ads_position_sorter"));
setting.setBannerShow(false);
setting.setAdsPosition("");
setting.setBannerAdsId("");
setting.setInterstitalShow(false);
setting.setAdsInitialTime("");
setting.setAdsDisplayTime("");
setting.setInterstitialAdsId("");
setting.setNotificationTitle("");
setting.setNotificationMessage("");
setting.setNotificationTitle("");
if (setting.getAppOpen()) {
setting.setNoLoginMessage(jsonObjectSetting.getString("notLogin_msg"));
}
setting.setFeaturedScrollEnable(jsonObjectSetting.getBoolean("featured_scroll_enabled"));
if (setting.isFeaturedScrollEnable()) {
Log.d("info setting AutoScroll", jsonObjectSetting.getJSONObject("featured_scroll").toString());
setting.setFeaturedScroolDuration(jsonObjectSetting.getJSONObject("featured_scroll").getInt("duration"));
setting.setFeaturedScroolLoop(jsonObjectSetting.getJSONObject("featured_scroll").getInt("loop"));
}
jsonObjectAppRating = jsonObjectSetting.getJSONObject("app_rating");
jsonObjectAppShare = jsonObjectSetting.getJSONObject("app_share");
gmap_has_countries = jsonObjectSetting.getBoolean("gmap_has_countries");
if (gmap_has_countries) {
gmap_countries = jsonObjectSetting.getString("gmap_countries");
}
app_show_languages = jsonObjectSetting.getBoolean("app_show_languages");
if (app_show_languages) {
languagePopupTitle = jsonObjectSetting.getString("app_text_title");
languagePopupClose = jsonObjectSetting.getString("app_text_close");
app_languages = jsonObjectSetting.getJSONArray("app_languages");
}
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
if (setting.getUserLogin().equals("0")) {
SplashScreen.this.finish();
if (setting.isLanguageChanged()) {
if (isRTL)
updateViews("ur");
else {
updateViews("en");
}
}
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.right_enter, R.anim.left_out);
} else {
SplashScreen.this.finish();
if (setting.isLanguageChanged()) {
if (isRTL)
updateViews("ur");
else {
updateViews("en");
}
}
setting.isAppOpen(false);
Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.right_enter, R.anim.left_out);
}
if (app_show_languages && !setting.isLanguageChanged()) {
if (setting.getLanguageRtl()) {
updateViews("ur");
} else {
updateViews("en");
}
}
}
}, 2000);
} else {
Toast.makeText(activity, response.get("message").toString(), Toast.LENGTH_SHORT).show();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("info settings error", String.valueOf(t));
Log.d("info settings error", String.valueOf(t.getMessage() + t.getCause() + t.fillInStackTrace()));
}
});
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base));
}
private void updateViews(String languageCode) {
LocaleHelper.setLocale(this, languageCode);
}
}
This is UrlController java class which uses to call retrofit api:
UrlController.java
public class UrlController {
static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.build();
private static String Purchase_code = "************************";
private static String Custom_Security = "***********************";
private static String url = "null";
private static String Base_URL = "https://yourdomain.co.in/demo/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(Base_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass)
{
url = retrofit.baseUrl().toString();
return retrofit.create(serviceClass);
}
public static <S> S createService(
Class<S> serviceClass, String username, String password, Context context)
{
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
String authToken = Credentials.basic(username, password);
return createService(serviceClass, authToken, context);
}
return createService(serviceClass, null, null, context);
}
public static <S> S createService(
Class<S> serviceClass, final String authToken, Context context)
{
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken, context);
if (!httpClient.interceptors().contains(interceptor))
{
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
public static Map<String, String> AddHeaders(Context context) {
Map<String, String> map = new HashMap<>();
if (SettingsMain.isSocial(context)) {
map.put("AdForest-Login-Type", "social");
}
map.put("Purchase-Code", Purchase_code);
map.put("custom-security", Custom_Security);
map.put("Adforest-Request-From", "android");
map.put("Adforest-Lang-Locale", SettingsMain.getLanguageCode());
map.put("Content-Type", "application/json");
map.put("Cache-Control", "max-age=640000");
return map;
}
public static Map<String, String> UploadImageAddHeaders(Context context) {
Map<String, String> map = new HashMap<>();
if (SettingsMain.isSocial(context)) {
map.put("AdForest-Login-Type", "social");
}
map.put("Purchase-Code", Purchase_code);
map.put("custom-security", Custom_Security);
map.put("Adforest-Lang-Locale", SettingsMain.getLanguageCode());
map.put("Adforest-Request-From", "android");
map.put("Cache-Control", "max-age=640000");
return map;
}
}
when it executes:
myCall.enqueue(new Callback()
{
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObj)
{
//some code here
} );
#Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{
//some code here
}
It does not executes either the on response method or on Failure method. No error or exception in catch block. In android studio logcat debug mode it shows :
D/WindowClient: Remove from mViews:android.widget.LinearLayout{a73a5de V.E...... ......I. 0,0-580,115}, this = android.view.WindowManagerGlobal#eeef6d7
i don't understand the problem behind it...is this debug message is the cause due to which next activity not opening or it is happening due to something else??
I am badly stuck here...not finding any way to move ahead !!

Related

While fetching data and storing it into sqlite db the UI of my app freezes

Hello My app is freezes ui for some seconds while it is fetching data from network and stores it in db and then shows it in recyclerview. For fetching data from network I am using retrofit and for storing it and fetching form db Room library. Both with the help of MVVM pattern. Is there a way to remoove the UI freeze?
Here is my code:
In the Mainactivity when clicking download btn
downloadBtn.setOnClickListener(v ->
eventsViewModel.insertEvents(this));
Viewmodel class:
public void insertEvents(Context context){
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String token = preferences.getString("token", "");
final Map<String,String> queryData = new HashMap<>();
queryData.put("token", token);
Call<EventsResponse> call = RetrofitClient.getmInstance().getApi().getEvents(queryData);
call.enqueue(new Callback<EventsResponse>() {
#Override
public void onResponse(Call<EventsResponse> call, Response<EventsResponse> response) {
if (response.code() == 401){
String email = preferences.getString("email", "");
String password = preferences.getString("password", "");
Call<LoginResponse> call1 = RetrofitClient.getmInstance().getApi().loginuser(email, password);
call1.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.code() == 200){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putString("token", response.body().getToken());
editor.apply();
insertEvents(context);
}
else {
}
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
}
});
}
if (response.code() == 200){
eventList = response.body().getData();
EventsTable eventsTable = new EventsTable();
TicketDatesTable ticketDatesTable = new TicketDatesTable();
for (int i = 0; i < eventList.size(); i++) {
eventsTable.setEvent_id(eventList.get(i).getId());
eventsTable.setTitle_tk(eventList.get(i).getTitle_tk());
eventsTable.setTitle_ru(eventList.get(i).getTitle_ru());
eventsTable.setImageURL("https://bilettm.com/" + eventList.get(i).getImage_url());
eventsTable.setStart_date(eventList.get(i).getStart_date());
eventsTable.setEnd_date(eventList.get(i).getEnd_date());
eventsTable.setSales_volume(eventList.get(i).getEnd_date());
eventsTable.setOrganiser_fees_volume(eventList.get(i).getOrganiser_fees_volume());
eventsTable.setViews(eventList.get(i).getViews());
eventsTable.setSales_volume(eventList.get(i).getSales_volume());
eventsTable.setIs_live(eventList.get(i).getIs_live());
if (!eventList.get(i).getTicket_dates().isEmpty()) {
showTimeList = eventList.get(i).getTicket_dates();
int b = 0;
while (b < showTimeList.size()) {
ticketDatesTable.setEvent_id(showTimeList.get(b).getEvent_id());
ticketDatesTable.setTicket_date(showTimeList.get(b).getTicket_date());
insertTicketDates(ticketDatesTable);
try {
Thread.sleep(150);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
b++;
}
}
insert(eventsTable);
try {
Thread.sleep(150);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
#Override
public void onFailure(Call<EventsResponse> call, Throwable t) {
}
});
}
public void insert(EventsTable data){
repository.insertEvents(data);
}
public void insertTicketDates(TicketDatesTable ticketDatesTable){
repository.insertTicketDates(ticketDatesTable);
Here is my repository :
public void insertEvents(EventsTable data){
new EventInsertion(eventsDAO).execute(data);
}
private static class EventInsertion extends AsyncTask<EventsTable, Void, Void> {
private EventsDAO eventsDAO;
private EventInsertion(EventsDAO eventsDAO) {
this.eventsDAO = eventsDAO;
}
#Override
protected Void doInBackground(EventsTable... eventsTables) {
eventsDAO.insertEvents(eventsTables[0]);
return null;
}
}
public void insertTicketDates(TicketDatesTable data){
new TicketDatesInsertion(eventsDAO).execute(data);
}
private static class TicketDatesInsertion extends AsyncTask<TicketDatesTable, Void, Void> {
private EventsDAO eventsDAO;
private TicketDatesInsertion(EventsDAO eventsDAO) {
this.eventsDAO = eventsDAO;
}
#Override
protected Void doInBackground(TicketDatesTable... ticketDatesTables) {
eventsDAO.insertTicketDates(ticketDatesTables[0]);
return null;
}
}
Here is my DAO:
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertEvents(EventsTable data);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertTicketDates(TicketDatesTable datesTable);
I think it freezes when it is storing it into sqlite db
I found my problem. It was initializing entity before starting for loop:
BEFORE:
EventsTable eventsTable = new EventsTable();
for (int i = 0; i < eventList.size(); i++) {
INSERT();
}
AFTER:
for (int i = 0; i < eventList.size(); i++) {
EventsTable eventsTable = new EventsTable();
INSERT();
}
A better solution would be to collect all your required objects in an ArrayList and then pass it on to the AsyncTask and from there to DAO for bulk insertion.
And remove all Thread.sleep(150) statements as they serve no purpose.
why you are using this Thread.sleep(150);Call is already a background task in retrofit

Retrofit 2 image upload

in fact I am in the process of preparing an android application that makes the upload of an image on a server thanks to a REST API.
I tested lapi with POSTMAN and I have no errors.
but have an error in this part: I that the crash app before intent
this is my source codes:
public class FileShooser extends AppCompatActivity {
private static final int INTENT_REQUEST_CODE = 100;
private String name ;
private CompositeSubscription mSubscriptions;
ProgressDialog progressdialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSubscriptions = new CompositeSubscription();
// get name from last activity
name= getIntent().getStringExtra("Name");
// start file shooser intent
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
try {
startActivityForResult(intent, INTENT_REQUEST_CODE );
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==INTENT_REQUEST_CODE)
{
if(resultCode==RESULT_OK){
uploadImage( data.getData());
}
}
}
public byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream byteBuff = new ByteArrayOutputStream();
int buffSize = 1024;
byte[] buff = new byte[buffSize];
int len = 0;
while ((len = is.read(buff)) != -1) {
byteBuff.write(buff, 0, len);
}
return byteBuff.toByteArray();
}
private void uploadImage(Uri fileUri) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
// use the FileUtils to get the actual file by uri
File file = new File(fileUri.getPath());
showSnackBarMessage("name:"+file.getName());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// progress dialog
progressdialog = new ProgressDialog(getApplicationContext());
progressdialog.setMessage("Please wait ...");
progressdialog.show();
retrofitInterface.upload(name,body).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError);
}
private void handleError(Throwable error) {
progressdialog.dismiss();
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
showSnackBarMessage(response.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
} else {
showSnackBarMessage("Network Error !");
}
}
private void handleResponse(Response response) {
progressdialog.dismiss();
showSnackBarMessage(response.getMessage());
}
private void showSnackBarMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
thank you very much for your answers

Register a new user on ejabberd server in android

I am facing the problem to create a new user on ejabberd server but sign in is working fine. i used the github repository (https://github.com/dilicode/LetsChat) for register the new user and chat between two and more users. I search on intenet, i found some way to register those are:
1.add
%% In-band registration
{access, register, [{allow, all}]}.
in access rules in ejabberd server and
2. also add
{mod_register, [
{access_from, register},
...
] ...
it in access rules of ejabberd server.
my sign up activity as follows:
public class SignupActivity extends AppCompatActivity implements OnClickListener, Listener<Boolean> {
private static final int REQUEST_CODE_SELECT_PICTURE = 1;
private static final int REQUEST_CODE_CROP_IMAGE = 2;
private static final String RAW_PHOTO_FILE_NAME = "camera.png";
private static final String AVATAR_FILE_NAME = "avatar.png";
private EditText nameText;
private EditText phoneNumberText;
private EditText passwordText;
private Button submitButton;
private ImageButton uploadAvatarButton;
private File rawImageFile;
private File avatarImageFile;
private SignupTask signupTask;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
nameText = (EditText)findViewById(R.id.et_name);
phoneNumberText = (EditText)findViewById(R.id.et_phone_number);
passwordText = (EditText)findViewById(R.id.et_password);
uploadAvatarButton = (ImageButton)findViewById(R.id.btn_upload_avatar);
submitButton = (Button)findViewById(R.id.btn_submit);
submitButton.setOnClickListener(this);
uploadAvatarButton.setOnClickListener(this);
File dir = FileUtils.getDiskCacheDir(this, "temp");
if (!dir.exists()) {
dir.mkdirs();
}
rawImageFile = new File(dir, RAW_PHOTO_FILE_NAME);
avatarImageFile = new File(dir, AVATAR_FILE_NAME);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v == submitButton) {
String phoneNumber = phoneNumberText.getText().toString();
String password = passwordText.getText().toString();
String name = nameText.getText().toString();
if (phoneNumber.trim().length() == 0 || password.trim().length() == 0 ||
name.trim().length() == 0) {
Toast.makeText(this, R.string.incomplete_signup_info, Toast.LENGTH_SHORT).show();
return;
}
signupTask = new SignupTask(this, this, phoneNumber, password, name, getAvatarBytes());
signupTask.execute();
} else if(v == uploadAvatarButton) {
chooseAction();
}
}
private void chooseAction() {
Intent captureImageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rawImageFile));
Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(pickIntent, getString(R.string.profile_photo));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {captureImageIntent});
startActivityForResult(chooserIntent, REQUEST_CODE_SELECT_PICTURE);
}
#Override
public void onResponse(Boolean result) {
if (result) {
Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
setResult(RESULT_OK);
finish();
}
}
#Override
public void onErrorResponse(Exception exception) {
Toast.makeText(this, R.string.create_account_error, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_SELECT_PICTURE:
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
startCropImage(Uri.fromFile(rawImageFile));
} else {
startCropImage(data == null ? null : data.getData());
}
break;
case REQUEST_CODE_CROP_IMAGE:
Bitmap bitmap = BitmapFactory.decodeFile(avatarImageFile.getAbsolutePath());
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
drawable.setCircular(true);
uploadAvatarButton.setImageDrawable(drawable);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startCropImage(Uri source) {
if (source != null) {
int size = getResources().getDimensionPixelSize(R.dimen.default_avatar_size);
CropImageIntentBuilder cropImage = new CropImageIntentBuilder(size, size, Uri.fromFile(avatarImageFile));
cropImage.setSourceImage(source);
startActivityForResult(cropImage.getIntent(this), REQUEST_CODE_CROP_IMAGE);
}
}
private byte[] getAvatarBytes() {
if (!avatarImageFile.exists()) return null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(avatarImageFile);
} catch (FileNotFoundException e) {
AppLog.e("avatar file not found", e);
}
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return output.toByteArray();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (signupTask != null) {
signupTask.dismissDialogAndCancel();
}
}
}
SignupTaskActivity as follows:
public class SignupTask extends BaseAsyncTask<Void, Void, Boolean> {
private String user;
private String name;
private String password;
private byte[] avatar;
private ProgressDialog dialog;
public SignupTask(Listener<Boolean> listener, Context context, String user, String password, String name, byte[] avatar) {
super(listener, context);
this.user = user;
this.name = name;
this.password = password;
this.avatar = avatar;
dialog = ProgressDialog.show(context, null, context.getResources().getString(R.string.signup));
}
#Override
public Response<Boolean> doInBackground(Void... params) {
Context context = getContext();
if (context != null) {
try {
SmackHelper.getInstance(context).signupAndLogin(user, password, name, avatar);
if (avatar != null) {
ImageCache.addAvatarToFile(context, user, BitmapFactory.decodeByteArray(avatar, 0, avatar.length));
}
PreferenceUtils.setLoginUser(context, user, password, name);
return Response.success(true);
} catch(SmackInvocationException e) {
AppLog.e(String.format("sign up error %s", e.toString()), e);
return Response.error(e);
}
}
return null;
}
#Override
protected void onPostExecute(Response<Boolean> response) {
dismissDialog();
super.onPostExecute(response);
}
#Override
protected void onCancelled() {
super.onCancelled();
dismissDialog();
}
public void dismissDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void dismissDialogAndCancel() {
dismissDialog();
cancel(false);
}
}
SmackHelper class as follows:
public class SmackHelper {
private static final String LOG_TAG = "SmackHelper";
private static final int PORT = 5222;
public static final String RESOURCE_PART = "Smack";
private XMPPConnection con;
private ConnectionListener connectionListener;
private Context context;
private State state;
private PacketListener messagePacketListener;
private PacketListener presencePacketListener;
private SmackAndroid smackAndroid;
private static SmackHelper instance;
private SmackContactHelper contactHelper;
private SmackVCardHelper vCardHelper;
private FileTransferManager fileTransferManager;
private PingManager pingManager;
private long lastPing = new Date().getTime();
public static final String ACTION_CONNECTION_CHANGED = "com.mstr.letschat.intent.action.CONNECTION_CHANGED";
public static final String EXTRA_NAME_STATE = "com.mstr.letschat.State";
private SmackHelper(Context context) {
this.context = context;
smackAndroid = SmackAndroid.init(context);
messagePacketListener = new MessagePacketListener(context);
presencePacketListener = new PresencePacketListener(context);
SmackConfiguration.setDefaultPacketReplyTimeout(20 * 1000);
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
ProviderManager.addExtensionProvider(UserLocation.ELEMENT_NAME, UserLocation.NAMESPACE, new LocationMessageProvider());
}
public static synchronized SmackHelper getInstance(Context context) {
if (instance == null) {
instance = new SmackHelper(context.getApplicationContext());
}
return instance;
}
public void setState(State state) {
if (this.state != state) {
Log.d(LOG_TAG, "enter state: " + state.name());
this.state = state;
}
}
public void signupAndLogin(String user, String password, String nickname, byte[] avatar) throws SmackInvocationException {
connect();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("name", nickname);
try {
AccountManager.getInstance(con).createAccount(user, password, attributes);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
login(user, password);
vCardHelper.save(nickname, avatar);
}
public void sendChatMessage(String to, String body, PacketExtension packetExtension) throws SmackInvocationException {
Message message = new Message(to, Message.Type.chat);
message.setBody(body);
if (packetExtension != null) {
message.addExtension(packetExtension);
}
try {
con.sendPacket(message);
} catch (NotConnectedException e) {
throw new SmackInvocationException(e);
}
}
public List<RosterEntry> getRosterEntries() {
List<RosterEntry> result = new ArrayList<RosterEntry>();
Roster roster = con.getRoster();
Collection<RosterGroup> groups = roster.getGroups();
for (RosterGroup group : groups) {
result.addAll(group.getEntries());
}
return result;
}
and finally my menifest file
public UserProfile search(String username) throws SmackInvocationException {
String name = StringUtils.parseName(username);
String jid = null;
if (name == null || name.trim().length() == 0) {
jid = username + "#" + con.getServiceName();
} else {
jid = StringUtils.parseBareAddress(username);
}
if (vCardHelper == null) {
return null;
}
VCard vCard = vCardHelper.loadVCard(jid);
String nickname = vCard.getNickName();
return nickname == null ? null : new UserProfile(jid, vCard);
}
public String getNickname(String jid) throws SmackInvocationException {
VCard vCard = vCardHelper.loadVCard(jid);
return vCard.getNickName();
}
private void connect() throws SmackInvocationException {
if (!isConnected()) {
setState(State.CONNECTING);
if (con == null) {
con = createConnection();
}
try {
con.connect();
}catch (SmackException.NoResponseException er){
Log.e(LOG_TAG,"Norespponse exception");
}
catch(Exception e) {
Log.e(LOG_TAG, String.format("Unhandled exception %s", e.toString()), e);
startReconnectIfNecessary();
throw new SmackInvocationException(e);
}
}
}
#SuppressLint("TrulyRandom")
private XMPPConnection createConnection() {
ConnectionConfiguration config = new ConnectionConfiguration(PreferenceUtils.getServerHost(context), PORT);
SSLContext sc = null;
MemorizingTrustManager mtm = null;
try {
mtm = new MemorizingTrustManager(context);
sc = SSLContext.getInstance("TLS");
sc.init(null, new X509TrustManager[] { mtm }, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (KeyManagementException e) {
throw new IllegalStateException(e);
}
config.setCustomSSLContext(sc);
config.setHostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier()));
config.setSecurityMode(SecurityMode.required);
config.setReconnectionAllowed(false);
config.setSendPresence(false);
config.setSecurityMode(SecurityMode.disabled);
List<HostAddress> list = config.getHostAddresses();
boolean data = config.isSendPresence();
return new XMPPTCPConnection(config);
}
public void cleanupConnection() {
if (con != null) {
con.removePacketListener(messagePacketListener);
con.removePacketListener(presencePacketListener);
if (connectionListener != null) {
con.removeConnectionListener(connectionListener);
}
}
if (isConnected()) {
try {
con.disconnect();
} catch (NotConnectedException e) {}
}
}
private void onConnectionEstablished() {
if (state != State.CONNECTED) {
//processOfflineMessages();
try {
con.sendPacket(new Presence(Presence.Type.available));
} catch (NotConnectedException e) {}
contactHelper = new SmackContactHelper(context, con);
vCardHelper = new SmackVCardHelper(context, con);
fileTransferManager = new FileTransferManager(con);
OutgoingFileTransfer.setResponseTimeout(30000);
addFileTransferListener();
pingManager = PingManager.getInstanceFor(con);
pingManager.registerPingFailedListener(new PingFailedListener() {
#Override
public void pingFailed() {
// Note: remember that maybeStartReconnect is called from a different thread (the PingTask) here, it may causes synchronization problems
long now = new Date().getTime();
if (now - lastPing > 30000) {
Log.e(LOG_TAG, "Ping failure, reconnect");
startReconnectIfNecessary();
lastPing = now;
} else {
Log.e(LOG_TAG, "Ping failure reported too early. Skipping this occurrence.");
}
}
});
con.addPacketListener(messagePacketListener, new MessageTypeFilter(Message.Type.chat));
con.addPacketListener(presencePacketListener, new PacketTypeFilter(Presence.class));
con.addConnectionListener(createConnectionListener());
setState(State.CONNECTED);
broadcastState(State.CONNECTED);
MessageService.reconnectCount = 0;
}
}
private void broadcastState(State state) {
Intent intent = new Intent(ACTION_CONNECTION_CHANGED);
intent.putExtra(EXTRA_NAME_STATE, state.toString());
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
public void login(String username, String password) throws SmackInvocationException {
connect();
try {
if (!con.isAuthenticated()) {
con.login(username, password, RESOURCE_PART);
}
onConnectionEstablished();
} catch(Exception e) {
SmackInvocationException exception = new SmackInvocationException(e);
// this is caused by wrong username/password, do not reconnect
if (exception.isCausedBySASLError()) {
cleanupConnection();
} else {
startReconnectIfNecessary();
}
throw exception;
}
}
public String getLoginUserNickname() throws SmackInvocationException {
try {
return AccountManager.getInstance(con).getAccountAttribute("name");
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
private void processOfflineMessages() {
Log.i(LOG_TAG, "Begin retrieval of offline messages from server");
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
try {
if (!offlineMessageManager.supportsFlexibleRetrieval()) {
Log.d(LOG_TAG, "Offline messages not supported");
return;
}
List<Message> msgs = offlineMessageManager.getMessages();
for (Message msg : msgs) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());
context.startService(intent);
}
offlineMessageManager.deleteMessages();
} catch (Exception e) {
Log.e(LOG_TAG, "handle offline messages error ", e);
}
Log.i(LOG_TAG, "End of retrieval of offline messages from server");
}
private ConnectionListener createConnectionListener() {
connectionListener = new ConnectionListener() {
#Override
public void authenticated(XMPPConnection arg0) {}
#Override
public void connected(XMPPConnection arg0) {}
#Override
public void connectionClosed() {
Log.e(LOG_TAG, "connection closed");
}
#Override
public void connectionClosedOnError(Exception arg0) {
// it may be due to network is not available or server is down, update state to WAITING_TO_CONNECT
// and schedule an automatic reconnect
Log.e(LOG_TAG, "connection closed due to error ", arg0);
startReconnectIfNecessary();
}
#Override
public void reconnectingIn(int arg0) {}
#Override
public void reconnectionFailed(Exception arg0) {}
#Override
public void reconnectionSuccessful() {}
};
return connectionListener;
}
private void startReconnectIfNecessary() {
cleanupConnection();
setState(State.WAITING_TO_CONNECT);
if (NetworkUtils.isNetworkConnected(context)) {
context.startService(new Intent(MessageService.ACTION_RECONNECT, null, context, MessageService.class));
}
}
private boolean isConnected() {
return con != null && con.isConnected();
}
public void onNetworkDisconnected() {
setState(State.WAITING_FOR_NETWORK);
}
public void requestSubscription(String to, String nickname) throws SmackInvocationException {
contactHelper.requestSubscription(to, nickname);
}
public void approveSubscription(String to, String nickname, boolean shouldRequest) throws SmackInvocationException {
contactHelper.approveSubscription(to);
if (shouldRequest) {
requestSubscription(to, nickname);
}
}
public void delete(String jid) throws SmackInvocationException {
contactHelper.delete(jid);
}
public String loadStatus() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadStatus();
}
public VCard loadVCard(String jid) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard(jid);
}
public VCard loadVCard() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard();
}
public void saveStatus(String status) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
vCardHelper.saveStatus(status);
contactHelper.broadcastStatus(status);
}
public SubscribeInfo processSubscribe(String from) throws SmackInvocationException {
SubscribeInfo result = new SubscribeInfo();
RosterEntry rosterEntry = contactHelper.getRosterEntry(from);
ItemType rosterType = rosterEntry != null ? rosterEntry.getType() : null;
if (rosterEntry == null || rosterType == ItemType.none) {
result.setType(SubscribeInfo.TYPE_WAIT_FOR_APPROVAL);
result.setNickname(getNickname(from));
} else if (rosterType == ItemType.to) {
result.setType(SubscribeInfo.TYPE_APPROVED);
result.setNickname(rosterEntry.getName());
approveSubscription(from, null, false);
}
result.setFrom(from);
return result;
}
public void sendImage(File file, String to) throws SmackInvocationException {
if (fileTransferManager == null || !isConnected()) {
throw new SmackInvocationException("server not connected");
}
String fullJid = to + "/" + RESOURCE_PART;
OutgoingFileTransfer transfer = fileTransferManager.createOutgoingFileTransfer(fullJid);
try {
transfer.sendFile(file, file.getName());
} catch (SmackException e) {
Log.e(LOG_TAG, "send file error");
throw new SmackInvocationException(e);
}
while(!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
Log.d(LOG_TAG, "send file status: " + transfer.getStatus());
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
private void addFileTransferListener() {
fileTransferManager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
new Thread() {
#Override
public void run() {
IncomingFileTransfer transfer = request.accept();
String fileName = String.valueOf(System.currentTimeMillis());
File file = new File(FileUtils.getReceivedImagesDir(context), fileName + FileUtils.IMAGE_EXTENSION);
try {
transfer.recieveFile(file);
} catch (SmackException e) {
Log.e(LOG_TAG, "receive file error", e);
return;
}
while (!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
Log.e(LOG_TAG, "receive file error, " + transfer.getError());
return;
}
}
// start service to save the image to sqlite
if (transfer.getStatus().equals(Status.complete)) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(request.getRequestor()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, context.getString(R.string.image_message_body));
intent.putExtra(MessageService.EXTRA_DATA_NAME_FILE_PATH, file.getAbsolutePath());
intent.putExtra(MessageService.EXTRA_DATA_NAME_TYPE, ChatMessageTableHelper.TYPE_INCOMING_IMAGE);
context.startService(intent);
}
}
}.start();
}
});
}
public void onDestroy() {
cleanupConnection();
smackAndroid.onDestroy();
}
public static enum State {
CONNECTING,
CONNECTED,
DISCONNECTED,
// this is a state that client is trying to reconnect to server
WAITING_TO_CONNECT,
WAITING_FOR_NETWORK;
}
}
but i could not found any progress.please help me out. thanks in advance.
After struggle i found solution of this kind of problem. we need to do server side changes like:
step1:
step2:
step3:
after doing all these steps we will able to register new user on ejabberd server.

Async Task - Android Instrumentaion Unit testing - Exception - Only thread created can update the asynctask

This is my Asnyc task class
class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
private static final String TAG = "EndpointsAsyncTask";
private MainActivity activity;
private ProgressBar mProgressBar;
private Exception mError = null;
private JsonGetTaskListener mListener = null;
InterstitialAd mInterstitialAd;
public EndpointsAsyncTask setListener(JsonGetTaskListener listener) {
this.mListener = listener;
return this;
}
public static interface JsonGetTaskListener {
public void onComplete(String jsonString, Exception e);
}
public EndpointsAsyncTask(MainActivity activity,ProgressBar mProgressBar){
this.activity = activity;
this.mProgressBar= mProgressBar;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// mProgressBar = new ProgressBar(this.activity);
mInterstitialAd = new InterstitialAd(this.activity);
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
// end options for devappserver
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://backendversionone.appspot.com/_ah/api/");
// https://endpoint-backend-1056.appspot.com/_ah/api/
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name+"check").execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(context, result, Toast.LENGTH_LONG).show();
// mProgressBar.setVisibility(View.GONE);
if (this.mListener != null)
this.mListener.onComplete(result, mError);
mProgressBar.setVisibility(View.GONE);
Intent myIntent = new Intent(context, LibraryMainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
myIntent.putExtra("joke", result);
context.startActivity(myIntent);
}
}
Im trying to test my Async task from test class
Find my class below.
public class MainActivityTest extends ActivityInstrumentationTestCase2 {
private MainActivity mMainActivity;
private TextView mFirstTestText;
ProgressBar pbar;
String mJsonString = null;
Exception mError = null;
CountDownLatch signal = null;
public MainActivityTest() {
super(MainActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
mMainActivity = getActivity();
signal = new CountDownLatch(1);
}
#Override
protected void tearDown() throws Exception {
super.tearDown();
signal.countDown();
}
#MediumTest
public void testcheck(){
Log.d("Testing baby", "Testcheck");
Log.d("Testing baby","Testcheck");
Log.d("Testing baby", "Testcheck");
final Button sendToReceiverButton = (Button)
mMainActivity.findViewById(R.id.buttontelljoke);
assertNotNull(sendToReceiverButton);
}
#SmallTest
public void testchecks(){
Log.d("Testing baby", "Testcheck");
Log.d("Testing baby","Testcheck");
Log.d("Testing baby", "Testcheck");
final Button sendToReceiverButton = (Button)
mMainActivity.findViewById(R.id.buttontelljoke);
assertNotNull(sendToReceiverButton);
}
#MediumTest
public void testasyncTaskTest(){
pbar = (ProgressBar)mMainActivity.findViewById(progressBar1);
try {
EndpointsAsyncTask jokeTask = new EndpointsAsyncTask(mMainActivity,pbar);
jokeTask.setListener(new EndpointsAsyncTask.JsonGetTaskListener() {
#Override
public void onComplete(String jsonString, Exception e) {
mJsonString = jsonString;
mError = e;
signal.countDown();
}
}).execute((new Pair<Context, String>(getActivity(), "")));
signal.await();
assertNotNull(mJsonString);
} catch (Exception e){
fail("Timed out");
}
}
protected Fragment waitForFragment(String tag, int timeout) {
long endTime = SystemClock.uptimeMillis() + timeout;
while (SystemClock.uptimeMillis() <= endTime) {
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentByTag(tag);
if (fragment != null) {
return fragment;
}
}
return null;
}
When running the test case , This line throws exception - Only the created thread can update the Async task
jokeTask.setListener(new EndpointsAsyncTask.JsonGetTaskListener() {
#Override
public void onComplete(String jsonString, Exception e) {
mJsonString = jsonString;
mError = e;
signal.countDown();
}
}).execute((new Pair<Context, String>(getActivity(), "")));
signal.await();
But running the test when my phone is locked, I dont get exception and works fine.
How can i fix this issue.
Not sure if it will helps but try to call
mJsonString = jsonString;
mError = e;
signal.countDown();
in onUiTherad(Runnable)

loopj AsyncHttpClient more then 3 post not working

I am starting then 4 post after each other. But I catch only response from 3 of the 4 posts.
Can somebody explain to me why? I tried it also with get and it has the same problem. Am I doing the posts to quick after each other?
Resclient class:
public class RestClient {
private static AsyncHttpClient client = new AsyncHttpClient();
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
}
Webservice resolver:
public class WSBeer extends WSBase {
public WSBeer(OnWSRequestCompleted listener, Context context) {
super(listener, context);
}
public void getAll(String date) throws JSONException {
Tools.LOG_DEBUG("GetAllBeer");
RequestParams params = new RequestParams();
params.add("date", date);
RestClient.post(url, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Tools.LOG_DEBUG("WSBeer onSucces: " + response);
listener.onRestTaskCompleted(Constants.FUNCTION_DB_BEER, response);
}
#Override
public void onFailure(Throwable e, JSONArray errorResponse) {
Tools.LOG_DEBUG("WSBeer getAll: " + errorResponse);
handleError(e, errorResponse, null);
}
#Override
public void onFailure(Throwable e, JSONObject errorResponse) {
Tools.LOG_DEBUG("WSBeer getAll: " + errorResponse);
handleError(e, null, errorResponse);
}
});
}
}
SyncHandler class:
public class SyncHandler implements OnWSRequestCompleted {
private OnSyncListener listener;
private Context context;
private WSBeer wsBeer;
public SyncHandler(OnSyncListener listener, Context context) {
this.listener = listener;
this.context = context;
}
#Override
public void onRestTaskCompleted(int function, JSONObject response) {
switch (function) {
case Constants.FUNCTION_DB_BEER:
List<Beer> beerList = null;
try {
beerList = ResponseBeer.getAll(response);
} catch (IOException e) {
Tools.LOG_ERROR(e);
}
Tools.LOG_DEBUG("Beers");
if (beerList != null) {
new SaveBeerHelper(listener).execute(beerList.toArray(new Beer[beerList.size()]));
}
break;
}
}
public void syncBeer() {
wsBeer = new WSBeer(this, context);
try {
Tools.LOG_DEBUG("Start loading beer...");
String date = getSyncDate(Constants.FUNCTION_DB_BEER);
wsBeer.getAll(date);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getSyncDate(int databaseId) {
SyncData syncData = Shared.dbRepo.syncRepository.getById(databaseId);
if (syncData != null) {
Tools.LOG_DEBUG("SyncData: " + syncData.getSyncDate().toString());
return syncData.getSyncDate().toString();
} else {
new SyncData(databaseId).Save(Shared.dbRepo);
}
Tools.LOG_DEBUG("SyncData: ");
return "";
}
}
WEBSERVICE ACTION:
public function bierenAction()
{
$this->view->status = 204; //Nog geen content
if ($this->getRequest()->isPost()){
$date = $this->postParam('date');
if ($date != "") {
$bieren = self::$proxyBier->getBierenByUpdated($date);
} else {
$bieren = self::$proxyBier->getBieren();
}
} else {
$bieren = self::$proxyBier->getBieren();
}
$this->view->data = $bieren;
$this->view->status = 200; //Alles oke
$this->view->ajax();
}
Also you can use this instead https://github.com/leonardoxh/AsyncOkHttpClient this library just use OkHttpClient instead of Apache librarys, and this library is the base codes for Loopj AsyncHttpClient 2.0 (where the library will be re implemented with Square OkHttp)
I used the newer version of async-http library
compile 'com.loopj.android:android-async-http:1.4.5-SNAPSHOT'
and everything works like a charm :)

Categories

Resources