Java 使用毕加索将url转换为imageView
我正在使用毕加索将url转换为imageView,但出现了一个错误。这是演示url,我想稍后从json获取url,但演示url甚至不起作用。请检查是否有人能解决 WordActivity.javaJava 使用毕加索将url转换为imageView,java,android,json,xml,picasso,Java,Android,Json,Xml,Picasso,我正在使用毕加索将url转换为imageView,但出现了一个错误。这是演示url,我想稍后从json获取url,但演示url甚至不起作用。请检查是否有人能解决 WordActivity.java package com.example.anandparmeetsingh.books; import android.app.LoaderManager; import android.content.Context; import android.content.Loader; import a
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();
}
}
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>
请尝试此函数获取位图
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;
}
}
正在加载图像的imageView为空。检查资源id R.id.imageView是否正确。您的链接工作正常。。我在用Glide试试这个。!阅读 进度条循环(u)进度;; 循环_进度=(进度条)findViewById(R.id.circularprogress)
Picasso.with(context).load(url).into(imageview);
使用(MainActivity.this)滑动
.加载(“http://books.google.com/books/content?id=JGQBcu5O_ZcC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api")
.listener(新的RequestListener(){
@凌驾
公共布尔onException(异常e、字符串模型、目标、布尔isFirstResource){
循环_progress.setVisibility(View.GONE);
返回false;
}
@凌驾
公共布尔值onResourceReady(GlideDrawable资源、字符串模型、目标、布尔值isFromMemoryCache、布尔值isFirstResource){
循环_progress.setVisibility(View.GONE);
返回false;
}
因此,如果您在这一行imageView=(imageView)findViewById(R.id.imageView)之后设置断点,则变量为非空?发布您的活动\u word.xml
我在毕加索中检查您的url,它正在工作。毕加索不是您的问题。]()未获取此信息。图像不可见,但应用程序未崩溃。如何在imageView中获取图像?位图位图=getBitmapfromUrl(imageurl);imageView.setImageBitmap(位图)@parmeetsinghan请查看我的评论如何调用函数和设置图像位图。你能帮助我使用毕加索吗?@ratilchopdait同样没有帮助。所以你的解决方案是删除对调整大小的调用(函数调用的其余部分与问题中的完全相同)?有意思……你能解释一下为什么调整大小会导致非法辩论例外吗?@parmeetsinghan不要注意这个答案,我今天没有投票权,否则它会有-1。这是完全错误的。仅供参考,ctx是上下文,在活动中与“this”相同(这就是你正在做的).holder是Atif正在使用的ViewHolder对象,因为他懒得清理他复制/粘贴的代码,所以他也把它放在了这个答案的垃圾代码中,因为为什么不呢。他还建议在毕加索的基础上添加另一个库,这是不需要的,但会使你的应用程序apk更重。@Parmeetsinghan现在试试这段代码,希望如此我可以帮你!让我们来。
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;
}
}
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"
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;
}