In my App i have added Observable method in menuitemclicked but it's working when i'm clicking it twice . on Single press. method is not working but button is working fine any suggestion for this or any changes in method .
case R.id.upload:
fetch()
break;
io.reactivex.Observable fetchObservable() {
return io.reactivex.Observable.create(new ObservableOnSubscribe<Data>() {
#Override
public void subscribe(ObservableEmitter<Data> emitter) throws Exception {
try {
final Cursor cursor = getActivity().getContentResolver().query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{"display_name", "data1"}, null, null, null);
// final Map contact =new HashMap();
while (cursor.moveToNext()) {
Data data = new Data();
try {
String name = cursor.getString(cursor.getColumnIndex(Display_name));
String number = cursor.getString(cursor.getColumnIndex(Data1));
data.setContact_name(name);
data.setNumber(number);
Thread.sleep(60);
emitter.onNext(data);
} catch (Exception e) {
Toast.makeText(context, "not insert , Toast.LENGTH_SHORT).show();
}
}
emitter.onComplete();
}catch (Exception e){
emitter.onError(e);
}
}
});
// fetching method code
void fetch(){
fetchObservable().subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Data data) {
data.Contact_name=data.getContact_name();
data.number=data.getNumber();
String name= data.Contact_name;
String number= data.number;
}
count++;
textprogress.setText(String.valueOf(count));
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
});
}
Because u are not Running your UI in main thread
like this
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
textprogress.setVisibility(View.VISIBLE);
textprogress.setVisibility(View.VISIBLE);
}
});
Related
I am making app where users can chat with each other in app , but the problem is when user send message it doesn't appear in chat box until user refresh the activity . how can i update chat without refresh ?
this is my code
ParseQuery<Message> parseQuery = ParseQuery.getQuery(Message.class);
subscriptionHandling = parseLiveQueryClient.subscribe(parseQuery);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, new SubscriptionHandling.HandleEventCallback<Message>() {
#Override
public void onEvent(ParseQuery<Message> query, final Message message) {
// HANDLING create event
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mList.add(message);
msgAdapter.notifyDataSetChanged();
show_message.scrollToPosition(mList.size() - 1);
}
});
public void onEvent(ParseQuery<Message> query, Message message) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mList.clear();
getData();
}
});
public void onClick(View v) {
Message msg = parseMessenger.SendMessage(send_txt.getText().toString(), null, new SaveCallback() {
#Override
public void done(ParseException e) {
send_txt.setText("");
}
}, new SendCallback() {
#Override
public void done(ParseException e) {
}
});
if (mList == null) {
mList = new ArrayList<Message>();
}
}
});
getData();
private void getData() {
ParseQuery<Message> messageFromQuery = Message.getAllMessage();
messageFromQuery.whereEqualTo(Message.COL_USER_FROM, userFrom);
messageFromQuery.whereEqualTo(Message.COL_USER_TO, userTo);
ParseQuery<Message> messageToQuery = Message.getAllMessage();
messageToQuery.whereEqualTo(Message.COL_USER_TO, userFrom);
messageToQuery.whereEqualTo(Message.COL_USER_FROM, userTo);
List<ParseQuery<Message>> messageQueries = new ArrayList<ParseQuery<Message>>();
messageQueries.add(messageFromQuery);
messageQueries.add(messageToQuery);
ParseQuery<Message> messageQuery = ParseQuery.or(messageQueries);
messageQuery.orderByAscending("createdAt");
messageQuery.findInBackground(new FindCallback<Message>() {
#Override
public void done(List<Message> messages, ParseException e) {
if (messages != null) {
mList.clear();
mList.addAll(messages);
msgAdapter = new MsgAdapter(requireContext(), mList, userTo.getObjectId(), userTo);
show_message.setAdapter(msgAdapter);
show_message.scrollToPosition(mList.size() - 1);
}
}
});
}
i can add auto refresh when send button is clicked but i don't want so , it will not look nice when users use it .. please help
public class BackgroundTasker extends AsyncTask {
int progress;
#Override
protected void onPreExecute() {
result.startAnimation(fadeIn);
result.setTextSize(32);
progressupdator(20);
result.setText("Starting...");
}
#Override
protected Long[] doInBackground(String... address) {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(new Long[] {
MainActivity.this.getvalue(address[0]) });
}
}
protected void onProgressUpdate(Long... values){
if(values[0]==Long.valueOf(333)) {
setProgress(100);
result.setText("N/A");
builder.setContentText("N/A");
notificationManager.notify(1,builder.build());
}
else{
setProgress(100);
result.setText(String.valueOf(values[0])+"ms");
builder.setContentText(String.valueOf(values[0])+"ms");
notificationManager.notify(1,builder.build());
}
}
protected void onPostExecute(int d) {
}
#Override
public void onClick(View v) {
DatabaseReference myRef = database.getReference("message");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
BackgroundTasker r = new BackgroundTasker();
r.execute(dataSnapshot.getValue(String.class));
Log.d("Fireabse", "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Firebase", "Failed to read value.", error.toException());
}
});
}
});
I want that whenever the button connected to onClick is pressed, The r.execute take new values from Firebase Realtime Database and perform AsyncTask with the new values.
How do i do that?
I get the value for the detectedLanguageCode variable inside the successListener, but out of the listener it becomes null.
Why is that happening?
i have put my code in a thread but it doesnt seem to get working.
Thread thread = new Thread(new Runnable() {
public void run() {
FirebaseLanguageIdentification languageIdentifier =
FirebaseNaturalLanguage.getInstance().getLanguageIdentification();
languageIdentifier.identifyLanguage(text)
.addOnSuccessListener(
new OnSuccessListener<String>() {
#Override
public void onSuccess(#Nullable String languageCode) {
if (languageCode != "und") {
detectedLanguageCode = languageCode;
//At this point detectedLanguageCode gets value
} else {
Log.i(TAG, "Can't identify language.");
}
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Model couldn’t be loaded or other internal error.
// ...
}
});
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// At this point detectedLanguageCode is null.
APPSYNC_ERROR: Attempt to invoke virtual method
java.util.Map
com.amazonaws.mobile.client.AWSMobileClientStore.get(java.lang.String[])
on a null object reference
I am trying to inserting data in AWS table, But i got this error.
Can you help me to resolve this issue?
AWSAppSyncClient client = AWSAppSyncClient.builder()
.context(context)
.region(AppHelper.cognitoRegion)
.serverUrl(AppHelper.SERVER_URL)
.cognitoUserPoolsAuthProvider(new CognitoUserPoolsAuthProvider() {
#Override
public String getLatestAuthToken() {
try {
return AWSMobileClient.getInstance().getTokens().getIdToken().getTokenString();
} catch (Exception e){
Log.e("APPSYNC_ERROR", e.getLocalizedMessage());
return e.getLocalizedMessage();
}
}
}).persistentMutationsCallback(new PersistentMutationsCallback() {
#Override
public void onResponse(PersistentMutationsResponse response) {
Log.d("NOTERROR", response.getMutationClassName());
}
#Override
public void onFailure(PersistentMutationsError error) {
Log.e("TAG", error.getMutationClassName());
Log.e("TAG", "Error", error.getException());
}
}).build();
You need to initialize AWSMobileClient successfully before its usage.
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
#Override
public void onResult(UserStateDetails userStateDetails) {
switch (userStateDetails.getUserState()){
case SIGNED_IN:
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView) findViewById(R.id.text);
textView.setText("Logged IN");
}
});
break;
case SIGNED_OUT:
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView) findViewById(R.id.text);
textView.setText("Logged OUT");
}
});
break;
default:
AWSMobileClient.getInstance().signOut();
break;
}
}
#Override
public void onError(Exception e) {
Log.e("INIT", e.toString());
}
});
If initialize is successful, you will be able to retrieve the tokens through the getTokens() method.
Source: https://aws-amplify.github.io/docs/android/authentication
I need to save in Realm a JSON that I've saved in Assets folder.
So I've decided to do it in this way:
private void putCountryIntoRealm()
{
Observable.create(new Observable.OnSubscribe<String>()
{
public void call(Subscriber<? super String> subscriber)
{
try
{
InputStream is = getActivity().getAssets().open("countries.json");
Reader inRead = new InputStreamReader(is);
Gson gson = new Gson();
JsonReader reader = new JsonReader(inRead);
reader.setLenient(true);
reader.beginArray();
while (reader.hasNext())
{
CountryObject ct = gson.fromJson(reader, CountryObject.class);
country.add(ct);
System.out.println("size ct: "+country.size());
subscriber.onNext(reader.toString());
}
reader.endArray();
reader.close();
subscriber.onCompleted();
}
catch (IOException e)
{
subscriber.onError(e);
}
}
}).subscribeOn(Schedulers.newThread())
.subscribe(new Subscriber<String>()
{
#Override
public void onCompleted()
{
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
realm.executeTransactionAsync(new Realm.Transaction()
{
float total = 0;
float size = country.size();
String progressCount;
public void execute(Realm mRealm)
{
Countries countries = new Countries();
int i;
System.out.print("countries size: "+size);
for (i = 0; i < country.size(); i++)
{
total = (i/size * 100);
progressCount = String.format("%.0f",total);
countries.setId(country.get(i).getId());
countries.setCode(country.get(i).getCode());
countries.setName(country.get(i).getName());
countries.setContinent(country.get(i).getContinent());
countries.setKeywords(country.get(i).getKeywords());
countries.setWikipedia_link(country.get(i).getWikiLink());
mRealm.insertOrUpdate(countries);
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
//Log.d("%",progressCount);
dialog = new ProgressDialog(getActivity());
dialog.setTitle("Salvataggio country in corso");
dialog.setMessage(progressCount+"%");
}
});
}
}
},new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess()
{
Log.wtf("va","Ok");
if(dialog.isShowing())
dialog.dismiss();
}
}, new Realm.Transaction.OnError()
{
#Override
public void onError(Throwable error)
{
error.printStackTrace();
}
});
}
});
}
#Override
public void onError(Throwable e)
{
e.printStackTrace();
}
#Override
public void onNext(String s)
{
System.out.println(s);
}
});
}
but I have this error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'long com.plenitudesrls.aviocalc.helpful.CountryObject.getId()' on a null object reference
In fact, I print logs and the size in onNext() is 245, in onCompleted() is null.
Why I have this error? I have another case where this works good.
Thanks
EDIT: it works good, the problem was a MalformedJson that cause the crash