我正在获取nullPointerException “button.setOnClickListener(this);”....同时更改布局 CountDownTimer的finish()方法。这里是代码...请帮我解决这个问题.......提前谢谢
package com.example.vikrant.countdowntimer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context c = getApplicationContext();
new CountDownTimer(10000,5000){
@Override
public void onTick(long millisUntilFinished) {
setContentView(R.layout.timer);
}
@Override
public void onFinish() {
setContentView(R.layout.activity_main);
}
}.start();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String url="https://firebasestorage.googleapis.com/v0/b/fir-assignment-34e5b.appspot.com/o/rangoliA%2Frangolinew.jpg?alt=media&token=4a376937-7fec-420a-a18c-8c9ec7da95af";
image = (ImageView) findViewById(R.id.imageView);
DownloadImage downloadImage = new DownloadImage();
Bitmap bitmap;
try {
bitmap = downloadImage.execute(url).get();
image.setImageBitmap(bitmap);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class DownloadImage extends AsyncTask<String,Void,Bitmap>{
@Override
protected Bitmap doInBackground(String... params) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}
答案 0 :(得分:0)
您的按钮可能在您的&#34; R.layout.activity_main&#34;中定义。当你设置另一个内容时,&#34; findViewById(R.id.button)&#34;将返回null(因为它未在其他布局中定义)。
为什么要改变布局呢?