Android ImageView From URL: Not Getting Set (Using Picasso) - android

I'm brand new to Android development, so I'm probably doing something stupid. Any ideas why this code shouldn't work?
It compiles and runs, but doesn't actually successfully set the image (which is previously set to a gray background).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
Button getImageButton = (Button) (findViewById(R.id.btnGetImage));
getImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView myImageView = (ImageView) (findViewById(R.id.myImageView));
Picasso.with(v.getContext()).load("https://www.example.com/someimage").into(myImageView);
}
});
}

alter you code this way
Picasso.with(YOUR_ACTIVITY_NAME.this).load("https://www.example.com/someimage").into(myImageView);
Here v.getContext() is not related to the main context, so it won't help you, we need to pass context of current activity

Please try this and let me know.
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
Button getImageButton = (Button) (findViewById(R.id.btnGetImage));
ImageView myImageView = (ImageView) (findViewById(R.id.myImageView));
getImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Picasso.with(YourActivityName.this).load("https://www.example.com/someimage").into(myImageView);
}
});
}

Ding ding here is my answer
I am sure that you add the dependency
compile 'com.squareup.picasso:picasso:2.5.2'
and used the right url
Picasso.with(v.getContext()).load("http://i.imgur.com/DvpvklR.png").into(imageView);
I am telling you where you went wrong !!
Magic : Have you added the internet permission ? It needs to be in your manifest
<uses-permission android:name="android.permission.INTERNET" />
Rather than that your code is just fine
But i recommend you to use getApplicationContext()
copying from my comment
Picasso is a library and not an application. While creating
Picasso instance if you'll not pass context, then how do you think
it will get the application context from ? For it to work it requires
context , and it definitely needs to be provided by the application
using this library.It also prevents leaking an Activity (if that's
what you pass ,some of below answers have used ) by switching to the
application context. use getApplicationContext()
And for the people who randomly put an answer here read this as well
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside
of). Use this instead of the current Activity context if you need a
context tied to the lifecycle of the entire application, not just the
current Activity.
ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The
Context referred to from inside that ContextWrapper is accessed via
getBaseContext().
so any way he is accessing the currant activity context.
Cheers!

step 1 In Menifest check Internet Connection
<uses-permission android:name="android.permission.INTERNET" />
step 2 compile "com.squareup.picasso:picasso:2.4.0"
step 3 Image url is not showing any image in browser paste your url in browser and if you get image then you can set that image to imagview
step 4 check url is working or not there is not .png or .jpg extension for imagfile
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
Button getImageButton = (Button) (findViewById(R.id.btnGetImage));
getImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Initializing the ImageView
imageView = (ImageView) findViewById(R.id.imageView);
//Loading Image from URL
Picasso.with(this)
.load("https://www.example.com/someimage")
.placeholder(R.drawable.placeholder) // optional
.error(R.drawable.error) // optional
.resize(400,400) // optional
.into(imageView);
}
});
}

Related

How do I save the content view of my activity?

Alright so in my activity i changed my content view from one to another as you can see. so i was wondering how to save the content view that was there last when my activity was closed.
public class Levels extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
setContentView(R.layout.levels);
final EditText anstext1 = (EditText) findViewById(R.id.anstext1);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = anstext1.getText().toString();
if(result.equals("they"))
setContentView(R.layout.social);
else
Toast.makeText(getApplicationContext(), "Wrong", Toast.LENGTH_LONG).show();
}
});
}
}
setContentView
You should call this method only once in the Activity lifecycle.
Saving State
Most of the time you will save your models using onSaveInstanceState and restore them using the bundles generated from that method. Activity, Fragment and Views have these kind of methods build in.
Persisting state
If you are required to use the data for a longer period than the current app lifecycle you can use one of the following mechanisms:
SharedPreferences
SQL-lite DB
File I/O
Create a variable that has the type of R.layout.levels. Assuming R.layout.levels is a RelativeLayout: RelativeLayout rl;
Initialize it like this:
rl = (RelativeLayout) getLayoutInflater().inflate(R.layout.levels,null);
setContentView (rl);
If you want to save the variable for when the activity is destroyed you can put it in a custom Application class and retrieve it from there. You find here how to do it at "maintaining global state" : http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android
I don't know if it is good or bad to do this, but it could be a solution for what you're asking.

Android App Button 'onClick'

I am creating a charity app for Android. The app consists of 4 pages, each with a button which, when clicked, should navigate the user to the next page.
-Currently using Eclipse SDK-
The first (welcome) page button works and the code for this is:
public class CharityAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button main = (Button) findViewById(R.id.mybutton);
main.setOnClickListener (new OnClickListener(){
#Override
public void onClick(View v) {
setContentView(R.layout.donate);
// TODO Auto-generated method stub
}
});
}
I am wondering where I should put the code for the other buttons?
(this java file is currently called CharityAppActivity.java)....
Any help would be gratefully received. I would be more than willing to offer you any more code if you need it to help me a little better
Ps. the pages are named main.xml, donate.xml, value.xml and thanks.xml
Activity is only one screen of application.
You should create more activities for every screen and do not try to only change content. It is not possible call setContentView() multiple times by default.
I suggest you try to more samples application from SDK directly, read some tutorials or book.
Like you are finding Button main = (Button) findViewById(R.id.mybutton);
find other buttons from your main activity and set their onClickHandler to invoke your different activities.
I am assuming all the four concerned buttons are in same layout.
You just need to create 4 Activities.
The OnClick method will call the next Activity using "startActivity"
#Override
public void onClick(View v) {
Intent it = new Intent(NextClass.class);
startActivity(it);
}

Android (student cw) in need of direction

public class Menu extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
//myIntent.setClassName("hello.World", "hello.World.mybuttonclick");
// myIntent.putExtra("com.android.samples.SpecialValue", "Hello, Joe!"); // key/value pair, where key needs current package prefix.
//startActivity(myIntent);
//Button myButton = (Button) findViewById(R.id.my_button);
super.onCreate(icicle);
setContentView(R.layout.main);
}
public void updateLayout(){
Intent myIntent = new Intent(Menu.this, mybuttonclick.class);
startActivity(myIntent);
// TextView sayHello = (TextView) findViewById(R.id.Hello);
}
}
Hey guys, I am a new android java student and we have to develop a simple hello world app.. I am finding some difficulty getting my onClick() activity to work, using android:Onclick in xml.. what i am trying to do is change the content view do display a simply a different layout and saying hello.. i am using setContentLayout to do this, every time i click said button tho the android app crashes out.. am i doing something wrong?
regards,
Stefan
When you set a click listener in xml you must have the method defined inside the activity you are clicking in. Lets say you set the onClick in xml to be "buttonClicked", you must create a method looking exactly like the one below.
public void buttonClicked(View view)
{
//Your code here
}
The thing to notice is that the method is a public void with only a single parameter of type View. XML defined click listeners must be like this to work. The view object in the example above is the view that was clicked.
You update layout function needs to read
public void updateLayout(View view)
In response to your question, there are a number of things that are issues causing the complication that you described. Let it first be said, that you don't have to do anything any particular way, provided that you make concessions for certain things. Android is a very flexible platform and Java, as an OOP language allows you to do things that many non OOP languages do not.
Whenever you create a "clickable" item, like a Button, if you want to have your program respond, you must have something "listen" to it. This is known as a Listener. In your case, you are looking for an OnClickListener. The OnClickListener does not have to be a part of the Activity necessarily. It just has to be a class that implements View.OnClickListener. Then, you have tell the setOnClickListener() method of the Button who its listener is. The following example shows what is necessary without your declaration in XML (but it is important).
class Menu extends Activity implements View.OnClickListener
{
public void onCreate(Bundle icicle)
{ setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML);
btn.setOnClickListener(this);
}
public void onClick(View view)
{ int id = view.getId();
if (id == R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML)
updateLayout()//Do your Click event here
}
public void updateLayout()
{ //updateLayout code...
}
}
Something that needs to be noted is the OnClick() above. Every OnClickListener must use the same signature as theOnClick() That means itmust have the same return and same arguments even if it has a different name. For what you are trying to do (in XML), you have set your android:OnClick to updateLayout. This means that `updateLayout() must be declared as follows:
public void updateLayout(View view)
Now, getting the update method to actually work: While you provide your code, we don't actually know what errors you are getting. It is always much easier to solve a problem if we have a copy of the Logcat output that includes the error you are receiving. Once, we have that we can target your error specifically and I can edit my answer to include what you may additionally need.
FuzzicalLogic

Can't set image int into webview?

Allright so here's my problem. I have an app which contains alot of pictures and i wanted to be able to pinchzoom these, but since the ImageViewer doesnt support this natively I thought I'd use the Webviewer instead, but heres the thing. all my pictures are saved into my "picture" int and its the picture function i want to load into the webviewer. not a specific \drawable\bla.jpg Searched all around but didnt find anything about it. I'll attach some code for reference.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
int picture=intent.getIntExtra("picture", 22);
setContentView(R.layout.pictureframe);
ImageView image = (ImageView) findViewById(R.id.pansarvagn);
image.setBackgroundResource(picture);
and its here where i want smth like
Webview image = (WebView) findViewById(R.id.pansarvagn);
image.(setdata bla bla)
and this is the picture function
public void displayPicture(int pictureresource){
Intent intent = new Intent();
intent.putExtra("picture", pictureresource);
intent.setClass(getApplicationContext(), Picture.class);
startActivity(intent);
called by
Button tank = (Button) findViewById(R.id.tank);
tank.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
displayPicture(R.drawable.tank);
}
To further elaborate i want to put an image into a webview which i will be able to zoom into. so some sort of imageview inside the webview to fill up the webview with my picture. and then I want to be able to zoom in on it.
You need to create you own ContentProvider and override it's opeenFile(..) method. Then you can feed it to WebView:
myWebView.loadUrl("content://your.content.provider/someImageName");
Here is an example: http://www.techjini.com/blog/2009/01/10/android-tip-1-contentprovider-accessing-local-file-system-from-webview-showing-image-in-webview-using-content/
Note: with this approach you will need to save your images somewhere. You will not be able to serve them from memory.

Is it OK to use "mContext" (initialized at onCreate)?

Is this a bad habit, and why if it is? So in every activity adding this right after onCreate...
mContext = this;
and then use it in all other cases where context is required? For example
Toast.makeText(mContext, mContext.getString(R.string.someString), Toast.LENGTH_LONG);
EDIT: What if I have something like this...how the context should be passed? Because this cannot be applied (because of the View.OnClickListener()).
someButton = (Button) findViewById(R.id.someButton);
someButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, mContext.getString(R.string.warning), Toast.LENGTH_LONG).show();
}
});
Is this a bad habit, and why if it is?
Yes, it is a bad habit. It is a waste of code. this is shorter than mContext, and you have an extra line of code for setting the data member.
I disagree with Mr. Damiean's suggestion of always using getApplication(). Use getApplication() when you specifically need the Application object. You neither need nor want the Application object for creating a Toast -- your Activity is a perfectly suitable Context to use there. The Application object fails to work in many places, particularly when dealing with things involving the UI.
You can use this instead. Even in an OnClickListener or other subclasses you use ActivityName.this like this:
someButton = (Button) findViewById(R.id.someButton);
someButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ActivityName.this, ActivityName.this.getString(R.string.warning), Toast.LENGTH_LONG).show();
}
});

Categories

Resources