简体   繁体   English

在一个类中设置一个值并从Java中的另一个类中检索(Android应用程序)

[英]Setting a value in one class and retrieving from another class in Java (Android app)

I am setting an id from my Main class when the user enters it on start of the app. 当用户在应用程序启动时输入id时,我将从我的Main类设置一个id。 taking that I set it in a class called GetSet.java which also has a method to return it on being called. 我把它设置在一个名为GetSet.java的类中,它也有一个方法可以在被调用时返回它。 So I need the id set from this first class in a class called MySQLitehelper.java so I can retrieve the data according to the id set instead of hardcoding it. 所以我需要在名为MySQLitehelper.java的类中从第一个类中设置id,这样我就可以根据id集检索数据而不是硬编码。 This will make my app dynamic rather than static. 这将使我的应用程序动态而不是静态。 Here is my Code: 这是我的代码:

/ ----MainActivity.java----- / / ---- MainActivity.java ----- /

public class MainActivity extends Activity {

EditText etGWid;
Button OKbtn;

public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

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


    etGWid = (EditText)findViewById(R.id.etGWID);
    OKbtn = (Button)findViewById(R.id.OKbtn);

    final GetSet obj_getset = new GetSet();
    //MySQLitehelper db = new MySQLitehelper(null);

    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);  
            // Create a shared preferences variable using the SharedPreferenceManager for storing GWids

    SharedPreferences.Editor editor = app_preferences.edit();  // We also need a shared preferences editor to handle the shared preference requests
    // Call the edit method (library function) to editor variable can edit the key, values.

    editor.putInt("47688507", 47688507);   // put in the shared preferences values of user GWids and give them a key for retrieval purposes
    editor.putInt("1234567", 1234567);
    editor.putInt("7654321", 7654321);

    editor.commit();   //commit is necessary to save the shared preferences



    OKbtn.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            String gwidCheck = etGWid.getText().toString();  //get the value user enters for GWid

            if(app_preferences.contains(gwidCheck))       // this will check the stored shared preferences and compare with the value entered
            {
                Context context = getApplicationContext();
                CharSequence text = "Login Successfull";
                int duration = Toast.LENGTH_SHORT;                              //If it exists, then create a toast message for success



                //etGWid.setText("");    // make the textbox empty
                long setid = Long.parseLong(gwidCheck);   // take the string gwid and convert to long
                obj_getset.setId(setid);    // set the gwid entered



                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                intentfunction();
            } 
            else
            {
                Context context = getApplicationContext();
                CharSequence text = "Login Failed";                     // If doesnt exist, create a toast for fail
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }

        }
    });
}


private void intentfunction()
{
     Intent intent = new Intent(this, SelectOptions.class);
     //editText = (EditText) findViewById(R.id.editText1);
     //editText = new EditText(this);
     etGWid.setText("");   //set the edit text to blank
    String message = "TestHello";
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);

}
@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_main, menu);
    return true;
}

}

/*-----GetSet.java----*/

public class GetSet {

long gwid=0;

public void setId(long id)
{
    gwid = id;
}

public long getId()
{
    return gwid;
}

}

/ ---MySQLitehelper.java--- / / --- MySQLitehelper.java --- /

public class MySQLitehelper {

//public static final String TABLE_COMMENTS = "comments";
  public static final String COLUMN_ID = "GWid";
  public static final String COLUMN_DATE = "DateGWU";
  public static final String COLUMN_LOCATION = "location";
  public static final String COLUMN_TIME = "time";

  public static final String TABLE_NAME = "UPDTable";

  private static final String DATABASE_NAME = "UPDdb_version6";
  private static final int DATABASE_VERSION = 6;

  private final Context context;
  GetSet getset = new GetSet();
  public void GetIdForGwid(GetSet get)
  {
     getset=get; 
  }

  // Database creation sql statement
  private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_NAME +
                                " (" +COLUMN_ID+ " integer," + COLUMN_DATE + " VARCHAR," +
                                COLUMN_LOCATION+" VARCHAR," +COLUMN_TIME +" VARCHAR);";

//  private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME +
//                                              " Values (47688507,'DEC-07-2012','MARVIN 203','20:00');";

  private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +
          COLUMN_LOCATION+" ," +COLUMN_TIME +" )"  +
                          " Values (47688507,'DEC-07-2012','MARVIN 203','20:00');";



  DatabaseHelper dbhelper;
  SQLiteDatabase db;




 public MySQLitehelper(Context ctx)
  {
      this.context = ctx;
      dbhelper = new DatabaseHelper(ctx);
  }



private static class DatabaseHelper extends SQLiteOpenHelper {

     public DatabaseHelper(Context context)
     {
         super(context,DATABASE_NAME, null,DATABASE_VERSION);
     }

 @Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(DATABASE_CREATE);            //execute create table
    db.execSQL(DATABASE_INSERT);            //execute insert query
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (47688507,'DEC-22-2012','OLD MAIN','23:00');");
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (1234567,'DEC-14-2012','FUNGER','12:00');");
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (7654321,'DEC-29-2012','GELMAN','22:00');");
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (47688507,'DEC-12-2012','IVORY','23:00');");
 }

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    Log.w(MySQLitehelper.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}


// open the DB
 public MySQLitehelper open() throws SQLException
 {
    System.out.println("Inside open function");
     db = dbhelper.getWritableDatabase();
    return this;
 }

 public void close()
 {
     dbhelper.close();
 }



 public void insertRecord(long gwid, String date, String location, String time)
     {
           ContentValues initialValues = new ContentValues();
          initialValues.put(COLUMN_ID, gwid);
          initialValues.put(COLUMN_DATE, date);
          initialValues.put(COLUMN_LOCATION, location);
          initialValues.put(COLUMN_TIME, time);
          db.insert(TABLE_NAME, null, initialValues);
     }

public Cursor getAllrows()      //function to get all rows in the DB. Testing initially.
{

     Cursor cur = db.rawQuery("SELECT * FROM "+TABLE_NAME, null);
     return cur;
}

public Cursor getRecord() throws SQLException
{
        Cursor mCursor =
        db.query(true, TABLE_NAME, new String[] {COLUMN_ID,
        COLUMN_DATE, COLUMN_LOCATION, COLUMN_TIME},
        COLUMN_ID + "= 47688507", null, null, null, null, null);   //HARDCODED. Please make it dynamic
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
 return mCursor;
 }

}

I am retrieving it in the getRecord() method in the above class right at the bottom,instead of COLUMN_ID + "= 47688507 i wish to get the set value from the GetSet class ( getId method) and replace it in place of 47688507 . Any suggestions ? 我正在底部的上面的类中的getRecord()方法中检索它,而不是COLUMN_ID + "= 47688507我希望从GetSet类( getId方法)获取设置值并替换它代替47688507 。建议?

Read up on the "Singleton pattern", which is a way to create a persistent object to hold information to be passed from place to place. 阅读“单例模式”,这是一种创建持久对象的方法,用于保存要从一个地方传递到另一个地方的信息。

However, bear in mind that once onPause() has been called on your Activity, the system is free to destroy your application completely, and reconstruct it later. 但是,请记住,一旦在Activity上调用onPause() ,系统就可以完全销毁你的应用程序,并在以后重新构建它。 This means that even a singleton class is no guarantee that your data will be there when your application restarts. 这意味着即使单个类也无法保证在应用程序重新启动时您的数据将存在。 You must ALWAYS be prepared to restore your state from persistent storage in your onCreate() method. 您必须始终准备好在onCreate()方法中从持久存储中恢复您的状态。

Here's how I used a singleton class to implement a global preferences holder: In short, any place you have a Context, you can call Prefs.getPrefs() to get the preferences object. 以下是我使用单例类实现全局首选项持有者的方法:简而言之,您拥有Context的任何地方,您都可以调用Prefs.getPrefs()来获取首选项对象。 On the first call, it will read the preferences from persistent storage. 在第一次调用时,它将从持久存储中读取首选项。 On all subsequent calls, it just returns the pointer to the object already loaded. 在所有后续调用中,它只返回指向已加载对象的指针。 If your application is killed by the system and restarted, getPrefs() seamlessly re-reads the preferences as needed. 如果您的应用程序被系统杀死并重新启动,则getPrefs()会根据需要无缝地重新读取首选项。

/**
 * This is a singleton class to hold preferences.
 */
public class Prefs {
    private static volatile Prefs instance = null;

    // The values held by this class
    String identity = null;
    String apiUrl = "http://example.com/cgi-bin/api";
    int interval = 3600;    // when there's no activity

    /**
     * Return the single instance of this class, creating it
     * if necessary. This method is thread-safe.
     */
    public static Prefs getPrefs(Context ctx) {
        if (instance == null) {
            synchronized(Prefs.class) {
                if (instance == null) {
                    instance = new Prefs();
                    instance.readPrefs(ctx);
                }
            }
        }
        return instance;
    }

    /**
     * Re-read all preferences (you never need to call this explicitly)
     */
    private void readPrefs(Context ctx) {
        try {
            SharedPreferences sp =
                PreferenceManager.getDefaultSharedPreferences(ctx);
            identity = sp.getString("identity", identity);
            apiUrl = sp.getString("apiUrl", apiUrl);
            interval = sp.getInt("interval", interval);
        } catch (Exception e) {
            Log.e(TAG, "exception reading preferences: " + e, e);
            // TODO: report it
        }
    }

    /**
     * Save preferences; you can call this from onPause()
     */
    public void savePrefs(Context ctx) {
        try {
            SharedPreferences.Editor sp =
              PreferenceManager.getDefaultSharedPreferences(ctx).edit();
            sp.putString("identity", identity);
            sp.putString("apiUrl", apiUrl);
            sp.putInt("interval", interval);
            sp.commit();
        } catch (Exception e) {
            Log.e(TAG, "exception reading preferences: " + e, e);
            // TODO: report it
        }
    }

    /**
     * Save preferences to a bundle. You don't really need to implement
     * this, but it can make start-up go faster.
     * Call this from onSaveInstanceState()
     */
    public void onSaveInstanceState(Bundle state) {
        state.putString("identity", identity);
        state.putString("apiUrl", apiUrl);
        state.putInt("interval", interval);
    }

    /**
     * Recall preferences from a bundle. You don't really need to implement
     * this, but it can make start-up go faster.
     * Call this from onCreate()
     */
    public void restoreInstanceState(Bundle state) {
        identity = state.getString("identity");
        apiUrl = state.getString("apiUrl");
        interval = state.getInt("interval");
    }
}
  • Use a global singleton to store and retrieve data . 使用全局单例来存储和检索数据 When you do this, make sure that the singleton doesnt hold a reference to your activity or context. 执行此操作时,请确保单例不包含对您的活动或上下文的引用。
  • Since mysqlitehelper has a reference to context, you can also retrieve persisted data from SharedPreferences. 由于mysqlitehelper具有对上下文的引用,因此您还可以从SharedPreferences中检索持久数据。
  • - -

I think, you should be able to use your instance variable obj_getset to set the id with 我想,您应该能够使用实例变量obj_getset来设置id

obj_getset.setid(mCursor.COLUMN_ID)

in your getRecord function then retrieve it the same way when you need to 在你的getRecord函数中,然后在需要时以相同的方式检索它

obj_getset.getID()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中将值从一类设置为另一类 - Setting value from one class to another in Java 设置Java中另一个类的变量的值 - Setting the value of a variable from another class in Java 如何在Java(Android)中将变量的值从一个类调用到另一个类 - How to call the value of variables from one class to another in Java (Android) Android Java:设置从一个活动发送到另一个 Java 类的参数时出错 - Android Java: Error in setting parameter sent from one activity to another java class JAVA将价值从一个类传递到另一个类 - JAVA get the value from one class to another Java-从一类到另一类的变量值 - Java - variable value from one class to another class 在Java中将变量值从一个类传递到另一个类 - Passing a variable value from one class to another class in java 从一个类获取价值以在另一个类中使用它(java) - Get value from one class to use it in another class (java) Android帮助,试图将价值从一个类转移到另一个类(Android应用) - Android help, trying to get value moved from one class to another (android app) 将一个类从一个应用程序复制到另一个应用程序后,Android发出ClassNotFoundException异常 - ClassNotFoundException android after copy a class from one app to another one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM