I'm using this code to check my internet connection, but it does not allow me to use setText()
to change a text in layout, give error and close the app, can anyone help?
private void checkNetworkConnection() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
boolean wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
boolean mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if(wifiConnected) {
Log.i(TAG, "WIFI connected");
stsRede.setText("Conectado no WiFi");
} else if (mobileConnected){
Log.i(TAG, "Mobile Connected");
//stsRede.setText("Conectado no 3G");
}
} else {
Log.i(TAG,"Neither Mobile nor WIFi connected.");
//stsRede.setText("Sem conexão a internet");
}
}
Error returning:
08-27 23:25:26.454: I/Adreno-EGL(31529): <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LNX.LA.3.5.1_RB1.04.04.02.048.018_msm8226_LNX.LA.3.5.1_RB1__release_AU ()
08-27 23:25:26.454: I/Adreno-EGL(31529): OpenGL ES Shader Compiler Version: E031.24.00.08
08-27 23:25:26.454: I/Adreno-EGL(31529): Build Date: 03/07/14 Fri
08-27 23:25:26.454: I/Adreno-EGL(31529): Local Branch:
08-27 23:25:26.454: I/Adreno-EGL(31529): Remote Branch: quic/LNX.LA.3.5.1_RB1.1
08-27 23:25:26.454: I/Adreno-EGL(31529): Local Patches: NONE
08-27 23:25:26.454: I/Adreno-EGL(31529): Reconstruct Branch: AU_LINUX_ANDROID_LNX.LA.3.5.1_RB1.04.04.02.048.018 + f2fd134 + NOTHING
08-27 23:25:26.549: D/OpenGLRenderer(31529): Enabling debug mode 0
08-27 23:25:28.683: I/(31529): WIFI connected
08-27 23:25:28.685: D/AndroidRuntime(31529): Shutting down VM
08-27 23:25:28.685: W/dalvikvm(31529): threadid=1: thread exiting with uncaught exception (group=0x41920d40)
08-27 23:25:28.688: E/AndroidRuntime(31529): FATAL EXCEPTION: main
08-27 23:25:28.688: E/AndroidRuntime(31529): Process: br.com.renasti, PID: 31529
08-27 23:25:28.688: E/AndroidRuntime(31529): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.renasti/br.com.renasti.NovoRegActivity}: java.lang.NullPointerException
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.ActivityThread.access$800(ActivityThread.java:139)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.os.Handler.dispatchMessage(Handler.java:102)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.os.Looper.loop(Looper.java:136)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.ActivityThread.main(ActivityThread.java:5086)
08-27 23:25:28.688: E/AndroidRuntime(31529): at java.lang.reflect.Method.invokeNative(Native Method)
08-27 23:25:28.688: E/AndroidRuntime(31529): at java.lang.reflect.Method.invoke(Method.java:515)
08-27 23:25:28.688: E/AndroidRuntime(31529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
08-27 23:25:28.688: E/AndroidRuntime(31529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
08-27 23:25:28.688: E/AndroidRuntime(31529): at dalvik.system.NativeStart.main(Native Method)
08-27 23:25:28.688: E/AndroidRuntime(31529): Caused by: java.lang.NullPointerException
08-27 23:25:28.688: E/AndroidRuntime(31529): at br.com.renasti.NovoRegActivity.checkNetworkConnection(NovoRegActivity.java:232)
08-27 23:25:28.688: E/AndroidRuntime(31529): at br.com.renasti.NovoRegActivity.onCreate(NovoRegActivity.java:57)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.Activity.performCreate(Activity.java:5248)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
08-27 23:25:28.688: E/AndroidRuntime(31529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
08-27 23:25:28.688: E/AndroidRuntime(31529): ... 11 more
Personal, below my NewRegActivity Class. In it I retrieve the textview stsRede, however I do not understand the error.
public class NovoRegActivity extends Activity {
Calendar cal = new GregorianCalendar();
public Dados dados = new Dados();
private Uri fileUri;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final String MEDIA_TYPE_IMAGE = null;
private static final String TAG = null;
private TextView txtfoto;
private EditText edtBairro;
private TextView txtLatitude;
private TextView txtLongitude;
private TextView txtdata;
private Button btGps;
public int ano, mes, dia;
public TextView stsRede;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Remove barra de titulos
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_novo_reg);
//Checa status de conexão com a internet
checkNetworkConnection();
//Recupera os id's vindo da activity NovoReg
setupElements();
//Checa status do gps
checaStatusGps();
//Inicia gps sem necessidade de clicar no botao. Apenas chamando o método
startGPS();
//Recupera data
recuperaData();
}
//Verifica se gps está ativado, caso não esteja, solicita ativação
public void checaStatusGps(){
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
} else {
//Depois configurar um Alert Box aqui antes avisando sobre o gps
Toast.makeText(NovoRegActivity.this, "Por favor ative seu gps!", Toast.LENGTH_LONG).show();
//Chama tela de ativação do Gps
Intent ligaGps = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(ligaGps);
}
}
// Método usado para importar os elementos da classe R
public void setupElements(){
//Recupera id txt foto e edt bairro
txtfoto = (TextView) findViewById(R.id.txtStatusFoto);
edtBairro = (EditText) findViewById(R.id.editBairro);
txtLatitude = (TextView) findViewById(R.id.txtLatitude);
txtLongitude = (TextView) findViewById(R.id.txtLongitude);
txtdata = (TextView) findViewById(R.id.txtdata);
stsRede = (TextView) findViewById(R.id.stsRede);
btGps = (Button) findViewById(R.id.btnGps);
btGps.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
startGPS();
}});
}
public void recuperaData() {
//Recuperando data atual
Calendar calendar = Calendar.getInstance();
ano = calendar.get(Calendar.YEAR);
mes = calendar.get(Calendar.MONTH);
dia = calendar.get(Calendar.DAY_OF_MONTH);
//Seta na variavel dataRegistro
txtdata.setText(dia + "/" + (mes+1)+ "/" +ano);
}
//Método que faz a leitura de fato dos valores recebidos do GPS
public void startGPS(){
LocationManager lManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener lListener = new LocationListener() {
public void onLocationChanged(Location locat) {
updateView(locat);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lListener);
}
// Método que faz a atualização da tela para o usuário.
public void updateView(Location locat){
Double latitude = locat.getLatitude();
Double longitude = locat.getLongitude();
txtLatitude.setText(latitude.toString());
txtLongitude.setText(longitude.toString());
//Log.i("Gps", "pegou!");
}
//Método para registrar a foto
public void foto(View v){
File diretorio = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String nomeImagem = diretorio.getPath()+ "/" + System.currentTimeMillis()+".jpg";
// create Intent to take a picture and return control to the calling application
Intent novafoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(new File(nomeImagem));
novafoto.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(novafoto, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
//Método de retorno do arquivo gravado
private Uri getOutputMediaFileUri(String mediaTypeImage) {
// TODO Auto-generated method stub
return null;
}
//Método para recuperar status da câmera
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//Alterar status de registro da foto visualmente
txtfoto.setText("Foto Registrada!");
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Foto Registrada", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
//Toast.makeText(this, "Registro de foto cancelado!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Falha na captura da imagem!", Toast.LENGTH_LONG).show();
}
}
}
//Faz o registro no banco de dados e envia para WS
public void registrar(View v){
//Checa campos vazios
/*if (edtBairro.getText().toString().equals("") || txtfoto.getText().toString().equals("")){
Toast.makeText(this, "Existe campos vazios!" , Toast.LENGTH_SHORT).show();
return;
}*/
//Verifica status internet
if (stsRede.getText().toString().equals("Sem conexão a internet")){
Toast.makeText(this, "Você precisa da internet para enviar o alerta!", Toast.LENGTH_SHORT).show();
return;
}
//Gravando no banco de dados
dados.setLatitude(txtLatitude.getText().toString());
dados.setLongitude(txtLongitude.getText().toString());
dados.setDataEnvio(txtdata.getText().toString());
dados.setBairro(edtBairro.getText().toString());
//Colocar evento aqui para registrar imagem no banco
BD bd = new BD (this);
bd.inserir(dados);
Log.i("BD","Salvou");
Toast.makeText(this, "Enviado com sucesso!", Toast.LENGTH_SHORT).show();
}
private void checkNetworkConnection() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
boolean wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
boolean mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if(wifiConnected) {
Log.i(TAG, "WIFI connected");
//stsRede.setText("Conectado no WiFi");
} else if (mobileConnected){
Log.i(TAG, "Mobile Connected");
//stsRede.setText("Conectado no 3G");
}
} else {
Log.i(TAG,"Neither Mobile nor WIFi connected.");
//stsRede.setText("Sem conexão a internet");
}
}
}