2015-03-22 5 views
0

У меня есть TableView с 60 TextView, что пользователь может касаться и вводить данные внутри них с помощью другой операции с диалогом. DialogActivity набор текста и цвета коснулся TextView. Проблема в том, что когда я касаюсь другого TextView, я теряю предыдущий коснутый TextView. Могу ли я использовать SharedPreference для магазина шаг за шагом все затронутые TextView? Например, если я установил TextView в позиции 1: 1 (строка: columm), и я хочу установить TextView 2: 2, как я могу поэтапно сохранить все TextView, чтобы не потерять их введенные данные?Как использовать SharedPreferences для сохранения значений TextView?

Некоторые Java от деятельности, что называем DialogActivity

public class ActivitySetOrario extends ActionBarActivity { 

//Static perch� cosi non perdo i dati inseriti in precedenza! 
static DataBase DB = new DataBase(); 
static int clickedTextViewId; // Declare TextView as class level member field 


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

}//Fine oncreate 

//Prende indietro la materia aggiunta dall'ActivityAddMateria 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if(requestCode == 1) { 
     if (resultCode == RESULT_OK) { 

      String result = data.getStringExtra("result"); //Take the materia from Dialog 
      int color = data.getIntExtra("color", 1); //Take the color from Dialog 

      Materia materia; 
      materia = new Materia(); 
      materia.setMateria(result); //put the name materia into class materia 
      materia.setColor(color); //put the color materia into class materia 
      DB.getMaterie().add(materia); 
      // Now use mTextView here 
      //View view = findViewById(clickedTextViewId); 
      TextView clickedtextView = (TextView) findViewById(clickedTextViewId); //(TextView) view; 
      if(clickedTextViewId == clickedtextView.getId()) { 
       clickedtextView.setText(result); 
       clickedtextView.setBackgroundColor(color); 
      } 
     } 

     if (resultCode == RESULT_CANCELED) { 
      //Nessuna materia inserita 
     } 
    } 
}//onActivityResult 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_set_orario, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 

    switch (item.getItemId()) { 
    case R.id.draw_orario: 
     //addMateria(); 
     return true; 
    case R.id.save_data_orario: 
     //SERIALIZZO I DATI CHE DOVRA PRENDERE ActivityOrario 
     backToOrario(); 
     return true;  
    case R.id.exit_orario: 
     //Torno alla schermata orario annullo ogni modifica NON SERIALIZZO 
     backToOrario(); 
     finish(); 
     return true;  
    case R.id.action_settings: 
     return true; 
    default: 
     return super.onOptionsItemSelected(item); 
    } 
} 

//Torna alla ActivityOrario 
public void backToOrario(){ 
    Intent myIntent = new Intent(ActivitySetOrario.this, ActivityOrario.class); 
    startActivity(myIntent); 
} 

public void addMateria(View v){ 
    //To get ID of your TextView do this 
    clickedTextViewId = v.getId(); 
    //StartActivityForResult perche mi aspetto la materia inserita dall'altra activity 
    Intent myIntent = new Intent(ActivitySetOrario.this, ActivityAddMateria.class); 
    ActivitySetOrario.this.startActivityForResult(myIntent, 1); 
} 
} 

Кодекс DialogActivty

public class ActivityAddMateria extends Activity { 

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

    final Button exit_button = (Button) findViewById(R.id.exit_dialog_materia); 
    exit_button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 

      //No input 
      Intent returnIntent = new Intent(); 
      setResult(RESULT_CANCELED, returnIntent); 
      //Exit from Dialog 
      finish(); 
     } 
    }); 

    final Button accept_button = (Button) findViewById(R.id.add_materia); 
    accept_button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 

      //Find EditText for take data 
      EditText nome_materia = (EditText)findViewById(R.id.nome_materia); 
      //Put result into variable result that is send back 
      String result = nome_materia.getText().toString(); 
      int color = getResources().getColor(R.color.rosso); 
      Intent returnIntent = new Intent(); 
      returnIntent.putExtra("result",result).putExtra("color",color); 
      setResult(RESULT_OK,returnIntent); 
      // Exit to Dialog 
      finish(); 
     } 
    }); 

} 
} 

Это хорошо sharedpreferences или лучше другой способ?

+0

Для больших объемов данных, вы должны смотреть в Sqlite. – JonasCz

ответ

1

SharedPreferences подходит для небольших объемов данных, в противном случае вам нужно будет изучить sqllite для хранения тяжелых данных.

на ваш вопрос, посмотрите на этот пост: How to use SharedPreferences in Android to store, fetch and edit values

+0

Но могу ли я использовать SharedPreferences для хранения только 3 или 4 TextView и после сериализации их в файл? Я хочу использовать SharedPreference для создания временного ввода TExtView и после сохранения их с помощью Sqlite или файла или с помощью кнопки ok. или max 30 TextView, введенный и сохраненный в SharedPreference, является тяжелым хранилищем данных? – Mario

+0

, если его более 30 было бы лучше всего пойти с SQLlite, общие настройки - простой способ для приложений с подсветкой данных (1-10 текстовых просмотров), однако в вашем случае лучше всего использовать sqllite с самого начала, поскольку передача sharedpreferences в sqllite может причиняют больше вреда, чем пользы. взгляните на это обсуждение и решите, что лучше всего подходит для вашего приложения в долгосрочной перспективе. http://stackoverflow.com/questions/6276358/pros-and-cons-of-sqlite-and-shared-preferences – Matchbox2093

+0

Но SharedPreference - это то же самое, чтобы создать файл и сохранить в нем результаты? Извините, но я новичок в android и java, может быть, мой вопрос настолько глуп! – Mario

Смежные вопросы