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();
}
Related
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 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);
}
To begin with, I checked literally every single SwipeToRefreshLayout question to solve this issue, but none worked for me. So I'm asking for your help to solve this issue.
I want the refresher to go away "once the refreshing is complete". What I tried so far either made it go away too early, or not go away at all. Here is the related code: (note that mSwipeRefreshLayout is already defined.)
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
final double latitude = 39.9179;
final double longitude = 32.8627;
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
handler.post(refreshing);
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
}
private final Runnable refreshing = new Runnable(){
public void run(){
try {
if(mSwipeRefreshLayout.isRefreshing()){
handler.postDelayed(this, 500);
}else{
mSwipeRefreshLayout.setRefreshing(false);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};
and the data fetch function:
private void getForecast(double latitude, double longitude) {
String apiKey = "7d22cdb138cd70f2e9e8d2006cd0461c";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey
+ "/" + latitude + "," + longitude;
if (isNetworkAvailable()){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
}
else {
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}
}
swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getForecast(latitude, longitude); //call ur function here
swipeContainer.setRefreshing(false);
}
});
I wish to post a text / link defined by me on my wall. The way I'm doing, okay opening the box wall and posting a text set time. I want to post a text as if it were a variable.
Eg String text = "Text to be posted"
and this text appear on my wall. Any idea?
public void postToWall() {
facebook.dialog(cxt, "feed",new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile
JSONObject profile = new JSONObject(json);
// nome usu�rio
final String name = profile.getString("name");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Comentário enviado com sucesso" + "Name: " + name,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
} }
#Override
public void onCancel() {
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
});
}