【问题标题】:Why is my database list not showing at first and only showing after a click?为什么我的数据库列表一开始没有显示,只有点击后才显示?
【发布时间】:2020-08-12 17:40:49
【问题描述】:

我使用 Room Architecture 作为一个简单的数据库来显示城市名称列表。 数据库正在工作,但我唯一的问题是数据库列表仅在我点击编辑文本字段后显示。我附上了各自的代码和一些截图以便更好地理解。 我确信这是我所做的一些小的逻辑错误。任何人都可以帮忙吗? 提前致谢。

位置活动

package com.example.smweather;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

import java.util.List;

public class LocationsActivity extends AppCompatActivity {

    private LocationViewModel locationViewModel;

    AutoCompleteTextView trialedCity;
    String[] trialCityNames;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_locations);

        setTitle("Locations");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        trialedCity = findViewById(R.id.aedCity);
        trialCityNames = getResources().getStringArray(R.array.sample_city_names);
        ArrayAdapter<String> sampleCityListAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, trialCityNames);
        trialedCity.setAdapter(sampleCityListAdapter);

        trialedCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                trialedCity.setCursorVisible(true);
            }
        });

        RecyclerView locationRecyclerView = findViewById(R.id.location_recycler_view);
        locationRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        locationRecyclerView.setHasFixedSize(true);

        final LocationAdapter adapter = new LocationAdapter();
        locationRecyclerView.setAdapter(adapter);

        locationViewModel = new ViewModelProvider(this, 
        ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()))
                .get(LocationViewModel.class);
        locationViewModel.getAllLocations().observe(this, new Observer<List<Location>>() {
            @Override
            public void onChanged(List<Location> locations) {
                adapter.submitList(locations);
            }
        });

        adapter.setOnLocationClickListener(new LocationAdapter.OnLocationClickListener(){
            @Override
            public void onLocationClick(Location location) {

                String trialvalue = location.getStrlocation();
                Intent resultIntent = new Intent();
                resultIntent.putExtra("trialValue",trialvalue);
                setResult(RESULT_OK,resultIntent);
                finish();
            }
        });

        // TODO: 12-08-2020 swipe gesture to delete
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull                         
                 RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                locationViewModel.delete(adapter.getLocationAt(viewHolder.getAdapterPosition()));
                Toast.makeText(LocationsActivity.this, "Location deleted", 
                   Toast.LENGTH_SHORT).show();
            }
        }).attachToRecyclerView(locationRecyclerView);

    }

    public void trialdata(View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(myApi.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        myApi trialapi = retrofit.create(myApi.class);

        Call<Example> exampleCall = 
        trialapi.getinfo(trialedCity.getText().toString().trim(),MainActivity.openWeatherapiKey);
        exampleCall.enqueue(new Callback<Example>() {
            @Override
            public void onResponse(Call<Example> call, Response<Example> response) {
                if (response.code() == 404) {
                    Toast.makeText(LocationsActivity.this, "Invalid City", 
                  Toast.LENGTH_SHORT).show();
                } else if (response.code() == 429) {
                    Toast.makeText(LocationsActivity.this, "Your account is temporary blocked due to 
                  exceeding of requests limitation of your subscription type.", 
              Toast.LENGTH_SHORT).show();
                } else if (!response.isSuccessful()) {
                    Toast.makeText(LocationsActivity.this, "Error code: " + response.code(), 
               Toast.LENGTH_SHORT).show();
                } else {
                    String trialvalue = trialedCity.getText().toString().trim();
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra("trialValue",trialvalue);

                    Location location = new Location(trialvalue);
                    locationViewModel.insert(location);
                    setResult(RESULT_OK,resultIntent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Example> call, Throwable t) {
                Toast.makeText(LocationsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}

ViewModel 类

package com.example.smweather;

import android.app.Application;

import java.util.List; 

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

public class LocationViewModel extends AndroidViewModel {
private LocationRepository repository;
private LiveData<List<Location>> allLocations;

public LocationViewModel(@NonNull Application application) {
    super(application);
    repository = new LocationRepository(application);
    allLocations = repository.getAllLocations();
}

public void insert(Location location) {
    repository.insert(location);
}

public void update(Location location) {
    repository.update(location);
}

public void delete(Location location) {
    repository.delete(location);
}

public void deleteAllLocations() {
    repository.deleteAllLocations();
}

public LiveData<List<Location>> getAllLocations() {
    return allLocations;
}
}

In the first image The list of database should show below the search button

The list only shows when the editText field is clicked

请看上面的图片更好的理解。

【问题讨论】:

  • 在你的视图模型中,发送一个命令来获取初始数据;它可以在活动的 onResume 方法中,也可以在视图模型的 init 块中;看起来您正在过滤数据集,而过滤器方法正在获取初始数据;
  • 我已经粘贴了我的视图模型类。

标签: android database retrofit2 android-room android-livedata


【解决方案1】:

我不完全确定,但也许你应该在 Observer 中调用 adapter.notifyDataSetChanged()

【讨论】:

  • OMG 是的,它奏效了。非常感谢。我已经坚持了两天了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
  • 2021-04-05
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多