call a method from a DialogFragment

1

As I can call a method from DilogFragment , the problem is that in this DialogFragment I use it to generate a dialog box where I enter two data that is stored in a file until that part I have no problem, it is saved correctly everything.

But what I want to do is that once that data is saved, we have to execute a method that will read the new data, but when doing the instance the method gives me an error:

  

** Attempt to invoke virtual method 'java.io.FileInputStream android.content.Context.openFileInput (java.lang.String)' on a null object reference

This is the code of my main class where I have the method that I want to call, the method is called refresh () , this method is at the end of the code:

package com.example.enriq.myapplication;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Principal extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private String archivo = "sesion.obj";
    private String carga = "parquimetro.obj";

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        try{
            ObjectInputStream objInput = new ObjectInputStream(openFileInput(carga));
            Registro_parqueo persona = (Registro_parqueo) objInput.readObject();
            objInput.close();
            TextView luffy = (TextView)findViewById(R.id.muestrario);
            luffy.setText(persona.toString()+"\n");

            //Toast.makeText(Principal.this, "Archivo cargado correctamente", Toast.LENGTH_SHORT).show();
        }catch (IOException e){
            Toast.makeText(this,"Error al leer el archivo",Toast.LENGTH_SHORT).show();
        }catch (ClassNotFoundException e){
            Log.e("Principal", "Error clase no encontrada");
        }


        View header = navigationView.getHeaderView(0);
        TextView text = (TextView) header.findViewById(R.id.ususesion);
            try {
                ObjectInputStream objInput = new ObjectInputStream(openFileInput(archivo));
                Usuario persona = (Usuario) objInput.readObject();
                objInput.close();
                text.setText(persona.toString());
                Toast.makeText(this, "Sesión inicia con exito", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(this, "Error al cargar el archivo", Toast.LENGTH_SHORT).show();
            } catch (ClassNotFoundException e) {
                Log.e("MainActivity", "Error clase no encontrada");
            }
    }

    @Override
    public void onBackPressed(){
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        }else{
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public boolean onOptionsItemSelected(MenuItem item){
        //este metodo es para obtener el id del menu de los
        //tres puntos
        int id = item.getItemId();

        if(id == R.id.exportar){
            //onClickRadio(view);
        }else if(id == R.id.sesion){
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }
    /*public void onClickAlerta(View view){
        listaParqueos lista = new listaParqueos();
        lista.DialogoAlerta(view);
    }*/

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if(id == R.id.iniciotap){
            /*Parqueos parqueos = new Parqueos();
            android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.exp, parqueos).commit();*/
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setSubtitle("Parqueos");

        }else if(id == R.id.noticiastap){
            //Traemos al fragmento de noticias
            /*configuracion confi = new configuracion();
            android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
            //vamos a sustitur el contenedor del activity main por un nuevo fragment
            manager.beginTransaction().replace(R.id.exp, confi).commit();*/
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setSubtitle("Preferencias");


           /* getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new ConfiguracionesFragment())
                    .commit();*/
        }
        //Este codigo nos permite mostrar que menu esta seleccionado
        //para poder identificar que menu esta en uso
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
//Este es el metodo al que quiero llamar
   public void refrescar(){

        try{
            ObjectInputStream objInput = new ObjectInputStream(openFileInput(archivo));
            Registro_parqueo persona = (Registro_parqueo) objInput.readObject();
            objInput.close();
            TextView luffy = (TextView)findViewById(R.id.muestrario);
            luffy.setText(persona.toString()+"\n");
        }catch (IOException e){
            Toast.makeText(this,"No quedo",Toast.LENGTH_SHORT).show();
        }catch (ClassNotFoundException e){
            Log.e("Principal", "Error clase no encontrada");
        }

    }
}

and this is my class Dialog that extends from a DialogFragment, in the method that is called onclicguardarpersona () I try to call the method that is in my main class that is called refresh () :

package com.example.enriq.myapplication;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import static android.content.Context.MODE_APPEND;
import static android.content.Context.MODE_PRIVATE;

/**
 * Created by Enriq on 30/01/2018.
 */

public class Dialogo extends android.support.v4.app.DialogFragment {
    private ArrayList<Registro_parqueo> lista;
    private String archivo = "parquimetro.obj";
    View view;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        //builder.setView(inflater.inflate(R.layout.dialog_signin, null))
        View MyView = inflater.inflate(R.layout.dialog_signin, null);
        final EditText matricula = (EditText)MyView.findViewById(R.id.parqueo);
        final EditText clienesillo = (EditText)MyView.findViewById(R.id.cliente);
                // Add action buttons
        builder.setView(MyView)
                .setPositiveButton("Registrar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        onClickGuardarPersona(matricula.getText().toString(),clienesillo.getText().toString());

                    }
                })
                .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Dialogo.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }

    public void onClickGuardarPersona(String matricula, String clienesillo) {
        try{

            ObjectOutputStream objOutput = new ObjectOutputStream(getActivity().openFileOutput(archivo, MODE_PRIVATE));
            objOutput.writeObject(new Registro_parqueo(matricula,clienesillo));
            objOutput.close();
            Toast.makeText(getActivity(), "Parqueo registrado", Toast.LENGTH_SHORT).show();
            Principal principal = new Principal();
            principal.refrescar();

        }catch (IOException e){
            Toast.makeText(getActivity(), "Error al guardar el parqueo", Toast.LENGTH_SHORT).show();
        }
    }
}
    
asked by Kike hatake 27.02.2018 в 19:28
source

1 answer

1

to call the method belonging to the Main class from

  

onClickGuardPersona (String enrollment, String clienillo)

, we should call the Activity:

  

((Main) getActivity ()). refresh ();

Instead of creating an Instance of that class.

    
answered by 27.02.2018 / 21:13
source