【问题标题】:Storing user input data in Internal Memory在内存中存储用户输入数据
【发布时间】:2011-08-16 16:59:48
【问题描述】:

我正在尝试创建一个简单的应用程序,它基本上是一个跟踪器,用于跟踪否。大学生每门学科的课程。该应用程序特定于我的大学时间表。这个想法是我有 3 个活动:main.java、Sublist.java 和 editcrap.java。 main.java 充当启动屏幕并启动 Sublist 活动。

在 Sublist 活动中,用户显示的布局显示 (TextView) (Button) (Counter_TextView) 彼此水平显示。其中有 7 个垂直对齐。

点击菜单按钮时:(编辑主题参数)出现,点击后将用户带到 editcrap.java 活动,其中用户输入在相应的 EditText 框中进行,询问每个对应的主题名称(TextView)和总数Sublist 活动中对应于 (Counter_TextView) 的类数。单击“确定”按钮后,数据将传递给子列表活动以进行显示和操作。

完成此操作后,我需要一种存储数据的方法,以便下次打开应用程序时,它会保留其先前的字符串并且不保留。类值。这是我遇到强制关闭错误或不保留数据错误的地方。这是我的代码... cud 有人请告诉我我做错了吗?我为此苦苦挣扎了好几天:)我基本上需要该应用程序来维护2个文件,其中一个文件包含字符串和其他需要读取并显示在Sublist.java活动中的数字,因为我们需要应用程序完成的任何更改用户也会反映到原始文件中

//Sublist.java:


package com.shuaib669.bunkrecord;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class Sublist extends Activity{

double[] no_of_classes = new double[7];
int count[]= new int[7];
double cutOff = 0.3;
String[] newText = new String[7];
String[] newNum = new String[7];
String countString = null;
TextView subject[] = new TextView[7];
TextView counter[] = new TextView[7];  //sub11 is counter text view label
Button button[] = new Button[7];     //button1 is the increment button


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Assigning Views to objects.
            subject[0] = (TextView) findViewById(R.id.textView1);   
            counter[0] = (TextView) findViewById(R.id.counter1);
            button[0] = (Button) findViewById(R.id.button1);

            subject[1] = (TextView) findViewById(R.id.textView2);
            counter[1] = (TextView) findViewById(R.id.counter2);
            button[1] = (Button) findViewById(R.id.button2);

            subject[2] = (TextView) findViewById(R.id.textView3);
            counter[2] = (TextView) findViewById(R.id.counter3);
            button[2] = (Button) findViewById(R.id.button3);

            subject[3] = (TextView) findViewById(R.id.textView4);
            counter[3] = (TextView) findViewById(R.id.counter4);
            button[3] = (Button) findViewById(R.id.button4);

            subject[4] = (TextView) findViewById(R.id.textView5);
            counter[4] = (TextView) findViewById(R.id.counter5);
            button[4] = (Button) findViewById(R.id.button5);

            subject[5] = (TextView) findViewById(R.id.textView6);
            counter[5] = (TextView) findViewById(R.id.counter6);
            button[5] = (Button) findViewById(R.id.button6);

            subject[6] = (TextView) findViewById(R.id.textView7);
            counter[6] = (TextView) findViewById(R.id.counter7);
            button[6] = (Button) findViewById(R.id.button7);

            try {
        // open the file for reading

        DataInputStream in= new DataInputStream(openFileInput(getFilesDir() + "/" + "subject.txt"));
        // if file the available for reading
        if (in!= null) {
          // prepare the file for reading
          String line;
          int x=0;
          // read every line of the file into the line-variable, on line at the time
          while(in.readLine() != null) {
              // do something with the strings from the file

              line=DataInputStream.readUTF(in);
              subject[x].setTextColor(Color.BLACK);
              subject[x].setText(line);
              x+=1;

          }

        }

        // close the file again
        in.close();
      } 
    catch (Exception e) {
        e.printStackTrace();// do something if the myfilename.txt does not exits
      }

    button[0].setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(count[0]>=(no_of_classes[0]*cutOff)){
                counter[0].setTextColor(Color.RED);
                countString = "" +(++count[0]);                 //Convert from int to String to set in your textview::
                counter[0].setText(countString);
            }
            else{
                countString = "" +(++count[0]);                 //Convert from int to String to set in your textview::
                counter[0].setText(countString);
            }


        }
    });

    button[1].setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(count[1]>=(no_of_classes[1]*cutOff)){
                counter[1].setTextColor(Color.RED);
                countString = "" +(++count[1]);                 //Convert from int to String to set in your textview::
                counter[1].setText(countString);
            }
            else{
                countString = "" +(++count[1]);                 //Convert from int to String to set in your textview::
                counter[1].setText(countString);
            }


        }
    });

    button[2].setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(count[2]>=(no_of_classes[2]*cutOff)){
                counter[2].setTextColor(Color.RED);
                countString = "" +(++count[2]);                 //Convert from int to String to set in your textview::
                counter[2].setText(countString);
            }
            else{
                countString = "" +(++count[2]);                 //Convert from int to String to set in your textview::
                counter[2].setText(countString);
            }


        }
    });

    button[3].setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(count[3]>=(no_of_classes[3]*cutOff)){
                counter[3].setTextColor(Color.RED);
                countString = "" +(++count[3]);                 //Convert from int to String to set in your textview::
                counter[3].setText(countString);
            }
            else{
                countString = "" +(++count[3]);                 //Convert from int to String to set in your textview::
                counter[3].setText(countString);
            }


        }
    });

    button[4].setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(count[4]>=(no_of_classes[4]*cutOff)){
                counter[4].setTextColor(Color.RED);
                countString = "" +(++count[4]);                 //Convert from int to String to set in your textview::
                counter[4].setText(countString);
            }
            else{
                countString = "" +(++count[4]);                 //Convert from int to String to set in your textview::
                counter[4].setText(countString);
            }


        }
    });

    button[5].setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(count[5]>=(no_of_classes[5]*cutOff)){
                counter[5].setTextColor(Color.RED);
                countString = "" +(++count[5]);                 //Convert from int to String to set in your textview::
                counter[5].setText(countString);
            }
            else{
                countString = "" +(++count[5]);                 //Convert from int to String to set in your textview::
                counter[5].setText(countString);
            }


        }
    });

    button[6].setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(count[6]>=(no_of_classes[6]*cutOff)){
                counter[6].setTextColor(Color.RED);
                countString = "" +(++count[6]);                 //Convert from int to String to set in your textview::
                counter[6].setText(countString);
            }
            else{
                countString = "" +(++count[6]);                 //Convert from int to String to set in your textview::
                counter[6].setText(countString);
            }


        }
    });



}

public boolean onCreateOptionsMenu(Menu menu){      // What the MENU button does.
    super.onCreateOptionsMenu(menu);
    MenuInflater castle = getMenuInflater();
    castle.inflate(R.menu.main_menu, menu);
    return(true);
}


public boolean onOptionsItemSelected(MenuItem item){  // Opens Options of MENU.

    switch(item.getItemId()){

    case R.id.editcrap: startActivityForResult((new Intent("com.shuaib669.bunkrecord.EDITCRAP")), 1);
                        return(true);
    }

return(false);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){

case 1: if(resultCode==Activity.RESULT_OK){

        newText = data.getStringArrayExtra("com.shuaib669.bunkrecord.thetext");
        newNum = data.getStringArrayExtra("com.shuaib669.bunkrecord.thenum");

        try {
              // open myfilename.txt for writing
        DataOutputStream out = new DataOutputStream(openFileOutput(getFilesDir() + "/" + "subject.txt", Context.MODE_PRIVATE));     
        //newNum = data.getIntArrayExtra("com.shuaib669.thenum");
        //for loop to setText in the TextViews of main.xml
        for(int x=0;x<7;x++){



                    subject[x].setTextColor(Color.BLACK);
                    subject[x].setText(newText[x]);
                    // write the contents on mySettings to the file
                    out.writeUTF(newText[x]);

                    try{
                        no_of_classes[x]=Integer.parseInt(newNum[x]);
                        }
                        catch(Exception nfe){
                            nfe.printStackTrace();
                        }         
                  // close the file
                  out.close();
                  }
        }


        catch (Exception e) {
                    Log.i("Data Input Sample", "I/O Error");    //do something if an Exception occurs.
                }



            }


break;
}                                             


}
  } 

//editcrap.java:

package com.shuaib669.bunkrecord;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class editcrap extends Activity{

EditText sub[] = new EditText[7];           //list of subject text edit labels.
Button parambutton1;                                            //OK buttons for edit list.
EditText num[] = new EditText[7];           //list of objects of total no. of classes bunked edit text labels. (boinkers i know)  
String theText[] = new String[7];
String theNum[] = new String[7];

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.params);

    sub[0] = (EditText) findViewById(R.id.peditText1);          //pedittext is the parameter menu edit text label
    num[0] = (EditText) findViewById(R.id.pnumText1);           //EditText label for takin in total no. of classes for 1 subject

    sub[1] = (EditText) findViewById(R.id.peditText2);
    num[1] = (EditText) findViewById(R.id.pnumText2);

    sub[2] = (EditText) findViewById(R.id.peditText3);
    num[2] = (EditText) findViewById(R.id.pnumText3);

    sub[3] = (EditText) findViewById(R.id.peditText4);
    num[3] = (EditText) findViewById(R.id.pnumText4);

    sub[4] = (EditText) findViewById(R.id.peditText5);
    num[4] = (EditText) findViewById(R.id.pnumText5);

    sub[5] = (EditText) findViewById(R.id.peditText6);
    num[5] = (EditText) findViewById(R.id.pnumText6);

    sub[6] = (EditText) findViewById(R.id.peditText7);
    num[6] = (EditText) findViewById(R.id.pnumText7);

    parambutton1 = (Button) findViewById(R.id.parambutton1);    //pbutton1 is the ok button to accept the input.

    parambutton1.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub


            for(int x=0;x<7;x++){


                    theText[x] = sub[x].getText().toString();
                    theNum[x]  = num[x].getText().toString();
                    //theNum[x]  = Integer.parseInt(num[x].getText().toString());

                }



            Intent data = new Intent(editcrap.this, Sublist.class);
            data.putExtra("com.shuaib669.bunkrecord.thetext", theText);
            data.putExtra("com.shuaib669.bunkrecord.thenum", theNum);
            setResult(Activity.RESULT_OK, data);
            finish();

        }
    });


}




}

【问题讨论】:

  • 为什么不使用共享首选项?
  • 为什么不使用 SQLite 数据库。或者你可以做一个 SharedPreference,看起来就是这样。
  • 好的,我会这样做...:)...感谢您的建议 :)
  • 这只是比将它们放入文件要容易得多,SharedPreferences 可以采用原语(int,bool,String)并将它们保存在一个名称下,因此您知道哪些是哪些。
  • 我无法理解共享首选项及其相关方法的工作原理......使用共享首选项保存和检索数据的重要步骤是什么?

标签: android android-layout android-emulator android-manifest


【解决方案1】:

使用共享首选项

public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";

onCreate() 方法中的以下代码

EtUserName=(EditText) findViewById(R.id.EditText01);
EtPassword=(EditText) findViewById(R.id.EditText02);

在这里您可以在 editText 中获得 Preferences 值...(如果您以前保存过 Preferences)

SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);   
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null); 

EtUserName.setText(username);  
EtPassword.setText(password);

复选框单击事件中的以下代码...(在此处保存首选项)

             String us,pa;
         us=EtUserName.getText().toString();
         pa=EtPassword.getText().toString();
         SharedPreferences settings = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
                         getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
                         .edit()
                         .putString(PREF_USERNAME, us)
                         .putString(PREF_PASSWORD, pa)
                         .commit();

更多信息click here.andhere

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多