How to pass information between screens, using Bundle and Classes with Get and Set?

Asked

Viewed 1,114 times

1

I’m trying to pass information from one screen to another.

I’ve tried to (2) two manners:

  • 1) I created a class only to create variables and encapsulate the methods
  • 2) Now, I’m trying to get past Berne without the encapsulated methods.

Problems 1): The problem is that whole the get stays null if I use on another screen unseen that of the Aboutscreen .

Problems 2): The problem is that is giving the following error, as it is below.

  • ERROR:

06-16 15:28:26.235 16338-16338/com.vuforia.samples.Books E/Androidruntime: FATAL EXCEPTION: main Process: com.vuforia.samples.Books, PID: 16338 java.lang.Runtimeexception: Unable to instantiate Activity Componentinfo{com.vuforia.samples.Books/com.vuforia.samples.Books.app.Books.Books}: java.lang.Nullpointerexception: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null Object Reference at android.app.Activitythread.performLaunchActivity(Activitythread.java:2495) at android.app.Activitythread.handleLaunchActivity(Activitythread.java:2650) at android.app.Activitythread. -wrap11(Activitythread.java) at android.app.Activitythread$H.handleMessage(Activitythread.java:1505) at android.os.Handler.dispatchMessage(Handler.java:111) at android.os.Looper.loop(Looper.java:207) at android.app.Activitythread.main(Activitythread.java:5776) at java.lang.reflect.Method.invoke(Native Method) at com.android.Internal.os.Zygoteinit$Methodandargscaller.run(Zygoteinit.java:888) at com.android.Internal.os.Zygoteinit.main(Zygoteinit.java:749) Caused by: java.lang.Nullpointerexception: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null Object Reference at com.vuforia.samples.Books.app.Books.Books.(Books.java:138) at java.lang.Class.newInstance(Native Method) at android.app.Instrumentation.newActivity(Instrumentation.java:1072) at android.app.Activitythread.performLaunchActivity(Activitythread.java:2485) at android.app.Activitythread.handleLaunchActivity(Activitythread.java:2650)  at android.app.Activitythread. -wrap11(Activitythread.java)  at android.app.Activitythread$H.handleMessage(Activitythread.java:1505)  at android.os.Handler.dispatchMessage(Handler.java:111)  at android.os.Looper.loop(Looper.java:207)  at android.app.Activitythread.main(Activitythread.java:5776)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.Internal.os.Zygoteinit$Methodandargscaller.run(Zygoteinit.java:888)  at com.android.Internal.os.Zygoteinit.main(Zygoteinit.java:749)

- Aboutscreen.java:

/*===============================================================================
Copyright (c) 2016 PTC Inc. All Rights Reserved.

Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.

Vuforia is a trademark of PTC Inc., registered in the United States and other 
countries.
===============================================================================*/

package com.vuforia.samples.Books.ui.ActivityList;

import com.vuforia.samples.Books.R;
import com.vuforia.samples.Books.app.Books.Books;
import com.vuforia.samples.Books.app.Neoris.Shopping;
import android.Manifest;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.util.List;


public class AboutScreen extends FragmentActivity {

    private Button mStartButton;
    private String mClassToLaunch;
    private String mClassToLaunchPackage;

    private TextView txtShoppingName;
    private TextView txtShoppingCity;
    private TextView txtShoppingLat;
    private TextView txtShoppingLong;

    private Location location;
    private LocationManager locationManager;
    private Address endereco;

    private double latitude;
    private double longitude;
    private String nomeShopping;
    private String licenseKey;
    private String aKey;
    private String sKey;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about_screen);


        Bundle extras = getIntent().getExtras();
        mClassToLaunchPackage = getPackageName();
        mClassToLaunch = mClassToLaunchPackage + "." + extras.getString("ACTIVITY_TO_LAUNCH");

        /**
         * VERIFICAÇÃO DA PERMISSÃO DO USUÁRIO AO USO DO GPS.
         */

        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

        } else {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }

        if (location !=null){
            latitude = location.getLatitude();
            longitude = location.getLongitude();

            verificarShopping(latitude, longitude); //Verifica a Lat e Long, retorna o 'Nome do Shopping' e insere as Key's

            try {
                endereco = buscarEndereco(latitude, longitude);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        mStartButton = (Button) findViewById(R.id.button_start);
        mStartButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                //Cria um Layout para o DialogFragment.
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(AboutScreen.this);
                View mView = getLayoutInflater().inflate(R.layout.fragment_dialogo, null);

                Button mComecarButton = (Button) mView.findViewById(R.id.btn_comecar);

                txtShoppingName = (TextView) mView.findViewById(R.id.txtShoppingName);
                txtShoppingCity = (TextView) mView.findViewById(R.id.txtShoppingCity);
                txtShoppingLat = (TextView) mView.findViewById(R.id.txtShoppingLat);
                txtShoppingLong = (TextView) mView.findViewById(R.id.txtShoppingLong);

                //Insere as Informações ao DialogFragment.
                Shopping shop = new Shopping();

                txtShoppingName.setText(" " + nomeShopping);
                txtShoppingCity.setText(" " + endereco.getLocality());
                txtShoppingLat.setText(" " + latitude);
                txtShoppingLong.setText(" " + longitude);


                //Abre a Activity Books.
                mComecarButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent(AboutScreen.this, Books.class);
                        startActivity(i);
                    }
                });

                mBuilder.setView(mView);
                AlertDialog dialog = mBuilder.create();
                dialog.show();
            }
        });

    }

    //Busca em uma List os Endereços da Geolocalização do GPS.
    public Address buscarEndereco(double latitude, double longitude) throws IOException {
        Geocoder geocoder;
        Address address = null;
        List<Address> addresses;

        geocoder = new Geocoder(getApplicationContext());
        addresses = geocoder.getFromLocation(latitude, longitude, 1);

        if(addresses.size() > 0){
            address = addresses.get(0);
        }

        return address;
    }

    public String verificarShopping(double latitude, double longitude){

        Shopping shop = new Shopping();
        Bundle bundle = new Bundle();
        Intent intent = new Intent(AboutScreen.this, Books.class);


        if((this.latitude == latitude)&&(this.longitude == longitude)){
            /*FUNCIONA*/shop.setNome("Neoris");
            /*NÃO FUNCIONA EM OUTRA ACTIVITY, SOMENTE NESTA*/shop.setLicenseKey("Ad84Z0z/////AAAAGSgcOhPVvkoniWypHW2Dfsw+iX69sih5qx5JH1PEs92sM2xIhbsKnb2eTNkfBeQymsfgyRswpCDi2Ocu78RH+5+7/fXED7hJPLf3T7k4xKKLl4z8OKfCmr8jE0L5wQdJVV9L3tiHEoUx67M4b3ZSlO3/AzDLYi2/Zt3z8fuPo62osy469O+bKBsKKZtnyX9K7RYwJ2colMQ1bIhQERjg1w5cEZLHUacXAI1ndYhzS2Xl5iwAz98VZ65sptn+PrA5Xno55VGddt7rSBmvwuhZzeyShWnOqiYFhjWg80F3PFv2H/hYfIt4ML37yerJxS/n0z8yFv1H5gPi+Abd5nfaboz/xx1WgXf0yDvQKslFV+rr");

            nomeShopping = shop.getNome();
            licenseKey = shop.getLicenseKey();
            aKey = shop.getAccessKey();
            sKey = shop.getSecretKey();

            // CÓDIGO AQUI
            bundle.putString("aKey", "f854427b00cf89cb4909cf3780a22f1fe6dd1daa");
            bundle.putString("sKey", "16208b50224e2ff8d3c93f069d2c4adf739cea7a");
            intent.putExtras(bundle);

            startActivity(intent);


            return nomeShopping;
        }
        return "oi";
    }



}
  • Books java.:

    package com.vuforia.samples.Books.app.Books;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String acKey = bundle.getString("aKey");
    String secKey = bundle.getString("sKey");
    
    Shopping shop = new Shopping();
    private String kAccessKey = acKey;
    private String kSecretKey = secKey;
    

1 answer

1


What your mistake says:

EXCEPTION: main Process: com.vuforia.samples.Books, PID: 16338 java.lang.Runtimeexception: Unable to instantiate Activity

Your class Books is not registered as a Activity

This, because you are calling her as an Activity:

 Intent i = new Intent(AboutScreen.this, Books.class);
  startActivity(i);

To register as an Activity (if it is one) add the following line in the file Androidmanifest.xml within the TAG application:

 <activity android:name="com.vuforia.samples.Books"></activity>

Here is an example of how to pass parameters between Activity's

Class where we send the data:

public class ActivityUm extends AppCompatActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

        Button.class.cast(findViewById(R.id.all)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Vamos chamar a ActivityDois!
                Intent i = new Intent(ActivityUm.this, ActivityDois.class);
//                // Informamos uma chave, para que na próxima tela ele consiga pegar o valor!
                i.putExtra("VALOR_1", "Este é o valor que vamso passar no parametro 1");
                i.putExtra("VALOR_2", 12345L);
                startActivity(i);
            }
        });
    }
}

Class where we will receive the data:

public class ActivityDois extends AppCompatActivity{


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

        //Agora vamos pegar o valor, se o getIntent() não seja nulo!
        if(null != getIntent()){
            /** Pegamos o VALOR_1**/
            final String valor1 = getIntent().getStringExtra("VALOR_1");
            /** Caso seja nulo, o valor será -1**/
            final Long valor2 = getIntent().getLongExtra("VALOR_2", -1L);
        }
    }
}
  • Tell me one thing. I am analyzing your code to test, but I would like to know the following: In normal java, we create classes and insert the variables and their encapsulations. How do I use this mode on Android, using get and set of a class? This is the correct mode to use on mobile?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.