简体   繁体   中英

How do i connect my main thread with a created worker thread?

Hey I have a trouble with using a room database on android studio java. I am trying to save the components of a class when I click on a save button. but the thing is that it is a bad thing to use a save or download call on a main thread so I am creating my own thread but how do I then outside of that thread use the data? my class that I'm doing this in looks like this...

UPDATE: Should this work then?

package com.example.jenso.paperseller;

import android.arch.persistence.room.Room;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CreateCustomer extends AppCompatActivity {
    EditText name;
    EditText address;
    EditText phonenumber;
    EditText email;
    Button saveCustomer;
    PapperSellerDatabase pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_customer);
        name = findViewById(R.id.nameInput);
        address = findViewById(R.id.addressInput);
        phonenumber = findViewById(R.id.phonenumberInput);
        email = findViewById(R.id.emailInput);
        saveCustomer = findViewById(R.id.saveInput);
        setTheDataBase();


        saveCustomer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CreateCustomer.this, MainActivity.class));
                pd.customerDao().insertAll(new Customer(name.getText().toString(),address.getText().toString(),phonenumber.getText().toString(),email.getText().toString()));
            }
        });




    }
    public void setTheDataBase(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //here you obtain data from async source
                PapperSellerDatabase pd = Room.databaseBuilder(getApplicationContext(),PapperSellerDatabase.class,"production")
                        .fallbackToDestructiveMigration()
                        .build();


            }
        }).start();



    }
}

and on the load side I do this?

package com.example.jenso.paperseller;

import android.arch.persistence.room.Room;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.ThemedSpinnerAdapter;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    List<Customer> customers;
    PapperSellerDatabase database;


    FloatingActionButton fab;
    private static final  String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        recyclerView = findViewById(R.id.recycler);
        customers = new ArrayList<>();


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new PapperRecyclerAdapter(customers,this);
        recyclerView.setAdapter(adapter);

        downloadTheData();

        fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: Do this when you click");
                startActivity(new Intent(MainActivity.this, CreateCustomer.class));
            }

        });



    }
    private void downloadTheData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //here you obtain data from async source
                PapperSellerDatabase pd = Room.databaseBuilder(getApplicationContext(),PapperSellerDatabase.class,"production")
                        .fallbackToDestructiveMigration()
                        .build();


                customers = pd.customerDao().getAllCustomers();

            }
        }).start();




    }




}

so how would I go further with if I click the button I wanna save the data to the room database and then leave the view?

Whenever you work with premises, as in JavaScript for instance, you are not sure when the premise will be fulfilled, or in other words, when your date will become available. So what is usually done is to declare the variable in higher scope, which will make it available both to the thread that should set it (worker) and to the one should use it (main).

Update

public class Example {
  //here you initialize your variable that will contain data
  List <RemoteData> remoteData = null;

  ....

  public void hereRemoteDataIsUsed(){
     if(remoteData != null){ 
        //use remoteData here
        ...
     }
  }

  ....
  public void hereRemoteDataIsSet(){
      new Thread(new Runnable() {
          @Override
          public void run() {
            //here you obtain data from async source     
            remoteData = getDataFromSomeAsyncSource();
          }
    }).start();
  }
}

You can notice that in the method where the data is obtained nothing is returned. Since it is an asynchronous operation you don't know when it will be fulfilled. You just know that it will be, eventually. So you just wait until it is available ( remoteData != null ).

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