Java 领域对象只能在创建它们的线程上访问
我从一个url下载JSON数据,因为我计划在许多活动中使用它,所以我使用Realm离线存储它,现在当我尝试从mainactivity访问存储的数据时,它工作正常,但是数据是这样的,它是一个arraylist,由另外两个arraylist(嵌套arraylist)组成。 因此,每当我想访问第二个屏幕中主对象的一个ArrayList时,我都会将对象的位置从主屏幕发送到第二个屏幕。我正试图从那里获取数据。但这表明了这一错误 任何帮助都将不胜感激。提前谢谢 堆栈跟踪Java 领域对象只能在创建它们的线程上访问,java,android,json,multithreading,realm,Java,Android,Json,Multithreading,Realm,我从一个url下载JSON数据,因为我计划在许多活动中使用它,所以我使用Realm离线存储它,现在当我尝试从mainactivity访问存储的数据时,它工作正常,但是数据是这样的,它是一个arraylist,由另外两个arraylist(嵌套arraylist)组成。 因此,每当我想访问第二个屏幕中主对象的一个ArrayList时,我都会将对象的位置从主屏幕发送到第二个屏幕。我正试图从那里获取数据。但这表明了这一错误 任何帮助都将不胜感激。提前谢谢 堆栈跟踪 FATAL EXCEPTIO
FATAL EXCEPTION: main
Process: com.example.vamshi.baking, PID: 2643
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vamshi.baking/com.example.vamshi.baking.UI.SecondScreenDetails}: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
at android.app.ActivityThread.access$1000(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
at io.realm.BaseRealm.checkIfValid(BaseRealm.java:385)
at io.realm.IngredientsRealmProxy.realmGet$quantity(IngredientsRealmProxy.java:98)
at com.example.vamshi.baking.Data.Ingredients.getQuantity(Ingredients.java:28)
at com.example.vamshi.baking.UI.SecondScreenDetails.setDisplay(SecondScreenDetails.java:63)
at com.example.vamshi.baking.UI.SecondScreenDetails.onCreate(SecondScreenDetails.java:42)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2402)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
at android.app.ActivityThread.access$1000(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-04 17:42:44.452 2643-2643/com.example.vamshi.baking E/MQSEventManagerDelegate: failed to get MQSService.
主要活动
public class MainActivity extends AppCompatActivity {
public static ListView myList;
public static ListAdapter myAdapter;
public static Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm.init(this);
realm = Realm.getDefaultInstance();
DownloadTask newTask = new DownloadTask();
newTask.execute("hi");
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.Recipe_list);
// getData();
setDisplay();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String p = String.valueOf(position);
// Toast.makeText(MainActivity.this, p, Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, SecondScreenDetails.class);
in.putExtra("Position", p);
startActivity(in);
}
});
}
public void setDisplay(){
ArrayList<Recipe> finalRecipies = new ArrayList<>();
RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
for(Recipe r: rrRecipies){
finalRecipies.add(r);
// Toast.makeText(this, r.getName(), Toast.LENGTH_SHORT).show();
}
myAdapter = new ListViewAdapter(this, finalRecipies);
myList.setAdapter(myAdapter);
}
@Override
protected void onDestroy() {
realm.close();
super.onDestroy();
}
}
public类MainActivity扩展了AppCompatActivity{
公共静态列表视图myList;
公共静态列表适配器myAdapter;
公共静态领域;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Realm.init(this);
realm=realm.getDefaultInstance();
DownloadTask newTask=新的DownloadTask();
newTask.execute(“hi”);
setContentView(R.layout.activity_main);
myList=(ListView)findViewById(R.id.Recipe\u列表);
//getData();
setDisplay();
myList.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
字符串p=字符串.valueOf(位置);
//Toast.makeText(MainActivity.this,p,Toast.LENGTH_SHORT).show();
Intent in=新的Intent(MainActivity.this,SecondScreenDetails.class);
in.putExtra(“位置”,p);
星触觉(in);
}
});
}
公共void setDisplay(){
ArrayList finalRecipies=新的ArrayList();
RealmResults rrRecipies=realm.where(Recipe.class).findAll();
对于(配方r:RRRecipes){
最终决定添加(r);
//Toast.makeText(this,r.getName(),Toast.LENGTH_SHORT).show();
}
myAdapter=新的ListViewAdapter(此为最终选项);
myList.setAdapter(myAdapter);
}
@凌驾
受保护的空onDestroy(){
realm.close();
super.ondestory();
}
}
第二屏幕活动(问题活动)
公共类SecondScreenDetails扩展了AppCompative活动{
公共领域;
@BindView(R.id.Components_列表)回收视图ingre_列表;
@BindView(R.id.steps_按钮)按钮下一个按钮;
公共职位;
公共静态SecondScreenRecycleServiceAdapter myAdapter;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u second\u screen\u details);
Realm.init(this);
realm=realm.getDefaultInstance();
setDisplay();
把(这个)绑起来;
next_button.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
}
});
}
私有void setDisplay(){
ArrayList finalRecipies=新的ArrayList();
ArrayList FinalingElements=新的ArrayList();
RealmResults rrRecipies=realm.where(Recipe.class).findAll();
Intent in=getIntent();
position=Integer.parseInt(在.getStringExtra(“position”)中);
对于(配方r:RRRecipes){
最终决定添加(r);
}
int i=finalRecipies.get(position.getComponents().size();
对于(int j=0;j您可以在AsyncTask中提取数据请求的所有逻辑,并在中决定是否返回领域数据或服务数据。您可以在AsyncTask中提取数据请求的所有逻辑,并在中决定是否返回领域数据或服务数据。对不起,我听不懂您的意思,我听不懂您的意思这是什么版本的Realm?它是最新版本(3.4.0),在AsyncTask中有private RealmList realmRecipe=new RealmList();
作为一个字段,看起来是从错误线程意外访问数据的简单方法。我首先要删除它。这是什么版本的Realm?它是最新版本(3.4.0)将private RealmList realmRecipe=new RealmList();
作为异步任务中的一个字段,看起来是一种从错误线程意外访问数据的简单方法。我首先要删除它。
public class SecondScreenDetails extends AppCompatActivity {
public Realm realm;
@BindView(R.id.ingredients_list)RecyclerView ingre_list;
@BindView(R.id.steps_button)Button next_button;
public int position;
public static SecondScreenRecyclerViewAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_screen_details);
Realm.init(this);
realm = Realm.getDefaultInstance();
setDisplay();
ButterKnife.bind(this);
next_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
private void setDisplay() {
ArrayList<Recipe> finalRecipies = new ArrayList<>();
ArrayList<Ingredients> finalIngredients = new ArrayList<>();
RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
Intent in = getIntent();
position = Integer.parseInt(in.getStringExtra("Position"));
for(Recipe r: rrRecipies){
finalRecipies.add(r);
}
int i = finalRecipies.get(position).getIngredients().size();
for( int j = 0 ; j<i ; j++){
Ingredients n = new Ingredients(finalRecipies.get(position).getIngredients().get(j).getQuantity(),
finalRecipies.get(position).getIngredients().get(j).getMeasure(),
finalRecipies.get(position).getIngredients().get(j).getIngredient());
finalIngredients.add(n);
}
myAdapter = new SecondScreenRecyclerViewAdapter(finalIngredients);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
ingre_list.setLayoutManager(mLayoutManager);
ingre_list.setItemAnimator(new DefaultItemAnimator());
ingre_list.setAdapter(myAdapter);
}
}
public class DownloadTask extends AsyncTask<String,Void,String> {
private RealmList<Recipe> realmRecipe = new RealmList<>();
String result;
@Override
protected String doInBackground(String... params) {
result = "";
Realm realm = null;
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json").build();
try {
result = client.newCall(request).execute().body().string();
Log.i("RESULT", result);
JSONArray rootArray = new JSONArray(result);
for (int i = 0; i < rootArray.length(); i++) {
JSONObject tempObject = rootArray.getJSONObject(i);
JSONArray jIngredients = tempObject.getJSONArray("ingredients");
JSONArray jSteps = tempObject.getJSONArray("steps");
// Get the ingredients
List<Ingredients> ingredients = new ArrayList<>();
for (int j = 0; j < jIngredients.length(); j++) {
JSONObject tempIngredient = jIngredients.getJSONObject(j);
Ingredients nIngredient = realm.createObject(Ingredients.class);
nIngredient.setIngredient(tempIngredient.getString("ingredient"));
nIngredient.setMeasure(tempIngredient.getString("measure"));
nIngredient.setQuantity(tempIngredient.getString("quantity"));
// Ingredients newIngredient = new Ingredients(tempIngredient.getString("quantity"),
// tempIngredient.getString("measure"),
// tempIngredient.getString("ingredient"));
// ingredients.add(newIngredient);
ingredients.add(nIngredient);
}
// Get the steps
List<Steps> steps = new ArrayList<>();
for (int j = 0; j < jSteps.length(); j++) {
JSONObject tempStep = jSteps.getJSONObject(j);
Steps nStep = realm.createObject(Steps.class);
nStep.setDescription(tempStep.getString("description"));
nStep.setId(tempStep.getString("id"));
nStep.setShortDescription(tempStep.getString("shortDescription"));
nStep.setVideoURL(tempStep.getString("videoURL"));
steps.add(nStep);
// Steps newStep = new Steps(tempStep.getString("id"), tempStep.getString("shortDescription"),
// tempStep.getString("description"), tempStep.getString("videoURL"));
// steps.add(newStep);
}
// Create the recipe
Recipe nRecipe = realm.createObject(Recipe.class);
nRecipe.setId(tempObject.getString("id"));
nRecipe.setName(tempObject.getString("name"));
nRecipe.setServings(tempObject.getString("servings"));
nRecipe.setIngredients(ingredients);
nRecipe.setSteps(steps);
realmRecipe.add(nRecipe);
// Recipe newRecipe = new Recipe(tempObject.getString("id"), tempObject.getString("name"), tempObject.getString("servings"), ingredients, steps);
// MainActivity.mRecipies.add(newRecipe);
}
}catch (Exception e){
Log.i("Error Message", e.getMessage());
}
}
});
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}