variable becomes null out of successListener - android

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.

Related

AWS AppSync Error - AWSMobileClientStore.get(String) on null object reference

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

Why Observable.create() is not working on single click?

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);
}
});

How to resolve fragment not attached to activity in android?

I have a fragment in which,I load some data from sever using background thread and update the UI using "runOnUiThread".But it gives me error "fragment not attached to activity".
How can I resolve that issue?
code:-
AsyncTask.execute(new Runnable() {
#Override
public void run() {
/*Checking whether user is loggedin or not*/
if (loginSessionManager.isLogin()) {
/*Creating object of "CServerRequest" class*/
cServerRequest = new CServerRequest(mContext);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put(CRequestKey.AGENT_CODE, m_szMobileNumber.trim());
jsonObject.put(CRequestKey.PIN, m_szEncryptedPassword.trim());
if (BuildConfig.kDebugInfo)
Log.d(TAG, "Request::" + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.VISIBLE);
}
});
}
String s_szWalletURL = CAPIStorage.IREWARDS_URL + CAPIStorage.WALLET_BALANCE_URL;
cServerRequest.postWalletRequest("POST", s_szWalletURL, jsonObject);
/*Handling server response and error here*/
cServerRequest.setCallBackListener(new CServerRequest.IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
if (BuildConfig.kDebugInfo)
Log.d(TAG, "Response::" + response);
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(CResponseKey.GENERAL_RESULT_CODE));
if (nResultCodeFromServer == ConstantInt.TRANSACTION_SUCCESS) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.GONE);
m_walletHeading.setVisibility(View.VISIBLE);
m_SuccessLayout.setVisibility(View.VISIBLE);
}
});
}
String s_szWalletBalance = response.getString(CResponseKey.WALLET_BALANCE).trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet balance here from ui thread.
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (m_szCountryCode.equalsIgnoreCase(CResponseKey.COUNTRY_INDIA)) {
m_currency.setText(getString(string.ruppes_symbol));
} else {
m_currency.setText(getString(string.currency_dollar));
}
m_points.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
if (m_szCountryCode.equalsIgnoreCase(CResponseKey.COUNTRY_INDIA)) {
/*If found indian user then show conversion of points in rupees*/
amountConversionIndia();
} else {
/*If found non-indian then will show conversion of points in doller*/
amountConversionInternational();
}
}
});
}
/*Connection lost error*/
} else if (nResultCodeFromServer == ConstantInt.CONNECTION_LOST) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.connection_lost));
m_ErrorText.setText(getResources().getString(string.retry));
}
});
}
/*Timed out error from response*/
} else if (nResultCodeFromServer == ConstantInt.TIMED_OUT) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.connection_timed_out));
m_ErrorBtn.setText(getResources().getString(string.retry_text));
}
});
}
/*Technical failure response from server*/
} else if (nResultCodeFromServer == ConstantInt.TECHNICAL_FAILURE) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.technical_failure));
m_ErrorBtn.setText(getResources().getString(string.retry_text));
}
});
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void notifyError(String requestType, VolleyError error) {
if (BuildConfig.kDebugInfo)
Log.d(TAG, "Error::" + error);
if (isAdded()) {
/*Time out volley error*/
if (error instanceof TimeoutError) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.connection_timed_out));
m_ErrorBtn.setText(getResources().getString(string.retry_text));
}
});
/*Network volley error*/
}
}
if (isAdded()) {
if (error instanceof NetworkError) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.unable_to_connect_text));
m_ErrorBtn.setText(getResources().getString(string.retry));
}
});
}
}
}
});
} else {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (isAdded()) {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_ErrorText.setText(mContext.getResources().getString(string.please_log_into_your_account));
m_ErrorBtn.setText(getResources().getString(string.login_btn_text));
}
}
});
}
}
}
});
}
The solution to this problem should be cancel your asynctask in onStop().
You also don't introduce the problem of memory leak.
#Override
public void onStop() {
super.onStop();
mYourAsyncTask.cancel(true);
}

Observable gives me size of a List null in onComplete()

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

android parse google image

I'm trying to parse image from google with android
it's work for me and for another friend of mine but it doesn't
work for some one else
When i asked him for his error he said that the Element im object was empty
and when i run my program it have 22 elements
private void setImageFromGoogle(final String name) {
new Thread(new Runnable() {
#Override
public void run() {
try {
String url = "https://www.google.co.il/search?q=" + name + "&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjpq_CYh4jRAhXXdFAKHSOBCe0Q_AUICCgB&biw=1680&bih=920";
final Document doc = Jsoup.connect(url).userAgent("Chrome").get();
runOnUiThread(new Runnable() {
#Override
public void run() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
imageView.setImageBitmap(getImageBitmap(doc.select("[src]").get(1).attributes().get("src")));
}
});
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
runToast(e.toString());
}
});
Log.e("error", e.toString());
}
}
}).start();
}

Categories

Resources