How to replace nested callbacks (Testing.java) for easy reading like this:
if(isValidGenderID() && isValidReligionID() && isValidMaritalID()){
// DO PRIMARY TASK
}
Nested callbacks are too deep, making the program not easy to read!. How to resolved this problem?
//PersonValidation.java
public static void isValidGenderID(#NonNull Context context, int genderID, final IGenderDataSource.IIsExistGenderIDCallback callback) {
GenderDataSource.getInstance(context).isExistGenderID(genderID, new IGenderDataSource.IIsExistGenderIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
public static void isValidReligionID(#NonNull Context context, int religionID, final IReligionDataSource.IIsExistReligionIDCallback callback) {
ReligionDataSource.getInstance(context).isExistReligionID(religionID, new IReligionDataSource.IIsExistReligionIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
public static void isValidMaritalID(#NonNull Context context, int maritalID, final IMaritalDataSource.IIsExistMaritalIDCallback callback) {
MaritalDataSource.getInstance(context).isExistMaritalID(maritalID, new IMaritalDataSource.IIsExistMaritalIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
// GenderDataSource.java
#Override
public void isExistGenderID(final int ID, #NonNull final IIsExistGenderIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// ReligionDataSource.java
#Override
public void isExistReligionID(final int ID, #NonNull final IIsExistReligionIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// MaritalDataSource.java
#Override
public void isExistMaritalID(final int ID, #NonNull final IIsExistMaritalIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// Testing.java (Nested calls are too deep, making the program not easy to read)
#Override
public void createCustomer(#NonNull final Customer customer, #NonNull final ICustomerDataSource.ICreateCustomerCallback callback) {
//
// isValidGenderID?
//
isValidGenderID(context, customer.getGenderID(), new IGenderDataSource.IIsExistGenderIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// isValidReligionID?
//
isValidReligionID(context, customer.getReligionID(), new IReligionDataSource.IIsExistReligionIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// isValidMaritalID?
//
isValidMaritalID(context, customer.getMaritalID(), new IMaritalDataSource.IIsExistMaritalIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// DO PRIMARY TASK
//
} else {
callback.onFailure("Marital is not valid");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
//
} else {
callback.onFailure("Religion is not valid!");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
//
} else {
callback.onFailure("Gender is not valid!");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
Related
I am trying to make a fan made of an app but when I want to create a constructor with the AsyncRun interface class it gives me 2 errors that it is not a class and I am stuck on that
This is all the code of MultiThreadHelper
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import com.bluesquare.center.provider.MultiThreadHelper;
public class MultiThreadHelper {
public interface AsyncRun<T> {
void onError(Throwable th);
T onExecute();
void onSuccess(T t);
}
public static class Helper {
private static final Helper instance = new Helper();
private Handler handler;
private Handler mainHandler;
private Helper() {
HandlerThread handlerThread = new HandlerThread("MutiThreadHelper");
handlerThread.start();
this.handler = new Handler(handlerThread.getLooper());
this.mainHandler = new Handler(Looper.getMainLooper());
}
public void post(Runnable runnable) {
this.handler.post(runnable);
}
public void postOnMainThread(Runnable runnable) {
this.mainHandler.post(runnable);
}
public void a(final AsyncRun asyncRun) {
try {
final Object onExecute = asyncRun.onExecute();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onSuccess(onExecute);
}
});
} catch (Exception e2) {
e2.printStackTrace();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onError(e2);
}
});
}
}
public <T> void post(final AsyncRun<T> asyncRun) {
this.handler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.Helper.this.a(asyncRun);
}
});
}
}
public static void post(Runnable runnable) {
Helper.instance.post(runnable);
}
public static void postOnMainThread(Runnable runnable) {
Helper.instance.postOnMainThread(runnable);
}
public static <T> void post(AsyncRun<T> asyncRun) {
Helper.instance.post(asyncRun);
}
And this is the part where I get the 2 errors
public void a(final AsyncRun asyncRun) {
try {
final Object onExecute = asyncRun.onExecute();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onSuccess(onExecute);
}
});
} catch (Exception e2) {
e2.printStackTrace();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onError(e2);
}
});
}
}
What am I doing wrong or is there a solution?
I get error when I set SPR.startlistenening() method I want to use continuously speech recognition and perform tasks based on results.
I am making an app that countinuously uses speech recognition and do specific task on results:
#Override
protected void onStart() {
super.onStart();
setSPR();
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
SPR.startListening(intent);
}
private void setSPR() {
if (SpeechRecognizer.isRecognitionAvailable(this)){
SpeechRecognizer.createSpeechRecognizer(this);
SPR.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> results = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
setRecognitionResults(results.get(0));
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) { }
});
}
}
Error >>>
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.speech.SpeechRecognizer.startListening(android.content.Intent)'
on a null object reference at
com.teamdev.talkingtorch.MainActivity.onStart(MainActivity.java:74) at
android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1341)
at android.app.Activity.performStart(Activity.java:7278) at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2937)
I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.
My code:
public class MainActivity extends AppCompatActivity {
private class Testing extends IOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
}
Thankss
I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.
Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507
public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);
public AppCompactIOIOActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.helper_.create();
}
protected void onDestroy() {
this.helper_.destroy();
super.onDestroy();
}
protected void onStart() {
super.onStart();
this.helper_.start();
}
protected void onStop() {
this.helper_.stop();
super.onStop();
}
#SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if((intent.getFlags() & 268435456) != 0) {
this.helper_.restart();
}
}
protected IOIOLooper createIOIOLooper() {
throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}
public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
return this.createIOIOLooper();
}
}
Then in your MainActivity
public class MainActivity extends AppCompactIOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
Don't forget to add your resources and dependances from IOIO developers. Good luck!
Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key
Here is below link i had tried nothing worked:
How to update the values in Table using Realm android?
Update mutiple rows in table using Realm in Android
public class Chat_history extends AppCompatActivity {
#BindView(R.id.chat_history_toolbar)
CustomToolbar chat_history_toolbar;
#BindView(R.id.sendmessgae)
CustomEditText sendmessgae;
#BindView(R.id.chat_history_list)
ListView chat_history_list;
Chat_history_Adapter chathisadapter;
RealmResults<Chat_history_pojo> chathistorylist;
Realm chatrealm;
BroadcastReceiver chatreceiver;
public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
#Override
public void onChange(Object element) {
chathisadapter.addmessage(chathistorylist);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_history);
ButterKnife.bind(this);
Realm.init(getApplicationContext());
setSupportActionBar(chat_history_toolbar);
assert getSupportActionBar() != null;
**chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
for (Chat_history_pojo chtapojo:registrationRealm) {
chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.copyToRealm(registrationRealm);
}
chatrealm.commitTransaction();**
chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
chat_history_list.setStackFromBottom(true);
chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
chat_history_list.setAdapter(chathisadapter);
/*chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Constant.l("Realm Update Called");
RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
for(Chat_history_pojo updatepojo:updatehispojo){
updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.insertOrUpdate(updatepojo);
chathisadapter.notifyDataSetChanged();
}
}
});*/
sendmessgae.setDrawableClickListener(new DrawableClickListener() {
#Override
public void onClick(DrawablePosition target) {
switch (target) {
case RIGHT:
if (sendmessgae.getText().toString().isEmpty()) {
Constant.t(getApplicationContext(), "Please Enter Message");
} else {
sendmessage();
}
break;
default:
break;
}
}
});
if (getIntent().hasExtra("mtype")) {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
} else {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
}
chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
#Override
public void onClick(View view) {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
});
chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
startActivity(chathisintent);
}
});
chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
#Override
public void onClick(View v) {
chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
deleteresults.deleteAllFromRealm();
}
});
}
});
chatreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
chatupdatepojo.setType("text");
if (intent.getStringExtra("type").equals("image")) {
chatupdatepojo.setType("image");
} else if (intent.getStringExtra("type").equals("text")) {
chatupdatepojo.setType("text");
}
chatrealm.commitTransaction();
chatrealm.close();
}
};
IntentFilter intfil = new IntentFilter(BroadCastAction);
registerReceiver(chatreceiver, intfil);
}
#Override
protected void onDestroy() {
unregisterReceiver(chatreceiver);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
chatrealm.addChangeListener(chatupdatelisterner);
Session.pushnotification(getApplicationContext());
}
#Override
protected void onStop() {
super.onStop();
chatrealm.removeChangeListener(chatupdatelisterner);
Session.removepushnotification(getApplicationContext());
}
#OnClick(R.id.camera)
public void camera() {
TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
.setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
#Override
public void onImageSelected(Uri uri) {
try {
Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
} catch (IOException e) {
Constant.l(e.toString());
}
}
})
.setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
.create();
bottomSheetDialogFragment.show(getSupportFragmentManager());
}
private void sendimages(String sid, String rid, Bitmap sendbitmap) {
Constant.showloader(Chat_history.this);
String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
Constant.l(sendumageurl);
AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
Constant.l(String.valueOf(response));
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(response.getString("url"));
chatupdatepojo.setType("image");
chatrealm.commitTransaction();
chatrealm.close();
}
} catch (JSONException e) {
Constant.l(e.toString());
Constant.dismissloader();
}
Constant.dismissloader();
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
Constant.dismissloader();
}
});
}
#Override
public void onBackPressed() {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
private void sendmessage() {
String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
Constant.l(schatsendmesg);
AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setMessage(sendmessgae.getText().toString());
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setType("text");
chatrealm.commitTransaction();
chatrealm.close();
sendmessgae.setText("");
}
} catch (JSONException e) {
Constant.l(e.toString());
}
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
Session.pushnotification(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
Session.removepushnotification(getApplicationContext());
}
}
Try this way of updation.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//Here i am checking the condition
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);
//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();
//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);
//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();
If you need to update all, then get a RealmResults object and iterate through
RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();
NOTE:
When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.
Realm reference
Following is my class which uses a CountDownLatch and ExecutorService. I all startTest method from my activity. When I run this code CountdownLatch doesn't come out of wait.
public class Test implements Tester.StartListener, Tester.StopListener, Runnable{
private CountDownLatch latch;
ExecutorService executorService;
Context context;
ListElement listElement;
int countDown;
final String user = "palapi_android#tourmalinelabs.com";
public Test(Context context) {
this.context = context;
this.listElement = listElement;
}
public void startTest(int nTimes) throws InterruptedException {
this.countDown = nTimes;
executorService = Executors.newSingleThreadExecutor();
latch = new CountDownLatch(countDown);
executorService.execute(this);
latch.await();
}
#Override
public void run() {
setText("Running");
Tester.Start(context, user, this);
}
#Override
public void OnStarted() {
Tester.Stop(context, this);
}
#Override
public void OnFail( int reason ) {
Log.d("Failure", "failed because " + reason);
}
#Override
public void OnStopped() {
setText(String.valueOf(countDown));
countDown --;
latch.countDown();
if( countDown >= 0) {
runAfterDelayInRange(new Runnable() {
#Override
public void run() {
Tester.Start(context, user, Test.this);
}
});
} else {
setText("Done");
}
}
protected void setText(final String text) {
getHandler().post(new Runnable() {
#Override
public void run() {
if (listElement != null) {
listElement.setTestResult(text);
}
LauncherActivity activity = (LauncherActivity) context;
activity.notifyDataSetChanged();
}
});
}
protected void runAfterDelayInRange(Runnable action) {
getHandler().post(action);
}
private Handler getHandler(){
return new Handler(context.getMainLooper());
}
}
Can someone please tell me what am I doing wrong? Thank you in advance