空指针错误
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Image a=new Image();
Image.MyAsyncTask task=a.new MyAsyncTask();
task.execute();
}
public void loadimage(View view) {
startActivity(new Intent(this,Image.class));
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:onClick="loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="loading image"
/>
</LinearLayout>
public class Image extends Activity {
private ImageView imageView;
private ProgressBar progressBar;
//图片地址
private static String URL = "http://pic.qiantucdn.com/58pic/19/43/68/56d3e7ffb7957_1024.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
imageView = (ImageView) findViewById(R.id.image);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
new MyAsyncTask().execute(URL); //设置传递进去的参数
}
class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE); //显示进度条
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
progressBar.setVisibility(View.GONE); //隐藏进度条显示图片
imageView.setImageBitmap(bitmap);
}
@Override
protected Bitmap doInBackground(String... params) { //String... params可变长数组
String url = params[0]; //获取传递进来的参数
Bitmap bitmap = null;
URLConnection connection; //定义网络连接对象
InputStream is; //用于获取数据的输入的数据流
try {
connection = new URL(url).openConnection(); //获取网络连接对象
is = connection.getInputStream(); //获取输入流
BufferedInputStream bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis); //将输入流解析成bitmap
is.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>
activity都注册了
报错在这2行
Image 里的progressBar.setVisibility(View.VISIBLE); //显示进度条
MainActivity 里的task.execute();