如何将我的主线程与创建的工作线程连接?

时间:2018-03-10 18:45:57

标签: java multithreading android-studio download android-room

嘿我在android studio java上使用房间数据库时遇到了麻烦。 当我点击保存按钮时,我正在尝试保存类的组件。 但问题是在主线程上使用保存或下载调用是一件坏事,所以我正在创建自己的线程,但是如何在该线程之外使用数据呢?我这样做的课程看起来像这样......

更新:这应该可行吗?

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();



    }
}

在负载方面我这样做了吗?

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();




    }




}

那么,如果我点击按钮我想将数据保存到房间数据库然后离开视图,我该怎么做?

1 个答案:

答案 0 :(得分:1)

每当您使用场所时,例如在JavaScript中,您不确定何时会实现该前提,或者换句话说,当您的日期可用时。所以通常做的是在更高的范围内声明变量,这将使它既可以应用于应该设置它的线程(worker),也可以用于应该使用它的那个(main)。

<强>更新

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();
  }
}

您可以注意到,在获取数据的方法中,不会返回任何内容。由于它是异步操作,因此您不知道何时会实现它。你最终会知道它会是。所以你要等到它可用(remoteData != null)。