我正在使用Picasso将url转换为imageView但收到错误。这是我想稍后从json获取url的demo url但是demo url甚至无法正常工作。请检查是否有人可以解决。
WordActivity.java
package com.example.anandparmeetsingh.books;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class WordActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Word>> {
private static final String LOG_TAG = WordActivity.class.getName();
/**
* URL for word data from the USGS dataset
*/
private static String USGS_REQUEST_URL =
"https://www.googleapis.com/books/v1/volumes?q=harrypotter";
/**
* Adapter for the list of earthquakes
*/
public WordAdapter mAdapter;
ListView wordListView;
ArrayList<Word> words;
private TextView mEmptyStateTextView;
private String mQuery = "";
private ImageView imageView;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_word);
// Get a reference to the LoaderManager, in order to interact with loaders.
wordListView = (ListView) findViewById(R.id.list);
words = new ArrayList<>();
mAdapter = new WordAdapter(WordActivity.this, words);
// Create a new adapter that takes an empty list of earthquakes as input
// Set the adapter on the {@link ListView}
// so the list can be populated in the user interface
wordListView.setAdapter(mAdapter);
// Set an item click listener on the ListView, which sends an intent to a web browser
// to open a website with more information about the selected word.
// Set the adapter on the {@link ListView}
// so the list can be populated in the user interface
// Start the AsyncTask to fetch the word data
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
wordListView.setEmptyView(mEmptyStateTextView);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(this)
.load("http://books.google.com/books/content?id=JGQBcu5O_ZcC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api")
.resize(200,200)
.into(imageView);
// Get details on the currently active default data network
final NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (USGS_REQUEST_URL == null || networkInfo == null) {
wordListView.setEmptyView(mEmptyStateTextView);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
}
// If there is a network connection, fetch data
final EditText mEditText = (EditText) findViewById(R.id.search_go_btn);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (USGS_REQUEST_URL == null || networkInfo == null) {
wordListView.setEmptyView(mEmptyStateTextView);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
}
USGS_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
//mAdapter.notifyDataSetChanged();
// Get the text from the EditText and update the mQuery value.
mQuery = mEditText.getText().toString().replaceAll(" ", "+");
// If it's empty don't proceed.
if (mQuery.isEmpty()) {
Toast.makeText(WordActivity.this, "Nothing to search", Toast.LENGTH_SHORT).show();
}
// Update the mRequestUrl value with the new mQuery.
USGS_REQUEST_URL = USGS_REQUEST_URL + mQuery + "&maxResults=15";
Log.i("onQueryTextSubmit", "mRequestUrl value is: " + USGS_REQUEST_URL);
// Restart the loader.
LoaderManager loaderManager = getLoaderManager();
loaderManager.restartLoader(1, null, WordActivity.this);
Log.i("onClick", "loader restarted");
View progressBar = findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
// Try to make the progress bar appear again (not working)
//View progressBar = findViewById(R.id.progress_bar);
//progressBar.setVisibility(View.VISIBLE);
// Update mRequestUrl back to its original value.
USGS_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
// This is what makes the ListView update with new info.
}
});
if (networkInfo != null && networkInfo.isConnected()) {
// Get a reference to the LoaderManager, in order to interact with loaders.
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
loaderManager.initLoader(1, null, this);
} else {
// Otherwise, display error
// First, hide loading indicator so error message will be visible
View loadingIndicator = findViewById(R.id.progress_bar);
loadingIndicator.setVisibility(View.GONE);
//Update empty state with no connection error message
wordListView.setEmptyView(mEmptyStateTextView);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
mEmptyStateTextView.setText("No Connection");
}
}
public Loader<List<Word>> onCreateLoader(int i, Bundle bundle) {
return new WordLoader(this, USGS_REQUEST_URL);
}
/**
* {@link } to perform the network request on a background thread, and then
* update the UI with the list of earthquakes in the response.
* <p>
* AsyncTask has three generic parameters: the input type, a type used for progress updates, and
* an output type. Our task will take a String URL, and return an EarthquakeAdapter. We won't do
* progress updates, so the second generic is just Void.
* <p>
* We'll only override two of the methods of AsyncTask: doInBackground() and onPostExecute().
* The doInBackground() method runs on a background thread, so it can run long-running code
* (like network activity), without interfering with the responsiveness of the app.
* Then onPostExecute() is passed the result of doInBackground() method, but runs on the
* UI thread, so it can use the produced data to update the UI.
*/
@Override
public void onLoadFinished(Loader<List<Word>> loader, List<Word> earthquakes) {
// Clear the adapter of previous word data
View loadingIndicator = findViewById(R.id.progress_bar);
loadingIndicator.setVisibility(View.GONE);
words.clear();
// If there is a valid list of {@link Earthquake}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (earthquakes != null && !earthquakes.isEmpty()) {
words.addAll(earthquakes);
} else {
wordListView.setEmptyView(mEmptyStateTextView);
mEmptyStateTextView.setText("No Connection");
}
mAdapter.notifyDataSetChanged();
/* words.addAll(earthquakes);
mAdapter.notifyDataSetChanged();*/
}
@Override
public void onLoaderReset(Loader<List<Word>> loader) {
// Loader reset, so we can clear out our existing data.
words.clear();
}
}
错误消息
05-15 17:46:35.512 21319-21319/com.example.anandparmeetsingh.booklisting E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.anandparmeetsingh.booklisting, PID: 21319
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anandparmeetsingh.booklisting/com.example.anandparmeetsingh.books.WordActivity}: java.lang.IllegalArgumentException: Target must not be null.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.IllegalArgumentException: Target must not be null.
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:553)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:536)
at com.example.anandparmeetsingh.books.WordActivity.onCreate(WordActivity.java:75)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
activity_word.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.anandparmeetsingh.books.Book">
<TextView
android:id="@+id/magnitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:fontFamily="sans-serif-medium"
android:padding="12dp"
android:paddingTop="5dp"
android:text="Title"
android:textAlignment="center"
android:textColor="#616161"
android:textSize="32sp" />
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="@id/magnitude"
android:layout_centerInParent="true"
android:id="@+id/imageView"/>
<TextView
android:id="@+id/location_offset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/imageView"
android:layout_marginLeft="6dp"
android:ellipsize="end"
android:fontFamily="sans-serif-medium"
android:maxLines="1"
android:paddingBottom="6dp"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="12sp"
tools:text="Date" />
<TextView
android:id="@+id/primary_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/location_offset"
android:fontFamily="sans-serif-condensed"
android:paddingBottom="12dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:text="Description"
android:textAlignment="center"
android:textColor="#757575"
android:textSize="16sp" />
<TextView
android:id="@+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/primary_location"
android:fontFamily="sans-serif-condensed"
android:gravity="right"
android:paddingBottom="16dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:text="Mature"
android:textColor="#424242"
android:textSize="16sp" />
</RelativeLayout>
答案 0 :(得分:0)
请尝试此功能获取位图
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
答案 1 :(得分:0)
imageView您正在将图像加载为null。检查资源ID R.id.imageView是否正确。
答案 2 :(得分:0)
你的链接工作完全正常..我正在使用Glide尝试这个。!阅读Glide Documentation
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.android.support:support-v4:25.1.0'
Glide
.with(context)
.load(url)
.override(200, 200) // resizes the image to these dimensions (in pixel). does not respect aspect ratio
.into(imageView);
String url="http://api.androidhive.info/images/sample.jpg"
ProgressBar circular_progress; circular_progress =(ProgressBar)findViewById(R.id.circularprogress);
Picasso.with(context).load(url).into(imageview);
Glide.with(MainActivity.this)
.load("http://books.google.com/books/content?id=JGQBcu5O_ZcC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api")
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
circular_progress.setVisibility(View.GONE);
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
circular_progress.setVisibility(View.GONE);
return false;
}