How to pass data from several activities to another to store them in a file?

0

I have problems trying to collect information from a form that I have divided into several activities into a tabhost.

In my MainActivity I have a button that shows a screen where the file will be named, it will be saved and its content can be displayed, what I want is to send the information of all the activities to the activity that is responsible for saving in a file. I tried with Intent , pulling with an object of each class the data, even in the methods onPause and onResume . I have tried to verify that the values are there and print them on the screen. But when trying to send them to another side I have not been successful, I always get the error that I try to make reference to a null object. How could I solve this problem?

This is my MainActivity code:

public class MainActivity extends TabActivity {

PhotosActivity phot;
public static String mainObject;
String parametro="";
Bundle bundle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Creacion del tabhost
    TabHost tabHost = getTabHost();


   // parametro = bundle.getString("Valor");

    Button btnSave = (Button) findViewById(R.id.button3);
    //Boton que te envia a la activity para enviar correo
    Button btnMail = (Button) findViewById(R.id.button);
    btnMail.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            Intent intent2 = new Intent (v.getContext(), MailSender.class);
            startActivityForResult(intent2, 0);

        }
    });

    btnSave.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            Intent intentSave = new Intent (v.getContext(),GuardarArchivo.class);
            startActivityForResult(intentSave,0);

        }
    });

    // Tab for General Description
    TabHost.TabSpec gralspec = tabHost.newTabSpec("General");
    // setting Title and Icon for the Tab
    gralspec.setIndicator("", getResources().getDrawable(R.drawable.icon_general_tab));
    Intent photosIntent = new Intent(this, PhotosActivity.class);
    photosIntent.putExtra("Prueba","Valor de prueba");
    gralspec.setContent(photosIntent);

    // Tab for Cable
    TabHost.TabSpec cablespec = tabHost.newTabSpec("Cableado");
    cablespec.setIndicator("", getResources().getDrawable(R.drawable.icon_structure_tab));
    Intent songsIntent = new Intent(this, SongsActivity.class);
    cablespec.setContent(songsIntent);

    // Tab for Fiber
    TabHost.TabSpec fibrespec = tabHost.newTabSpec("Fibra");
    fibrespec.setIndicator("", getResources().getDrawable(R.drawable.icon_fiber_tab));
    Intent videosIntent = new Intent(this, VideosActivity.class);
    fibrespec.setContent(videosIntent);

    // Tab for UPS/PDU
    TabHost.TabSpec upsspec = tabHost.newTabSpec("UPS/PDU");
    upsspec.setIndicator("", getResources().getDrawable(R.drawable.icon_ups_tab));
    Intent upsIntent = new Intent(this, UpsActivity.class);
    upsspec.setContent(upsIntent);

    // Tab for CCTV
    TabHost.TabSpec cctvspec = tabHost.newTabSpec("CCTV");
    cctvspec.setIndicator("", getResources().getDrawable(R.drawable.icon_cctv_tab));
    Intent cctvIntent = new Intent(this, CctvActivity.class);
    cctvspec.setContent(cctvIntent);

    // Tab for CCTV
    TabHost.TabSpec acunitspec = tabHost.newTabSpec("AC UNIT");
    acunitspec.setIndicator("", getResources().getDrawable(R.drawable.icon_acunit_tab));
    Intent acunitIntent = new Intent(this, ACunitActivity.class);
    acunitspec.setContent(acunitIntent);

    // Tab for Other
    TabHost.TabSpec otherspec = tabHost.newTabSpec("OTHER");
    otherspec.setIndicator("", getResources().getDrawable(R.drawable.icon_other_tab));
    Intent otherIntent = new Intent(this, OtherActivity.class);
    otherspec.setContent(otherIntent);

    // Adding all TabSpec to TabHost
    tabHost.addTab(gralspec);
    tabHost.addTab(cablespec);
    tabHost.addTab(fibrespec);
    tabHost.addTab(upsspec);
    tabHost.addTab(cctvspec);
    tabHost.addTab(acunitspec);
    tabHost.addTab(otherspec);

}}

This is the Activity code GuardarArchivo :

public class GuardarArchivo extends AppCompatActivity implements View.OnClickListener{

PhotosActivity objectPh;
Button leer;
Button escribir;
Button mostrar;
TextView textView;
EditText textEdit;
static String nombreArchivo;
String contenido;
String stringPrueba;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.guardar_archivo);

    escribir = (Button)findViewById(R.id.btnGuardar);
    leer =(Button)findViewById(R.id.btnContenido);
    mostrar =(Button)findViewById(R.id.btnLista);
    textView = (TextView)findViewById(R.id.textView19);
    textEdit=(EditText) findViewById(R.id.editText35);



    escribir.setOnClickListener(this);
    leer.setOnClickListener(this);
    mostrar.setOnClickListener(this);

    //savedInstanceState = getIntent().getExtras();
    stringPrueba = savedInstanceState.getString("Lugar");
    if(stringPrueba!=null){
        Log.e("Prueba", "No nulo");
    }
    else{
        stringPrueba = "Sin valor";
    }

}


public void writeFile1() {

   Bundle bundle;
    nombreArchivo = textEdit.getText().toString();

    contenido = "Fecha de levantamiento: "+stringPrueba+"\t\t\t Hora levantamiento:";
    if(nombreArchivo.contentEquals("")){
        nombreArchivo = "Sin titulo";
    }
    try {
        FileOutputStream fos = openFileOutput(nombreArchivo + ".txt",Context.MODE_PRIVATE);
        fos.write(contenido.getBytes());
        Log.e("","Creado correctamente");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    private void readFile1(){

    String selectedFile = textEdit.getText().toString();
    String content= "";
    FileInputStream fis;
    try {
        fis = openFileInput(selectedFile);
        byte[] input = new byte[fis.available()];
        while (fis.read(input)!=-1){
            content += new String(input);
        }
        fis.close();
    }catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    textView.setText(contenido);
}

@Override
public void onClick(View v) {

    switch(v.getId()){

        case(R.id.btnGuardar):

            writeFile1();

            break;

        case(R.id.btnContenido):

            readFile1();

            break;

        case(R.id.btnLista):

            Intent intent2 = new Intent (v.getContext(), FileViewer.class);
            startActivityForResult(intent2, 0);

            break;

        default:

            break;
    }
}}

And this is one of the 7 Activity from which I try to get the data:

public class PhotosActivity extends Activity{

MainActivity object;
int day = 0, month = 0, year = 0, hour, minute, telefono;
static final int DIALOG_ID = 0, DIALOG_ID_HOUR = 1, DIALOG_ID_LIST = 2;
EditText textFecha, textHora, lugarArea;
String lugar, fecha, hora, direccionIns, eMail, descripcionGral, levantamientoPor, tipoPlano, infoPor, cargo, comentarios;

@RequiresApi(api = Build.VERSION_CODES.N)
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photos_layout);

    lugar="";

    //Spinner Tipo AcUnit
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Planos_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    lugarArea = (EditText) findViewById(R.id.editText3);

    //Mandamos a llamar las funciones de hora y calendario
    showDialogOnText();
    showDialogOnTextHour();

    //Le damos el valor de la fecha actual a las variables
    final Calendar cal = Calendar.getInstance();
    year = cal.get(Calendar.YEAR);
    day = cal.get(Calendar.DAY_OF_MONTH);
    month = cal.get(Calendar.MONTH);

    Resources res = getResources();

    hour = cal.get(Calendar.HOUR);
    minute = cal.get(Calendar.MINUTE);



}

//Reloj
public void showDialogOnTextHour() {
    textHora = (EditText) findViewById(R.id.editText2);
    textHora.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog(DIALOG_ID_HOUR);
                }
            });
}
//Calendario
public void showDialogOnText() {
    textFecha = (EditText) findViewById(R.id.editText1);
    textFecha.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog(DIALOG_ID);
                }
            });
}

@Override
protected Dialog onCreateDialog(int id) {
    if (id == DIALOG_ID)
        return new DatePickerDialog(this, dpickerListner, year, month, day);
    else if (id == DIALOG_ID_HOUR)
        return new TimePickerDialog(this, dpickerListnerHour, hour, minute, false);

    return null;
}
//Ajuste de hora de reloj
protected TimePickerDialog.OnTimeSetListener dpickerListnerHour = new TimePickerDialog.OnTimeSetListener() {

    @Override
    public void onTimeSet(TimePicker view, int hourDay, int minuteN) {
        minute = minuteN;
        hour = hourDay;
        if (minute < 10 && hour < 10) {
            textHora.setText("0" + hour + " : " + "0" + minute);
        } else if (hour < 10) {
            textHora.setText("0" + hour + " : " + minute);
        } else if (minute < 10) {
            textHora.setText(hour + " : " + "0" + minute);
        } else {
            textHora.setText(hour + " : " + minute);
        }
    }
};
//Asignacion de fecha en TextView
private DatePickerDialog.OnDateSetListener dpickerListner = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int yearN, int monthOfYear, int dayOfMonth) {
        year = yearN;
        month = monthOfYear + 1;
        day = dayOfMonth;
        textFecha.setText(day + "/" + month + "/" + year);
    }
};

public void onPause(){
    super.onPause();
    lugar = lugarArea.getText().toString();

            Log.e("lol",lugar);
}

public void onResume(){
    super.onResume();
    Bundle bund=new Bundle();

    lugar = lugarArea.getText().toString();
    bund.putString("Lugar",lugar);
    Log.e("lol",lugar);
}

}

    
asked by Jonathan Bustamante 16.01.2017 в 21:49
source

1 answer

0

Look at this example:

In your activity that sends data:

Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(key, "holamundo");
startActivity(intent);

In your onCreate of the Activity that receives data:

Intent intent = getIntent();
if (null != intent) { 
    String prueba = intent.getStringExtra(key, defaultValue);
 }
    
answered by 17.01.2017 в 20:35