简体   繁体   中英

I'm trying to store values from with a method to an object created earlier

So I'm still relatively new to java and android. I am trying to figure out if there is a way that I can store 2 values from inside methods of SomeClass to an object.

public class MainClass extends ...{

    Output outputObject = new Output();

    @Override
    protected void onCreate(Bundle savedInstanceState) {


        SomeClass classTask = new SomeClass(params) {
            @Override
            public void processFinish(String output) {
                outputObject.setVarOutput(output);
            }
        }
        classTask1.execute(link);




        SomeClass classTask2 = new SomeClass(params) {
            @Override
            public void processFinish(String output) {
                outputObject.setVar2Output(output);
            }
        }
        classTask2.execute(link2);


        // gather the outputObject values
        //for example
        result = outputObject.getVarOutput() + getVar2Output();
    }
    });

I've tried a few things to no avail. I'm not sure what to look for or into.

if there is a way that I can store 2 values from inside methods of SomeClass to an object.

Yes there is.

It is difficult to tell why the code you've provided isn't working for you as the names you've used are very abstract. I can assume

execute()

will do some computation, maybe on a different thread. If that is the case then you want to avoid touching the same object from different threads.

I can't give better advice without knowing more about what you're trying to do.

My first thought is that execute() does not go down the expected path and processFinish() is not called as expected. Can't know for sure without seeing the details of SomeClass.

Second, this isn't thread-safe from a long shot, because simultaneous onCreate() calls are going to result in both threads trying to update the object at the same time. Can't guarantee what you'll get, it's a race condition, but as soon as you mentioned database my ears perked up.

Now, if you make outputObject stored in thread-local storage, then at least concurrency isn't a problem, but if it's not the same thread reading as populating the objects, that's not going to work either. Of course, you could synchronize on outputObject, so you get your concurrency at the loss of scalability.

For me, the best solution is one where you create a unique outputObject per onCreate() call and figure out a way to get the data base to the outside world (which maybe isn't necessary since you're dumping the data right there)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM