gpt4 book ai didi

java - Realm 对象只能在创建它们的线程上访问

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:03 24 4
gpt4 key购买 nike

我正在从 URL 下载 JSON 数据,因为我计划将其用于许多 Activity ,所以我使用 Realm 离线存储它,现在当我尝试从 mainactivity 访问存储的数据时,它工作正常,但数据是这样的,它是一个由另外两个数组列表(嵌套数组列表)组成的数组列表。因此,每当我想访问第二个屏幕中主对象的数组列表之一时,我都会将对象的位置从主屏幕发送到第二个屏幕。我正在尝试从那里获取数据。但它显示了该错误。

如有任何帮助,我们将不胜感激。提前致谢。

堆栈跟踪

    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.

主要 Activity

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

SecondScreenActivity(问题 Activity )

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

最佳答案

您可以在AsyncTask中抽象出数据请求的所有逻辑,并在其中决定是返回 Realm 数据还是服务数据。

关于java - Realm 对象只能在创建它们的线程上访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44905833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com