我正在尝试连接到站点,使用Jsoup
解析站点上的图像,将每个图像另存为Bitmap
,然后在GridView
中显示所有这些图像。从GridView
中选择图像后,该图像应显示在ImageView
中。
但是,我得到的只是运行代码时出现的空白屏幕(显示吐司)。
这是我的MainActivity
:
package com.example.homework18;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class MainActivity extends AppCompatActivity {
ImageView img;
final private int REQUEST_INTERNET = 123;
List<Bitmap> images = new ArrayList<Bitmap>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, REQUEST_INTERNET);
} else{
downloadSomething();
}
final ImageSwitcher imgSwitcher = findViewById(R.id.imgSwitcher);
imgSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView imgView = new ImageView(MainActivity.this);
imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imgView.setBackgroundColor(Color.GREEN);
ImageSwitcher.LayoutParams imgLayoutParams = new ImageSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
imgView.setLayoutParams(imgLayoutParams);
return imgView;
}
});
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id) {
imgSwitcher.setImageResource(images.indexOf(position));
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
private void downloadSomething() {
//String imgurl = "http://2.bp.blogspot.com/-us_u2PBLSOI/UqgPMh7ovjI/AAAAAAAACdI/ujdyGregs6Y/s1600/amazing-butterfly-hd-image.jpg";
String texturl = "https://www.csuohio.edu/";
//new DownloadImageTask().execute(imgurl);
//new DownloadTextTask().execute(texturl);
new DownloadTextTask().execute(texturl);
}
private void getWebsite(String html) {
Document doc = Jsoup.parse(html);
Elements imgs = doc.select("img");
int num_of_imgs = imgs.size();
String img[] = new String[num_of_imgs];
int i = 0;
for(Element x : imgs){
String url = x.absUrl("src");
img[i] = url;
i++;
}
for(String url : img){
Bitmap image = DownloadImage(url);
images.add(image);
}
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = download(URL);
if(in != null) {
bitmap = BitmapFactory.decodeStream(in);
try {
in.close();
} catch (IOException e1) {
Log.d("NetworkingActivity", e1.getLocalizedMessage());
}
}
return bitmap;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
getWebsite(result);
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
return DownloadImage(urls[0]);
}
protected void onPostExecute(Bitmap result) {
//ImageView img = (ImageView) findViewById(R.id.imageView);
images.add(result);
//img.setImageBitmap(result);
}
private String DownloadText(String URL)
{
int BUFFER_SIZE = 2000;
InputStream in = download(URL);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0) {
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
Log.d("Networking", e.getLocalizedMessage());
return "";
}
return str;
}
private InputStream download(String URL) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
return in;
} catch (IOException e1) {
Log.d("NetworkingActivity", e1.getLocalizedMessage());
}
return null;
}
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null; int response = -1; URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex)
{
Log.d("Networking", " " +ex.getLocalizedMessage()); throw new IOException("Error connecting");
}
return in;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c) { context = c; }
//---returns the number of images---
public int getCount() { return images.size(); }
//---returns the item---
public Object getItem(int position) { return position; }
//---returns the ID of an item---
public long getItemId(int position) { return position; }
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(images.indexOf(position));
return imageView;
}
}
}
这是我的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<GridView
android:id="@+id/gridview"
android:layout_width="384dp"
android:layout_height="511dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<ImageSwitcher
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="@+id/gridview"
android:id="@+id/imgSwitcher"
/>
</LinearLayout>