android - Using EditText values to a textview on another activity

被刻印的时光 ゝ 提交于 2020-06-13 11:12:30

问题


What I need is quite simple.

1- User types some info on EditTexts.

2- Uses intent and bundle to take the data to another activity

3- Shows the data stored from EditTexts to TextViews.

But, here's the problem. EditTexts are at MainActivity, the activity that will receive the data isn't the next one, but the last one, named finalizar_relatorio.class.

And also, I'm trying to send this bundle to the next activity when I call one method because if I use startActivity() inside onCreate, it will start that activity right after pressing play. How should I call the startActivity() from within the method?

There are 4 numeric EditTexts and a char one.

Which Bundle.putXX should I use for those?

Like for char: Bundle.putString("VariableBeingCalledInNextActivity", variableThatStoresEditTextdata);

Could you help me pointing out what I'm doing wrong? Code's kind of messy, sorry for that.

I've tried following other questions here, but I'm guessing my problem is when I'm saving EditText data to the Bundle

MainActivity (UPDATED)

package com.example.relatoriodeobras;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {
public int tipo;
SharedPreferences dadosprocesso;
public static final String PREFERENCES = "MyPrefs" ;
public static final String processo    = "processo" ;
public static final String requerente  = "requerente" ;
public static final String portas      = "portas" ;
public static final String janelas     = "janelas" ;
public static final String unhab       = "unhab" ;

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

    final EditText editText4 = (EditText)findViewById(R.id.editText4);      
    final EditText editText5 = (EditText)findViewById(R.id.editText5);       
    final EditText editText6 = (EditText)findViewById(R.id.editText6);      
    final EditText editText7 = (EditText)findViewById(R.id.editText7);
    final EditText editText8 = (EditText)findViewById(R.id.editText8);


    Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
    String[] items = new String[] { "Tipo de fiscalização","Alvará", "Habite-se" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, items);

    dynamicSpinner.setAdapter(adapter);
    dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {

            String processo1   = editText4.getText().toString();
            String requerente1 = editText5.getText().toString();
            String portas1     = editText6.getText().toString();
            String janelas1    = editText7.getText().toString();
            String unhab1      = editText8.getText().toString();

            dadosprocesso = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = dadosprocesso.edit();
            editor.putString(processo, processo1);
            editor.putString(requerente, requerente1);
            editor.putString(portas, portas1);
            editor.putString(janelas, janelas1);
            editor.putString(unhab, unhab1);
            editor.commit();

            Log.v("item", (String) parent.getItemAtPosition(position));
            boolean fieldsOK = validate(new EditText[]{editText4,editText5,editText6,editText7,editText8});
            if(fieldsOK) {
                switch (position) {
                    case 1:
                        tipo = 1;
                        Intent intent = new Intent(MainActivity.this, alvara.class);
                        startActivity(intent);
                        break;
                    case 2:
                        tipo = 2;
                        Intent intent1 = new Intent(MainActivity.this, habitese.class);
                        startActivity(intent1);
                        break;
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }
    });
    obraFolder();
}

public void obraFolder(){   //Criar a pasta do projeto e o diretório em que os projetos estarão conditos, caso não tenha sido criado.
    EditText projectName = (EditText) findViewById(R.id.editText4);
    String obraName = projectName.getText().toString(); //obraName é a variável String que define o nome da pasta do projeto
    obraName = obraName.trim();
    File myInternalFile;

    String filepath = "Projetos" + obraName;
    String filename = obraName + ".txt";
    ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
    File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
    myInternalFile = new File(directory, filename);
}

private boolean validate(EditText[] fields){
    for(int i=0; i<fields.length; i++){
        EditText currentField=fields[i];
        if(currentField.getText().toString().length()<=0){
            Context context = getApplicationContext();
            CharSequence text = "Atenção! Exitem campos obrigatórios vazios!!";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
            //postDelayed
            return false;
        }
    }

    startActivity(dadosdaobra);
    return true;
}

}

finalizar_relatorio.java (UPDATED)

package com.example.relatoriodeobras;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class finalizar_relatorio extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_finalizar_relatorio);

      SharedPreferences dadosprocesso = getSharedPreferences("MyPrefs.xml", MODE_PRIVATE);
    String restoredtext = dadosprocesso.getString("text", null);
    if(restoredtext != null){
        String processo   = dadosprocesso.getString("processo", "processo");
        String requerente = dadosprocesso.getString("requerente", "requerente");
        String portas     = dadosprocesso.getString("portas", "portas");
        String janelas    = dadosprocesso.getString("janelas", "janelas");
        String unhab      = dadosprocesso.getString("unhab", "unhab");

        ((TextView)findViewById(R.id.textView18)).setText(processo);
        ((TextView)findViewById(R.id.textView20)).setText(requerente);
        ((TextView)findViewById(R.id.textView22)).setText(portas);
        ((TextView)findViewById(R.id.textView24)).setText(janelas);
        ((TextView)findViewById(R.id.textView26)).setText(unhab);

    }
}
}

回答1:


try This :-
Write this code in your main activity :-
public static final String KEY_PREFERNCE = "prefernce";
public static final String KEY_ID = "id";

SharedPrefernce shraedprefernce = MainActivity.this.getSharedPrefernce(KEY_PREFERNCE ,PRIVATEMODE);
SharedPrefernce.Editor editor = shraedprefernce.edit();
editor.putString(KEY_ID ,youredittext.getText.toString);
editor.commit;

the following code used in your last activity:-
SharedPrefernce shraedprefernce = YourActivity.this.getSharedPrefernce(MainActivity.KEY_PREFERNCE ,PRIVATEMODE);

String data = shraedprefernce.getString(MainActivity.KEY_ID,"");
yourTextView.setData(data);

Don't forget to commit the editor in your main activity.



回答2:


I might be confused by your question, but if your starting the activity in the onCreate, try grabbing the EditText Values in an Overrided onResume()

e.g.

protected void onResume() {
     String edittext4 = editText4.getText().toString();
     String edittext5 = editText5.getText().toString();
     String edittext6 = editText6.getText().toString();
     String edittext7 = editText7.getText().toString();
     String edittext8 = editText8.getText().toString();

     Intent dadosdaobra = new Intent(MainActivity.this, finalizar_relatorio.class);
Bundle dados = new Bundle();

     dados.putString("extra_processo", edittext5);
     dados.putString("extra_requerente", edittext4);
     dados.putString("extra_portas", edittext6);
     dados.putString("extra_janelas", edittext7);
     dados.putString("extra_unhab", edittext8);

     dadosdaobra.putExtras(dados);

     addSpinnerListeners();
}

private void addSpinnerListeners() {
      dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                               int position, long id) {
             Log.v("item", (String) parent.getItemAtPosition(position));
             boolean fieldsOK = validate(new EditText[]   {editText4,editText5,editText6,editText7,editText8});
             if(fieldsOK) {
                 switch (position) {
                     case 1:
                        tipo = 1;
                         Intent intent = new Intent(MainActivity.this, alvara.class);
                         startActivity(intent);
                        break;
                     case 2:
                        tipo = 2;
                         Intent intent1 = new Intent(MainActivity.this, habitese.class);
                         startActivity(intent1);
                        break;
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub
    }
});



回答3:


Use shared preference for this.Save data in shared prefernce and retrieve from it.



来源:https://stackoverflow.com/questions/39542184/android-using-edittext-values-to-a-textview-on-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!