如何使一个对象可以被Android程序中的所有活动访问?

发布于 2024-12-28 01:34:17 字数 269 浏览 3 评论 0原文

我有一个应用程序,其中包含两个活动/屏幕和一个我从中创建对象的java类。

我需要在第二个活动中使用在第一个活动(实例化 .java 类)中创建的对象。

最简单的方法是什么?我用谷歌搜索了一下,在 java 类上实现 Parcelable 接口似乎是这个问题最常见的答案。但这个对象有点复杂,分割它的每个成员似乎是一个蛮力解决方案。

难道就没有一个优雅的解决方案吗?

谢谢

编辑:将对象数据存储在简单的 SQlite 数据库上是一个解决方案吗?

I have an application which consists of two activities/screens and a java class from which i create objects.

I need to use an object I created on the first activity (instanciating the .java class) on the second activity.

What is the simplest way to do this? I googled about it and implementing the Parcelable interface on the java class seems to be the most common answer to this problem. But the object is kind of complex and parceling every single member of it seems like a brute-force solution.

Isn't there an elegant solution to this?

Thanks

EDIT: Is storing the object data on a simple SQlite database a solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韵柒 2025-01-04 01:34:18

您可以使用应用程序上下文(尽管这基本上是存储全局状态,因此您需要小心如何使用它):

到处使用应用程序上下文?

You could use the application context (although this is basically storing global state so you need to be careful how you're using it):

Using Application context everywhere?

未央 2025-01-04 01:34:18

在活动之间传递信息的最简单方法之一是使用捆绑

您可以在启动新活动之前向 Intent 添加额外内容

在另一端(另一个活动),您可以从 Bundle 中接收这些额外,并可能在新活动中重建对象。

这是一个示例:

首先,这是学生类:

Student 类 - Student.java:

package com.stephendiniz.objectsharing;

public class Student 
{
    int id;
    String name;
    String profession;

    Student()
    {
        id = 0;
        name = "";
        profession = "";
    }

    Student(int id, String name, String profession)
    {
        this.id = id;
        this.name = name;
        this.profession = profession;
    }

    public int getId()              { return id; }
    public String getName()         { return name; }
    public String getProfession()   { return profession; }
}

Main Activity 将引用 Student 类来生成对象 s

Main Activity - AndroidObjectSharing.java:

package com.stephendiniz.objectsharing;

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

public class AndroidObjectSharingActivity extends Activity
{
    TextView id;
    TextView name;
    TextView profession;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        id = (TextView)findViewById(R.id.id);
        name = (TextView)findViewById(R.id.name);
        profession = (TextView)findViewById(R.id.profession);

        Button submitButton = (Button)findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener()
            {
            final Intent newActivity = new Intent(AndroidObjectSharingActivity.this, NewActivity.class);
                public void onClick(View v)
                {
                    Student s = new Student(Integer.parseInt(id.getText().toString()), name.getText().toString(), profession.getText().toString());
                    newActivity.putExtra("extraStudentId", s.getId());
                    newActivity.putExtra("extraStudentName", s.getName());
                    newActivity.putExtra("extraStudentProfession", s.getProfession());

                    startActivity(newActivity);
                }
            });
    }
}

这是绑定到的 XML学生类:

主 XML 布局 - main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student ID:" />
    <EditText
        android:id="@+id/id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="9001" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Name:" />
    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Steve" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Profession:" />
    <EditText
        android:id="@+id/profession"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Computer Engineer" />

    <Button
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:text="Send to New Activity" />

</LinearLayout>

请注意,NewActivity 从 Bundle(在本例中名为 infoBundle)访问信息。 。

该对象以编程方式“重建”,就像它已被传递一样

新活动 - NewActivity.java:

package com.stephendiniz.objectsharing;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class NewActivity extends Activity
{
        LinearLayout ll;

        TextView id;
        TextView name;
        TextView profession;

        private final static String TAG = "NewActivity";
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Bundle infoBundle = getIntent().getExtras();
        Student s = new Student(infoBundle.getInt("extraStudentId"), infoBundle.getString("extraStudentName"), infoBundle.getString("extraStudentProfession"));

        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        id = new TextView(this);
        name = new TextView(this);
        profession = new TextView(this);

        id.setText("Student Id: " + s.getId() + "\n");
        name.setText("Student Name: " + s.getName() + "\n");
        profession.setText("Student Profession: " + s.getProfession() + "\n");

        ll.addView(id);
        ll.addView(name);
        ll.addView(profession);

        Button closeButton = new Button(this);
        closeButton.setText("Close Activity");
        closeButton.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    finish();
                }
            });

        ll.addView(closeButton);

        setContentView(ll);
    }
}

不要忘记将新活动添加到您的清单中!

Android Manifest - AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stephendiniz.objectsharing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidObjectSharingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".NewActivity"
            android:label="New Activity" />
    </application>

</manifest>

对于 XML 和编程脚本的混合感到抱歉,我在第一个 Activity 之后意识到需要显示很多文件,所以我压缩了最后一个文件,但你应该能够得到这个想法..

希望这有帮助!

One of the easiest ways to pass information between activities is to use Bundles.

You can add extras to an Intent before launching a new Activity.

On the other end (the other activity) you can then receive these extras out of the Bundle and possibly rebuilt the Object in the new activity..

Here's an Example:

First of all, here's the Student Class:

Student Class - Student.java:

package com.stephendiniz.objectsharing;

public class Student 
{
    int id;
    String name;
    String profession;

    Student()
    {
        id = 0;
        name = "";
        profession = "";
    }

    Student(int id, String name, String profession)
    {
        this.id = id;
        this.name = name;
        this.profession = profession;
    }

    public int getId()              { return id; }
    public String getName()         { return name; }
    public String getProfession()   { return profession; }
}

The Main Activity will reference the Student class to generate an object s

Main Activity - AndroidObjectSharing.java:

package com.stephendiniz.objectsharing;

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

public class AndroidObjectSharingActivity extends Activity
{
    TextView id;
    TextView name;
    TextView profession;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        id = (TextView)findViewById(R.id.id);
        name = (TextView)findViewById(R.id.name);
        profession = (TextView)findViewById(R.id.profession);

        Button submitButton = (Button)findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener()
            {
            final Intent newActivity = new Intent(AndroidObjectSharingActivity.this, NewActivity.class);
                public void onClick(View v)
                {
                    Student s = new Student(Integer.parseInt(id.getText().toString()), name.getText().toString(), profession.getText().toString());
                    newActivity.putExtra("extraStudentId", s.getId());
                    newActivity.putExtra("extraStudentName", s.getName());
                    newActivity.putExtra("extraStudentProfession", s.getProfession());

                    startActivity(newActivity);
                }
            });
    }
}

Here's the XML that is tied to the Student Class:

Main XML Layout - main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student ID:" />
    <EditText
        android:id="@+id/id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="9001" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Name:" />
    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Steve" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Profession:" />
    <EditText
        android:id="@+id/profession"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Computer Engineer" />

    <Button
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:text="Send to New Activity" />

</LinearLayout>

Note that the NewActivity accesses the information from a Bundle (named infoBundle in this case)..

The object is "rebuilt" programmatically as if it was passed.

New Activity - NewActivity.java:

package com.stephendiniz.objectsharing;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class NewActivity extends Activity
{
        LinearLayout ll;

        TextView id;
        TextView name;
        TextView profession;

        private final static String TAG = "NewActivity";
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Bundle infoBundle = getIntent().getExtras();
        Student s = new Student(infoBundle.getInt("extraStudentId"), infoBundle.getString("extraStudentName"), infoBundle.getString("extraStudentProfession"));

        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        id = new TextView(this);
        name = new TextView(this);
        profession = new TextView(this);

        id.setText("Student Id: " + s.getId() + "\n");
        name.setText("Student Name: " + s.getName() + "\n");
        profession.setText("Student Profession: " + s.getProfession() + "\n");

        ll.addView(id);
        ll.addView(name);
        ll.addView(profession);

        Button closeButton = new Button(this);
        closeButton.setText("Close Activity");
        closeButton.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    finish();
                }
            });

        ll.addView(closeButton);

        setContentView(ll);
    }
}

Don't forget to add the new activity to your Manifest!

Android Manifest - AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stephendiniz.objectsharing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidObjectSharingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".NewActivity"
            android:label="New Activity" />
    </application>

</manifest>

Sorry for the mix of XML and Programmatic Scripting, I realized after the first Activity that it would be a lot of files to display so I condensed the last file, but you should be able to get the idea..

Hope this helps!

月亮邮递员 2025-01-04 01:34:18
class Bike{
private static int id;
public static int getId() 
{
    return id;
}
public static void setId(int id) 
{
    Bike.id = id;
}
public static String getName() 
{
    return name;
}

public static void setName(String name)
{
    Bike.name = name;
}
private static String name;

 }


 class Honda4 {

 public static void main(String args[]){

     Bike.setName("Duraivel");
     Bike.setId(1);
     GetValue g = new GetValue();

 }
 }

 class GetValue
 {
     {
         System.out.print("Bike Name"+ Bike.getName());
         System.out.print("Bike ID "+ Bike.getId()); 
     }
 }
class Bike{
private static int id;
public static int getId() 
{
    return id;
}
public static void setId(int id) 
{
    Bike.id = id;
}
public static String getName() 
{
    return name;
}

public static void setName(String name)
{
    Bike.name = name;
}
private static String name;

 }


 class Honda4 {

 public static void main(String args[]){

     Bike.setName("Duraivel");
     Bike.setId(1);
     GetValue g = new GetValue();

 }
 }

 class GetValue
 {
     {
         System.out.print("Bike Name"+ Bike.getName());
         System.out.print("Bike ID "+ Bike.getId()); 
     }
 }
美人如玉 2025-01-04 01:34:18

我认为 Singleton 是创建可在所有活动中访问的对象的正确方法。它是一种只能创建一次的对象,如果您尝试再次访问它,它将返回该对象的现有实例。有关其工作原理的更多信息,请参阅答案。

I think Singleton is the right way to create an object accessible in all activities. It's a kind of object that only can be created once, and if you try to access it again it will return the existing instance of the object. See this answer for more information about how it works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文