BitmapFactory.decodeStream() is working without INTERNET PERMISSION - java

I am supposed to fetch images from internet and display it on my activity.For this i am using asynctask class.I forgot to mention INTERNET permission in my manifest file and the application is running succesfully without giving any exception and is able to fetch all the images on Emulator.
On device it is showing Network error.
My question is why emulator is behaving like this.I am using genymotion emulator (Google Nexus 4)
Code is like:-
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button btnClick = null;
Button btnClick2 = null;
Context context = MainActivity.this;
ImageView imageview = null;
ProgressBar progressBar;
String URL = "http://images.visitcanberra.com.au/images/canberra_hero_image.jpg";
String URLTiger = "http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg";
String URLTree = "http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg";
String URLSky = "http://www.ucl.ac.uk/news/news-articles/1213/muscle-fibres-heart.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick2 = (Button)findViewById(R.id.btnClick2);
imageview = (ImageView)findViewById(R.id.imageview);
progressBar = (ProgressBar)findViewById(R.id.progressbar);
progressBar.setVisibility(ProgressBar.GONE);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnClick:
new ImageDownloader(this).execute("http://stylonica.com /wp-content/uploads/2014/02/nature.jpg");
new ImageDownloader(this).execute(URLTiger);
new ImageDownloader(this).execute(URLTree);
new ImageDownloader(this).execute(URLSky);
break;
case R.id.btnClick2:
new Thread(new Runnable() {
#Override
public void run() {
btnClick2.post(new Runnable() {
#Override
public void run() {
btnClick2.setText("Thread B");
}
});
}
}).start();
break;
}
}
public class ImageDownloader extends AsyncTask<String,String,Bitmap> {
ProgressDialog progressDialog;
Context context;
Bitmap bitmap;
public ImageDownloader(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// progressDialog = ProgressDialog.show(context,"Loading Image ","Please wait....");
progressBar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... args) {
try {
Log.d("new URL(args[0]..............", new URL(args[0]) + "");
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap image) {
if(image != null){
imageview.setImageBitmap(image);
// progressDialog.dismiss();
progressBar.setVisibility(ProgressBar.INVISIBLE);
}else{
// progressDialog.dismiss();
progressBar.setVisibility(ProgressBar.INVISIBLE);
Toast.makeText(context, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
And I have not mentioned INTERNET permission in my manifest file.

Disclaimer: I work on Genymotion.
The answer is that it is a Genymotion bug. :(
Android API compliance is absolutely fundamental for Genymotion.
Please, accept our apologies for the time you lost on this.
We investigated this bug immediately and fixed it.
You will have the fix in our next release.
The problem only happen on version 2.3.7, 4.1.1 et 4.2.2.

Related

Picasso Showing the Error Path Must Not Be Empty?

I am trying to fetching image from firebase. so when there is no image in firebase i want that my app logo will be set there. but my app is crashing and throwing the error into a log-cat.
I tried using if-else condition. and also on Success and on Error Methods. but did't worked fine.
private static final String Earnings_Freebies = "EARNINGS_FREEBIES";
private Earnings_Freebies list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earnings_freebies);
list = (Earnings_Freebies) getIntent().getExtras().getSerializable(Earnings_Freebies);
if (TextUtils.isEmpty(list.getmImageView())){
m_EF_ImageView.setImageResource(R.drawable.app_logo);
mProgressBarEF.setVisibility(View.GONE);
}
Picasso.with(getApplicationContext())
.load(list.getmImageView())
.into(m_EF_ImageView, new Callback() {
#Override
public void onSuccess() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.GONE);
}
#Override
public void onError() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.VISIBLE);
}
});
I want when there is error. or i forget to put image into firebase then app logo will automatically set into Image-view.
You can try below code. If not helpful then let me know a bit more about Earnings_Freebies model.
Make sure you were using latest dependency of Picasso.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earnings_freebies);
list = (Earnings_Freebies) getIntent().getExtras().getSerializable(Earnings_Freebies);
if (list == null && TextUtils.isEmpty(list.getmImageView())){
m_EF_ImageView.setImageResource(R.drawable.app_logo);
mProgressBarEF.setVisibility(View.GONE);
Picasso.with(getApplicationContext())
.load(R.mipmap.ic_launcher) // can also be a drawable
.into(m_EF_ImageView);
} else {
Picasso.with(getApplicationContext())
.load(list.getmImageView())
.placeholder(R.mipmap.ic_launcher) // can also be a drawable
.into(m_EF_ImageView);
}
}
you can try this way:
private static final String Earnings_Freebies = "EARNINGS_FREEBIES";
private Earnings_Freebies list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earnings_freebies);
list = (Earnings_Freebies) getIntent().getExtras().getSerializable(Earnings_Freebies);
if (list != null && list.getmImageView() != null && !TextUtils.isEmpty(list.getmImageView())){
Picasso.with(getApplicationContext())
.load(list.getmImageView())
.into(m_EF_ImageView, new Callback() {
#Override
public void onSuccess() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.GONE);
}
#Override
public void onError() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.VISIBLE);
}
});
}else{
Picasso.with(getApplicationContext())
.load(R.drawable.app_logo)
.placeholder(R.drawable.app_logo)
.into(m_EF_ImageView);
}
}
1) Picasso supports both download and error placeholders as optional features.
2) An error drawable will be used in case where there’s a failure in loading the image. In this case the interim placeholder image will be replaced by the error drawable that’s placed inside .error() method, where you can display your app's icon image in case of error.
Picasso.with(this).load("https://someImageURL")
.error(R.mipmap.ic_launcher) // Your app's icon image displayed on error
.placeholder(R.drawable.user_placeholder) // some placeholder image
.into(imageView, new Callback() {
#Override
public void onSuccess() {
Log.d("TAG", "onSuccess");
}
#Override
public void onError() {
Toast.makeText(getApplicationContext(), "An error occurred", Toast.LENGTH_SHORT).show();
}
});

How can i make a PDF file load fast into the PDFVIEW library and How do i set progressBar?

I have an App in which i would like to display a progressBar while waiting for the PDF to load from my firebase. But I have tried putting the load function on the OnpostExecute then calling the execute on the Oncreate. The problem is that it takes too for the pdf to load from my firebase into my pdfViewer hence may cause a user to quit the App. How can I make it load quickly??
And the progressBar stops even before the file has loaded. Below, I have attached some of the code I used. And I have used the Android pdfViewer Library.
In Summary, How can I make a PDF file load quicker into my pdfViewer and How can I make sure that the Progressbar only stops when the PDF has successfully shown?? Thanks in Advance.
Here is myonCreate() and I used an AsyncTask
public class Geo2009Paper1 extends Activity {
PDFView pdfView;
ProgressBar progressBar;
private ProgressDialog pd;
RetrievePDFStream task;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf_viewer);
progressBar = (ProgressBar) findViewById(R.id.simpleProgressbar);
progressBar.setProgress(0);
pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.enableSwipe(true);
showProgress();
}
protected class RetrievePDFStream extends AsyncTask<String, Integer, InputStream> {
ProgressBar bar;
public void setProgressBar(ProgressBar bar) {
this.bar = bar;
}
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 10) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (this.bar != null) {
bar.setProgress(values[0]);
}
}
#Override
protected void onPostExecute(InputStream inputStream) {
if (isNetworkAvailable()) {
progressBar.setVisibility(View.INVISIBLE);
pdfView.fromStream(inputStream).load();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
progressBar.setVisibility(View.INVISIBLE);
}
}, 100);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(Geo2009Paper1.this);
builder.setCancelable(false);
builder.setTitle("No Internet");
builder.setMessage("Internet is required. Please Retry.");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog dialog = builder.create(); // calling builder.create after adding buttons
dialog.show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
public void showProgress() {
task = new RetrievePDFStream();
task.execute("My PDF Url");
}

Chrome Custom Tabs pre-load webpages while browsing?

I'm testing the Chrome Custom Tabs. It is supposed to preload webpages a user is likely to click in the background. This happens through calling
session.mayLaunchUrl(uri, null, null);
While the MainActivity is active, the webpage is preloaded nicely and when launching the URL, the webpage loads quickly as expected.
However I would like to serve other webpages automatically to the user while he is already browsing (and the activity therefore is in background). Then, preloading the webpages does not seem to speed up the loading process anymore and even though the new served webpages are loading, this happens slowly.
I wrote a small app demonstrating this behavior. Preloading and launching an URL manually works nicely (as the activity is active, I suppose), serving new webpages in a loop automatically is slow (as the activity is not active and the mayLaunchUrl method does not work as expected then).
Is it possible to make use of the pre-loading mechanism while the user is browsing already? If yes, how?
I added the MainActivity code as example below:
public class MainActivity extends AppCompatActivity {
private CustomTabsSession mCustomTabsSession;
private CustomTabsClient mClient;
private CustomTabsServiceConnection mConnection;
private EditText urlET;
private String TAG = "MainActivity";
private ArrayList<String> urlList;
private Thread cycleThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("MainActivity", "onCreate");
urlList = new ArrayList<>();
urlList.add("http://www.google.com");
urlList.add("https://github.com");
urlList.add("http://stackoverflow.com");
urlList.add("http://www.heise.de");
// pre launch the chrome browser, bind services etc
warmup();
urlET = (EditText) findViewById(R.id.urlID);
// pre load a webpage manually
Button prepareBt = (Button) findViewById(R.id.prepareBt);
assert prepareBt != null;
prepareBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mayLaunch(null);
}
});
//launch webpage manually
Button launchBt = (Button) findViewById(R.id.launchBt);
assert launchBt != null;
launchBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launch(null);
}
});
//start a loop that serves webpages every 10 seconds
Button cycleBt = (Button) findViewById(R.id.cycleBt);
assert cycleBt != null;
cycleBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cycleThread !=null)
cycleThread.interrupt();
cycleThread = new Thread(cycle);
cycleThread.start();
}
});
}
private Runnable cycle = new Runnable() {
#Override
public void run() {
int i = 0;
mayLaunch(Uri.parse(urlList.get(i)));
try {
Thread.sleep(5000);
while (true){
try {
Log.d(TAG, "launch: "+urlList.get(i));
launch(Uri.parse(urlList.get(i)));
i++;
if(i>=urlList.size())
i=0;
Thread.sleep(5000);
Log.d(TAG, "prepare: "+urlList.get(i));
mayLaunch(Uri.parse(urlList.get(i)));
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private void mayLaunch(Uri uri){
if(uri ==null)
uri = Uri.parse(urlET.getText().toString());
CustomTabsSession session = getSession();
session.mayLaunchUrl(uri, null, null);
}
private void launch(Uri uri){
if(uri ==null)
uri = Uri.parse(urlET.getText().toString());
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(getSession())
.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark))
.setShowTitle(true)
.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.setExitAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.build();
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
customTabsIntent.launchUrl(this,uri);
}
public CustomTabsSession getSession() {
if (mClient == null) {
mCustomTabsSession = null;
} else if (mCustomTabsSession == null) {
mCustomTabsSession = mClient.newSession(null);
Log.d(TAG, "getSession: created new session");
}
return mCustomTabsSession;
}
private void warmup(){
if (mClient != null) return;
String packageName = "com.android.chrome";
if (packageName == null) return;
mConnection = new CustomTabsServiceConnection() {
#Override
public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient customTabsClient) {
mClient = customTabsClient;
mClient.warmup(0L);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mClient = null;
mCustomTabsSession = null;
}
};
CustomTabsClient.bindCustomTabsService(this, packageName, mConnection);
}
private void coolDown(){
if (mConnection == null) return;
unbindService(mConnection);
mClient = null;
mCustomTabsSession = null;
mConnection = null;
}
public void onDestroy() {
Log.v("MainActivity", "onDestroy");
super.onDestroy();
coolDown();
}
#Override
public void onBackPressed(){
}
}
Thanks!
CustomTabs ignores mayLaunchUrl() sent from the background. This is for 2 reasons:
Simple measure to avoid wasted bandwidth (it is easy to check that a custom tab from the same session is not the foreground, just did not do it yet)
Pages loaded through mayLaunchUrl() currently do not preserve Window.sessionStorage(), which is not a problem for App -> CustomTab transition, but for navigating within a single CustomTab this may break assumptions for users with navigation patterns like:
SiteA -> SiteB -> SiteA
(the second visit to SiteA does not see what is in the session). Teaching mayLaunchUrl() to choose the right sessionStorage() is complex, no plans for this yet.

Android Checking Website Updates Periodically (JSOUP)

I have a simple Android app. I am getting HTML elements from a website (article count from wikipedia) by use of JSOUP. I am getting article count on button click RefreshBtn() and show in a textview tv1 as shown below:
public class MainActivity extends ActionBarActivity {
String URL = "https://en.wikipedia.org";
Element article;
TextView tv1;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
}
private class FetchWebsiteData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(URL).userAgent("Mozilla").get();
article = doc.select("div#articlecount > a").first();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if(article == null) tv1.setText("null!");
else tv1.setText(article.text() + " articles found!");
mProgressDialog.dismiss();
}
}
public void RefreshBtn(View v) {
new FetchWebsiteData().execute();
}
...
}
I want to get article count periodically (for example in every 2 hours). Then maybe I can create push-notifications if there is a change. What is the best way to do this? I need some suggestions. Thanks.
The best way is to use the internal Alarm Manager.
Alarm Manager Example
another way is to implement a second Thread:
new Thread(new Runnable()
#Override
public void run()
{
try
{
while(true)
{
Thread.sleep(100000); //milliseconds
// Do Something
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}).start();

Error with Twitter4J from Android with browser user authentication: No authentication challenges found

I am trying to develop my own Android application using Android Studio 0.4.2 and the Twitter4J library. My idea is to use a WebView to load there the Twitter authentication page and get the AccessToken from there. I can get the oauth_token and oauth_verifier, but after that all the Twitter methods to get followers, post twits, whatever are not working.
This is my code:
public class TwitterLoginFragment extends Fragment {
private static String TWITTER_CONSUMER_KEY = "***";
private static String TWITTER_CONSUMER_SECRET = "***";
private static final String TWITTER_CALLBACK_URL = "http://www.hita.pro";
private static SharedPreferences sharedPreferences;
private Button btnTwitterLogin;
private Button btnTwitterLogOut;
private WebView wvTwitterLogin;
private IDs iDs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
sharedPreferences = getActivity().getSharedPreferences("CONNECTION_INFO", Context.MODE_PRIVATE);
TwitterFactory.getSingleton().setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
return inflater.inflate(R.layout.fragment_twitter_login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstance) {
super.onActivityCreated(savedInstance);
wvTwitterLogin = (WebView) getView().findViewById(R.id.wvTwitterLogin);
wvTwitterLogin.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("KEY_TWITTER_LOGIN", true);
editor.putString("OAUTH_TOKEN", url.substring(url.indexOf("oauth_token=") + 12, url.indexOf("&")));
editor.putString("OAUTH_VERIFIER", url.substring(url.indexOf("oauth_verifier=") + 15));
editor.commit();
TwitterFactory.getSingleton().setOAuthAccessToken(new AccessToken(sharedPreferences.getString("OAUTH_TOKEN", ""), sharedPreferences.getString("OAUTH_VERIFIER", "")));
new GetTwitterFollowers().execute();
return true;
}
});
btnTwitterLogin = (Button) getView().findViewById(R.id.btnTwitterLogin);
btnTwitterLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginToTwitter();
}
});
btnTwitterLogOut = (Button) getView().findViewById(R.id.btnTwitterLogOut);
btnTwitterLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
twitterLogOut();
}
});
}
public void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
wvTwitterLogin.loadUrl(TwitterFactory.getSingleton().getOAuthRequestToken(TWITTER_CALLBACK_URL).getAuthenticationURL());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
goToTwitterLogin();
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), getString(R.string.error_already_logged_twitter), Toast.LENGTH_LONG).show();
}
}
});
thread.start();
} else
Toast.makeText(getActivity(), getString(R.string.error_already_logged_twitter), Toast.LENGTH_LONG).show();
}
private void goToTwitterLogin() {
btnTwitterLogin.setVisibility(View.GONE);
btnTwitterLogOut.setVisibility(View.GONE);
wvTwitterLogin.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
return sharedPreferences.getBoolean("KEY_TWITTER_LOGIN", false);
}
private void twitterLogOut() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("KEY_TWITTER_LOGIN", false);
editor.commit();
}
private class GetTwitterFollowers extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... v) {
try {
iDs = TwitterFactory.getSingleton().getFollowersIDs(-1);
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
iDs.getIDs();
}
}
}
When I call to TwitterFactory.getSingleton().getFollowersIDs(-1) after the user has singed in, I'm getting this exception:
java.io.IOException: No authentication challenges found
I'm desperated, I have spent one week trying to solve this problem but all the threads I have found in StackOverflow and other sites are not working. The system clock is OK, I have tried with ConfigurationBuilder and other solutions, but no luck. Can somebody help me?
Thanks a lot!
Have you tried to work with instance not singleton from TwitterFactory?
Uri uri = Uri.parse(url);
String token = uri.getQueryParameter("OAUTH_TOKEN");
String verifier = uri.getQueryParameter("OAUTH_VERIFIER");
Twitter twitter = TwitterFactory.getInstance(
new AccessToken(token,verifier);
twitter.getFollowers(-1);

Categories

Resources