how to integrate google assistant in android for native application? - android

I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.
API.AI
Actions on Google
Tutorial of Google Assistant

First of all you need to train your model on API.AI to respond upon some text given to the model.
Some code with API.AI FYI:
//Initialize Service
private void initService(final LanguageConfig selectedLanguage) {
try {
final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
Log.w(TAG, "Sending" + textToSend);
final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
private AIError aiError;
#Override
protected void onPreExecute() {
super.onPreExecute();
showHideProgressBar(true);
if (mVoiceRecorder != null) {
mVoiceRecorder.pauseRecording();
}
}
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
if (!TextUtils.isEmpty(event)) {
request.setEvent(new AIEvent(event));
}
final String contextString = params[2];
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(contextString)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
requestExtras = new RequestExtras(contexts, null);
}
try {
Log.i("API AI Request", "" + request.toString());
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
showHideProgressBar(false);
speechSentStatus = false;
okSentStatus = false;
if (response != null) {
onResult(response, flag, textToSend);
} else {
onError(aiError);
}
}
};
if (flag == OPEN_COMPLAIN_CODE) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == OPEN_DIAGNOSIS_CODE) {
task.execute("", Config.Events[1], Config.Events[1]);
} else if (flag == Constants.OPEN_MEDICATION_CODE) {
task.execute("", Config.Events[2], Config.Events[2]);
} else if (flag == Constants.OPEN_LABTEST_CODE) {
task.execute("", Config.Events[3], Config.Events[3]);
} else if (flag == Constants.COMPLAINTS_ADDED) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
task.execute("", Config.Events[1], Config.Events[1]);
} else {
task.execute(textToSend, null, "");
}
}
//Based on result you can handle the business logic
private void onResult(final AIResponse response, final int flag, final String textToSend) {
runOnUiThread(new Runnable() {
#Override
public void run() {
apiAiResponseCounter = apiAiResponseCounter + 1;
isLast = false;
final Result result = response.getResult();
Log.w(TAG, "" + result.getFulfillment().getSpeech());
if (flag == Constants.COMPLAINTS_ADDED) {
//method you want to execute on receiving certain text from model
send(textToSend.toLowerCase(), DONTTEXT);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
send(textToSend.toLowerCase(), DONTTEXT);
} else {
String error = "";
final String speech = result.getFulfillment().getSpeech();
if (speech.contains("?")) {
if (!result.getAction().equalsIgnoreCase("input.unknown")) {
if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
//DONOTHING
} else {
digiMessage(speech, YESNO);
}
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
} else {
if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
digiMessage(speech, ChatMessageAdapter.DURATION);
} else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
digiMessage(speech, ChatMessageAdapter.FREQUENCY);
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
}
if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
if (result.isActionIncomplete() == true) {
playSpeech(speech);
} else {
speechBuffer = "";
speechBuffer = speech;
}
} else {
if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
isLast = true;
if (mVoiceRecorder != null) {
stopVoiceRecording();
}
} else {
playSpeech(speech);
}
}
}
}
});
if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
Log.w(TAG, "Skipped");
} else {
inflateUI(response.getResult());
}
}

Related

AppsFlyer Android onInstallConversionDataLoaded delay callback

Ok so i grabbed the code from AppsFlyer Cordova plugin:
AppsFlyerProperties.getInstance().set(AppsFlyerProperties.LAUNCH_PROTECT_ENABLED, false);
AppsFlyerLib instance = AppsFlyerLib.getInstance();
try{
final JSONObject options = args.getJSONObject(0);
devKey = options.optString(AF_DEV_KEY, "");
isConversionData = options.optBoolean(AF_CONVERSION_DATA, false);
if(devKey.trim().equals("")){
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NO_DEVKEY_FOUND));
}
isDebug = options.optBoolean(AF_IS_DEBUG, false);
instance.setDebugLog(isDebug);
if(isDebug == true){
System.out.println("AppsFlyer Here 0");
Log.d("AppsFlyer", "Starting Tracking");
}
trackAppLaunch();
instance.startTracking(c.getApplication(), devKey);
if(isConversionData == true){
if(mAttributionDataListener == null) {
mAttributionDataListener = callbackContext;
}
if(mConversionListener == null){
mConversionListener = callbackContext;
}
registerConversionListener(instance);
sendPluginNoResult(callbackContext);
}
else{
callbackContext.success(SUCCESS);
}
}
catch (JSONException e){
e.printStackTrace();
}
registerConversionListener
private void registerConversionListener(AppsFlyerLib instance){
instance.registerConversionListener(cordova.getActivity().getApplicationContext(), new AppsFlyerConversionListener(){
#Override
public void onAppOpenAttribution(Map<String, String> attributionData) {
}
#Override
public void onAttributionFailure(String errorMessage) {
handleError(AF_ON_ATTRIBUTION_FAILURE, errorMessage);
}
#Override
public void onInstallConversionDataLoaded(Map<String, String> conversionData) {
// Delay here up to some minutes
}
OnInstallCoversionDataLoaded callback is delayed up to some minutes. Can anyone advise how to fix this?

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.

Why my json data not following an order in API 16 and lower API?

Explanation:I have json.In which, i have object namely matches.Inside the matches object i have lot of objects.I mean data->season->matches->object1,2,3 so on.
This objects are dynamic it's not fixed at the run-time.I tried to parse the matches object.
Here is my json data
Now i tried to parse this file using my url.I was used a volley network library to parse the json file from server.
Here is my code to parse the json and get the response
public class SeriesActivity extends AppCompatActivity {
Toolbar toolbar;
String series_key = "";
String url = "";
String access_token = "";
FrameLayout frameLayout;
List<SeriesMatches> series_header;
HashMap<SeriesMatches, List<SeriesMatches>> series_child;
String winner_team = "";
String overs = "";
String wickets_now = "";
String now_runs = "";
String now_bat_team = "";
String fullScore = "";
String team_name = "";
String[] over_parts;
ExpandableListView expListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
frameLayout = (FrameLayout) findViewById(R.id.adbar);
new AddLoader(getApplicationContext()).LoadAds(frameLayout);
SharedPreferences sharedPreferences = this.getSharedPreferences("SaveTime", MODE_PRIVATE);
access_token = sharedPreferences.getString("accessToken", null);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
Intent intent = getIntent();
series_key = intent.getStringExtra("series_key");
url = "https://api.litzscore.com/rest/v2/season/" + series_key + "/?access_token=" + access_token + "&card_type=summary_card";
if (!Utils.isNetworkConnected(this)) {
dialog_popup();
} else {
getSeriesMatches();
}
}
public void getSeriesMatches() {
String str_req = "getSeries";
StringRequest matches_req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
try {
JSONObject object = new JSONObject(response);
if (!object.getBoolean("status") || object.getString("status_code").equals("403")) {
// DialogAbandoned abandoned=new DialogAbandoned(getApplicationContext());
// abandoned.setDialog("Series","Data Coming soon...");
} else {
series_header = new ArrayList<>();
series_child = new HashMap<>();
if (object.has("data") && !object.isNull("data")) {
JSONObject data = object.getJSONObject("data");
JSONObject season;
JSONObject matches;
if (data.has("season") && !data.isNull("season")) {
season = data.getJSONObject("season");
if (season.has("matches") && !season.isNull("matches")) {
matches = season.getJSONObject("matches");
JSONArray matches_arr = matches.names();
JSONObject matches_obj;
for (int i = 0; i < matches_arr.length(); i++) {
SeriesMatches s_matches = new SeriesMatches();
matches_obj = matches.getJSONObject(matches_arr.getString(i));
JSONObject teams = matches_obj.getJSONObject("teams");
JSONObject team_a = teams.getJSONObject("a");
JSONObject team_b = teams.getJSONObject("b");
JSONObject start_date = matches_obj.getJSONObject("start_date");
s_matches.setRealted_name(matches_obj.getString("related_name"));
series_header.add(s_matches);
if (!matches_obj.isNull("msgs") && matches_obj.has("msgs")) {
JSONObject msgs = matches_obj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
}
}
JSONObject now;
now_bat_team = "";
now_runs = "";
wickets_now = "";
overs = "";
if (matches_obj.has("now") && !matches_obj.isNull("now")) {
now = matches_obj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if (now.getString("runs_str").equals("null")) {
overs = "0";
} else {
over_parts = now.getString("runs_str").split(" ");
overs = over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
team_name = "";
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
if (matches_obj.has("status_overview") && !matches_obj.isNull("status_overview")) {
if (matches_obj.getString("status_overview").equals("abandoned") || matches_obj.getString("status_overview").equals("canceled")) {
fullScore = "";
} else {
fullScore = team_name + " - " + now_runs + "/" + wickets_now + " (" + overs + " ovr)";
}
}
SeriesMatches s2 = new SeriesMatches();
s2.setTeam_Aname(team_a.getString("short_name"));
s2.setTemm_Akey(team_a.getString("key"));
s2.setTeam_Bname(team_b.getString("short_name"));
s2.setTeam_Bkey(team_b.getString("key"));
s2.setStatus(matches_obj.getString("status"));
s2.setDate(start_date.getString("iso"));
s2.setVenue(matches_obj.getString("venue"));
s2.setMsgs(winner_team);
s2.setScore(fullScore);
s2.setMom(matches_obj.getString("man_of_match"));
List<SeriesMatches> matches_info = new ArrayList<>();
matches_info.add(s2);
series_child.put(series_header.get(i), matches_info);
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
ExpandedListAdapter adapter = new ExpandedListAdapter(getApplicationContext(), series_header, series_child);
expListView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog_popup();
} else if (error instanceof AuthFailureError) {
dialog_popup();
} else if (error instanceof ServerError) {
dialog_popup();
} else if (error instanceof NetworkError) {
dialog_popup();
} else if (error instanceof ParseError) {
dialog_popup();
}
}
});
AppController.getInstance().addToRequestQueue(matches_req, str_req);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is my Expnadedlistview
public class ExpandedListAdapter extends BaseExpandableListAdapter{
private Context context;
private List<SeriesMatches> series_header;
private HashMap<SeriesMatches,List<SeriesMatches>> series_child;
private Typeface tf;
public ExpandedListAdapter(Context context,List<SeriesMatches> series_header,HashMap<SeriesMatches,List<SeriesMatches>> series_child){
this.context=context;
this.series_header=series_header;
this.series_child=series_child;
}
#Override
public int getGroupCount() {
return this.series_header.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this.series_header.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_group,null);
}
TextView text_group=(TextView)convertView.findViewById(R.id.lblListHeader);
SeriesMatches s=series_header.get(groupPosition);
text_group.setText(s.getRealted_name());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_child,null);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
}
TextView teamA=(TextView)convertView.findViewById(R.id.txt_one_country_name);
TextView teamB=(TextView)convertView.findViewById(R.id.txt_two_country_name);
TextView txt_venue=(TextView)convertView.findViewById(R.id.venue);
TextView txtTimeIST=(TextView)convertView.findViewById(R.id.txt_timeist);
TextView txtTimeGMT=(TextView)convertView.findViewById(R.id.txt_timegmt);
TextView txtDate=(TextView)convertView.findViewById(R.id.txt_date);
ImageView team_one_flag_icon=(ImageView)convertView.findViewById(R.id.team_one_flag_icon);
ImageView team_two_flag_icon=(ImageView)convertView.findViewById(R.id.team_two_flag_icon);
SeriesMatches s1=series_child.get(series_header.get(groupPosition)).get(childPosition);
String team_a_key=s1.getTemm_Akey();
String team_b_key=s1.getTeam_Bkey();
teamA.setText(s1.getTeam_Aname());
teamB.setText(s1.getTeam_Bname());
if(team_a_key.equals("ind")) {
team_one_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_a_key.equals("omn")){
team_one_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_a_key.equals("afg")) {
team_one_flag_icon.setImageResource(R.drawable.afg);
} else if(team_a_key.equals("aus")) {
team_one_flag_icon.setImageResource(R.drawable.aus);
} else if(team_a_key.equals("ban")) {
team_one_flag_icon.setImageResource(R.drawable.ban);
} else if(team_a_key.equals("eng")) {
team_one_flag_icon.setImageResource(R.drawable.eng);
} else if(team_a_key.equals("hkg")) {
team_one_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_a_key.equals("ire")) {
team_one_flag_icon.setImageResource(R.drawable.ire);
} else if(team_a_key.equals("nl")) {
team_one_flag_icon.setImageResource(R.drawable.nl);
} else if(team_a_key.equals("nz")) {
team_one_flag_icon.setImageResource(R.drawable.nz);
} else if(team_a_key.equals("pak")) {
team_one_flag_icon.setImageResource(R.drawable.pak);
} else if(team_a_key.equals("rsa")) {
team_one_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_a_key.equalsIgnoreCase("sl")) {
team_one_flag_icon.setImageResource(R.drawable.sl);
} else if (team_a_key.equals("uae")) {
team_one_flag_icon.setImageResource(R.drawable.uae);
} else if (team_a_key.equals("wi")) {
team_one_flag_icon.setImageResource(R.drawable.wi);
} else if (team_a_key.equals("zim")) {
team_one_flag_icon.setImageResource(R.drawable.zim);
} else if(team_a_key.equals("sct")) {
team_one_flag_icon.setImageResource(R.drawable.sct);
////////// IPL Team ///////////
} else if(team_a_key.equals("dd")) {
team_one_flag_icon.setImageResource(R.drawable.dd);
} else if(team_a_key.equals("kkr")) {
team_one_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_a_key.equals("mi")) {
team_one_flag_icon.setImageResource(R.drawable.mi);
} else if(team_a_key.equals("srh")) {
team_one_flag_icon.setImageResource(R.drawable.sh);
} else if(team_a_key.equals("kxip")) {
team_one_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_a_key.equals("rcb")) {
team_one_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_a_key.equals("rps")) {
team_one_flag_icon.setImageResource(R.drawable.rps);
} else if(team_a_key.equals("gl")) {
team_one_flag_icon.setImageResource(R.drawable.gl);
} else {
team_one_flag_icon.setImageResource(R.drawable.dft);
}
//for B TEAM
if(team_b_key.equals("ind")) {
team_two_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_b_key.equals("omn")){
team_two_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_b_key.equals("afg")) {
team_two_flag_icon.setImageResource(R.drawable.afg);
} else if(team_b_key.equals("aus")) {
team_two_flag_icon.setImageResource(R.drawable.aus);
} else if(team_b_key.equals("ban")) {
team_two_flag_icon.setImageResource(R.drawable.ban);
} else if(team_b_key.equals("eng")) {
team_two_flag_icon.setImageResource(R.drawable.eng);
} else if(team_b_key.equals("hkg")) {
team_two_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_b_key.equals("ire")) {
team_two_flag_icon.setImageResource(R.drawable.ire);
} else if(team_b_key.equals("nl")) {
team_two_flag_icon.setImageResource(R.drawable.nl);
} else if(team_b_key.equals("nz")) {
team_two_flag_icon.setImageResource(R.drawable.nz);
} else if(team_b_key.equals("pak")) {
team_two_flag_icon.setImageResource(R.drawable.pak);
} else if(team_b_key.equals("rsa")) {
team_two_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_b_key.equalsIgnoreCase("sl")) {
team_two_flag_icon.setImageResource(R.drawable.sl);
} else if (team_b_key.equals("uae")) {
team_two_flag_icon.setImageResource(R.drawable.uae);
} else if (team_b_key.equals("wi")) {
team_two_flag_icon.setImageResource(R.drawable.wi);
} else if (team_b_key.equals("zim")) {
team_two_flag_icon.setImageResource(R.drawable.zim);
} else if(team_b_key.equals("sct")) {
team_two_flag_icon.setImageResource(R.drawable.sct);
////////// IPL ///////////
} else if(team_b_key.equals("dd")) {
team_two_flag_icon.setImageResource(R.drawable.dd);
} else if(team_b_key.equals("kkr")) {
team_two_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_b_key.equals("mi")) {
team_two_flag_icon.setImageResource(R.drawable.mi);
} else if(team_b_key.equals("srh")) {
team_two_flag_icon.setImageResource(R.drawable.sh);
} else if(team_b_key.equals("kxip")) {
team_two_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_b_key.equals("rcb")) {
team_two_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_b_key.equals("rps")) {
team_two_flag_icon.setImageResource(R.drawable.rps);
} else if(team_b_key.equals("gl")) {
team_two_flag_icon.setImageResource(R.drawable.gl);
} else {
team_two_flag_icon.setImageResource(R.drawable.dft);
}
try {
String[] fullDate;
String fullTime = "";
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'+00':ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("hh:mm a");
String ist=outputFormat.format(utcFormat.parse(s1.getDate()));
Date timestamp;
timestamp = utcFormat.parse(s1.getDate());
fullDate = timestamp.toString().split(" ");
String monthName = fullDate[1];
String Dayname = fullDate[2];
fullTime = fullDate[3];
String[] gmt_fulldate = s1.getDate().split("T");
String gmt_time = gmt_fulldate[1];
String[] gmt_hour_parts = gmt_time.split("\\+");
String finalDate = Dayname + " " + monthName;
String finalTimeIST = ist + " IST | " + gmt_hour_parts[0] + " GMT";
String[] venue_parts=s1.getVenue().split(",");
int length=venue_parts.length;
if(length==1){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
txtTimeGMT.setText(venue_parts[0]);
}
if(length==2){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
txtTimeGMT.setText(venue_parts[0] + "," + venue_parts[1]);
}
if(length==3){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[1] + "," + venue_parts[2]);
}
if(length==4){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[2] + "," + venue_parts[3]);
}
if(s1.getStatus().equals("notstarted")){
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
txtDate.setTypeface(tf);
txtDate.setText("Started on " + finalDate);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(finalTimeIST);
}
if(s1.getStatus().equals("completed")){
txtDate.setTypeface(tf);
txtDate.setText(s1.getScore());
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(s1.getMsgs());
Log.e("NOTSTARTED","DONE");
txt_venue.setText("MOM : "+s1.getMom().substring(0, 1).toUpperCase() + s1.getMom().substring(1).replace("_", " "));
}
}
catch (ParseException e){
e.printStackTrace();
}
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Problem is i have mobile in which jellybean is installed.In the jellybean or lower of jellybean it's not comes in the order.If same code i ran into lollipop or marshmallow it's comes into the order.Order like
trieseries_2016_g1
trieseries_2016_g2
until trieseries_2016_final
Here is a screenshort of marshmallow
please, help me to solve out this problem.
Here is a sceenshort of jellybean

How to check timeout when load data from sever with Gson

new JSONData().execute(LinkData.HOME,LinkData.HOT,LinkData.NEW,LinkData.LIST_CATEGORY);
private class JSONData extends AsyncTask<String, Void, JSONArrayData> {
#Override
protected void onPreExecute() {
loading = true;
super.onPreExecute();
}
#Override
protected JSONArrayData doInBackground(String... params) {
CanBackPress = false;
URL url;
try {
for (int i = 0; i < params.length; i++) {
if (checkInternet.checkMobileInternetConn()) {
url = new URL(params[i]);
InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8");
if (i == 0) {
Post[] post;
post = new Gson().fromJson(reader, Post[].class);
for (Post p : post) {
data.getData().get(0).add(p);
// Log.d("post", "" + post.length);
Methods.savePostData(getBaseContext(), arrName[0], p);
}
}
if (i == 1) {
Post[] post;
post = new Gson().fromJson(reader, Post[].class);
for (Post p : post) {
data.getData().get(1).add(p);
Methods.savePostData(getBaseContext(), arrName[3], p);
Methods.savePostData(getBaseContext(), arrName[1], p);
}
}
if (i == 2) {
Post[] post;
post = new Gson().fromJson(reader, Post[].class);
for (Post p : post) {
data.getData().get(2).add(p);
Methods.savePostData(getBaseContext(), arrName[2], p);
}
}
if (i == 3) {
Zone[] zone;
zone = new Gson().fromJson(reader, Zone[].class);
for (Zone z : zone) {
data.getZoneList().get(0).add(z);
listCategory.add(z);
}
}
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(JSONArrayData d) {
super.onPostExecute(d);
CanBackPress = true;
stopThread = true;
intent.putExtra("MyData", d);
// if (d.getData().get(0).size() == 0 || d.getData().get(1).size() == 0 || d.getZoneList().get(0).size() == 0) {
// Log.d("LOI","LOI");
// showDialog();
// } else {
// neu tu push
if (toNotify) {
Log.d("eu tu push", "eu tu push");
startActivity(intent);
finish();
} else {
loading = false;
loadfn = true;
if (clickFalse == 0 && clickTrue == 0) {
Log.d("boqua","boqua");
//checkbox2();
stopThread = true;
startActivity(intent);
finish();
} else if (login) {
Log.d("facebook","facebook");
stopThread = true;
startActivity(intent);
finish();
}
}
}
}
I loaded data Json from sever with Gson. Now I want check for errors with the following cases:
- timeout (most important)
- if Json null or Non-standard
How I to do it?
My code load data
and I call it with :
As you can see from this answer, the Exception thrown for time out is java.net.SocketTimeoutException

How to stop Get data when orientation changes for selecting Checkbox

In my screen i am showing checkboxes with response of using GET when it is getting 0 means setchecked(false) and when it is getting 1 means setchecked(true).
Problem:
Consider when i am selected Multiple checkboxes and changed my
orientation the fragment is getting reloaded and it binding data from
GET method .How to overcome this problem .I am posting my code on
below .
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(savedInstanceState!=null)
{
cBox_furnishing.setChecked(savedInstanceState.getBoolean("Furnish"));
cBox_washMachine.setChecked(savedInstanceState.getBoolean("washMachine"));
cBox_ac.setChecked(savedInstanceState.getBoolean("ac"));
cBox_microwaveOven.setChecked(savedInstanceState.getBoolean("microwaveOven"));
cBox_ctv.setChecked(savedInstanceState.getBoolean("ctv"));
cBox_refrigerator.setChecked(savedInstanceState.getBoolean("refrigerator"));
cBox_tw.setChecked(savedInstanceState.getBoolean("tw"));
cBox_music.setChecked(savedInstanceState.getBoolean("music"));
cBox_pc.setChecked(savedInstanceState.getBoolean("pc"));
cBox_car.setChecked(savedInstanceState.getBoolean("car"));
}
Fragment_resident_info.leadno = getArguments().getString("LeadNo");
getdata();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
b_furnishing_CHECK = cBox_furnishing.isChecked();
b_washMachine_CHECK = cBox_washMachine.isChecked();
b_ac_CHECK = cBox_ac.isChecked();
b_microwaveOven_CHECK = cBox_microwaveOven.isChecked();
b_ctv_CHECK = cBox_ctv.isChecked();
b_refrigerator_CHECK = cBox_refrigerator.isChecked();
b_tw_CHECK = cBox_tw.isChecked();
b_music_CHECK = cBox_music.isChecked();
b_pc_CHECK = cBox_pc.isChecked();
b_car_CHECK = cBox_car.isChecked();
savedInstanceState.putBoolean("Furnish", b_furnishing_CHECK);
savedInstanceState.putBoolean("washMachine", b_washMachine_CHECK);
savedInstanceState.putBoolean("ac", b_ac_CHECK);
savedInstanceState.putBoolean("microwaveOven", b_microwaveOven_CHECK);
savedInstanceState.putBoolean("ctv", b_ctv_CHECK);
savedInstanceState.putBoolean("refrigerator", b_refrigerator_CHECK);
savedInstanceState.putBoolean("tw", b_tw_CHECK);
savedInstanceState.putBoolean("music", b_music_CHECK);
savedInstanceState.putBoolean("pc", b_pc_CHECK);
savedInstanceState.putBoolean("car", b_car_CHECK);
super.onSaveInstanceState(savedInstanceState);
}
private BroadcastReceiver reciever_assetseen = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
String response = intent.getStringExtra("httpResponse");
try
{
JSONArray ary = new JSONArray(response);
JSONObject obj = ary.getJSONObject(0);
String st_furnishing = obj.getString("Residence_Furnish");
String st_washingmachine = obj.getString("Washing_Machine");
String st_Ac = obj.getString("AC");
String st_microwaveoven = obj.getString("Microwave_Oven");
String st_ctv = obj.getString("CTV");
String st_refridge = obj.getString("Refrigerator");
String st_tw = obj.getString("TW");
String st_music = obj.getString("Music");
String st_pc = obj.getString("PC");
String st_car = obj.getString("CAR");
if(b_furnishing_CHECK == true)
{
cBox_furnishing.setChecked(true);
}
else if(st_furnishing.equals("0") || st_furnishing.equals("null") )
{
cBox_furnishing.setChecked(false);
}
else
{
cBox_furnishing.setChecked(true);
}
if(b_washMachine_CHECK == true)
{
cBox_washMachine.setChecked(true);
}
else if(st_washingmachine.equals("0") || st_washingmachine.equals("null") )
{
cBox_washMachine.setChecked(false);
}
else
{
cBox_washMachine.setChecked(true);
}
if( b_ac_CHECK == true)
{
cBox_ac.setChecked(true);
}
else if(st_Ac.equals("0")|| st_Ac.equals("null"))
{
cBox_ac.setChecked(false);
}
else
{
cBox_ac.setChecked(true);
}
if( b_microwaveOven_CHECK == true)
{
cBox_microwaveOven.setChecked(true);
}
else if(st_microwaveoven.equals("0") || st_microwaveoven.equals("null") )
{
cBox_microwaveOven.setChecked(false);
}
else
{
cBox_microwaveOven.setChecked(true);
}
if( b_ctv_CHECK == true)
{
cBox_ctv.setChecked(true);
}
else if(st_ctv.equals("0")|| st_ctv.equals("null") )
{
cBox_ctv.setChecked(false);
}
else
{
cBox_ctv.setChecked(true);
}
if( b_refrigerator_CHECK == true)
{
cBox_refrigerator.setChecked(true);
}
else if(st_refridge.equals("0")|| st_refridge.equals("null") )
{
cBox_refrigerator.setChecked(false);
}
else
{
cBox_refrigerator.setChecked(true);
}
if( b_tw_CHECK == true)
{
cBox_tw.setChecked(true);
}
else if(st_tw.equals("0")|| st_tw.equals("null") )
{
cBox_tw.setChecked(false);
}
else
{
cBox_tw.setChecked(true);
}
if( b_music_CHECK == true)
{
cBox_music.setChecked(true);
}
else if(st_music.equals("0")|| st_music.equals("null"))
{
cBox_music.setChecked(false);
}
else
{
cBox_music.setChecked(true);
}
if( b_pc_CHECK == true)
{
cBox_pc.setChecked(true);
}
else if(st_pc.equals("0")|| st_pc.equals("null") )
{
cBox_pc.setChecked(false);
}
else
{
cBox_pc.setChecked(true);
}
if( b_car_CHECK == true)
{
cBox_car.setChecked(true);
}
else if(st_car.equals("0")|| st_car.equals("null"))
{
cBox_car.setChecked(false);
}
else
{
cBox_car.setChecked(true);
}
}
catch(Exception e)
{
}
}
};
if(savedInstanceState!=null)
{
cBox_furnishing.setChecked(savedInstanceState.getBoolean("Furnish"));
cBox_washMachine.setChecked(savedInstanceState.getBoolean("washMachine"));
cBox_ac.setChecked(savedInstanceState.getBoolean("ac"));
cBox_microwaveOven.setChecked(savedInstanceState.getBoolean("microwaveOven"));
cBox_ctv.setChecked(savedInstanceState.getBoolean("ctv"));
cBox_refrigerator.setChecked(savedInstanceState.getBoolean("refrigerator"));
cBox_tw.setChecked(savedInstanceState.getBoolean("tw"));
cBox_music.setChecked(savedInstanceState.getBoolean("music"));
cBox_pc.setChecked(savedInstanceState.getBoolean("pc"));
cBox_car.setChecked(savedInstanceState.getBoolean("car"));
}else{
Fragment_resident_info.leadno = getArguments().getString("LeadNo");
getdata();
}

Categories

Resources