如何通过Id Room数据库获取数据

时间:2019-12-09 21:41:21

标签: android android-room

我正在努力,但无法获得任何结果,我只想使我的String脱机通过ID从数据库中获取数据 我通过getId获取ID号并将其发送到mainActivty,但是我不能从中受益,请检查我的代码

Dao
public interface FavNewsDao {



@Query("SELECT * FROM news_table")
LiveData<List<FavNews>> getAllNotes();

@Query("SELECT * FROM news_table WHERE id=:id")
int loadSingle(int id);
}

我正在recyclerView适配器中设置数据 这是我的MainActivity

public class Main2Activity extends AppCompatActivity {

private WebView web_View;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Intent getUrl = getIntent();

    String url2 = getUrl.getStringExtra("url");
    web_View = findViewById(R.id.webView);

    web_View.setWebViewClient(new WebViewClient());

    if (CheckInternet.isNetwork(getApplicationContext())) {
        if(url2!=null) {
            Log.e("url2", url2);
            web_View.loadUrl(url2);
        }
    } else {

        int data = getUrl.getIntExtra("data",0);


       int a = FavNewsDatabase.getInstance(getApplicationContext()).noteDao().loadSingle(1);
            Log.e("data2",a+"");
           String dds = Integer.toString(a);
       String encodedHtml = Base64.encodeToString(dds.getBytes(), Base64.NO_PADDING);

    web_View.loadData(encodedHtml, "text/html", "base64");

    }



}
}

我在适配器`intent.putExtra(“ data”,favNews.get(position).getId())中做什么? 这是我的问题

       int a = FavNewsDatabase.getInstance(getApplicationContext()).noteDao().loadSingle(1);

那么如何通过ID获取离线数据

@Entity(tableName = "news_table")
 public class FavNews {

@PrimaryKey(autoGenerate = true)
private int id;

private String title;

private String description;

private String url;

private String offlineData;

当然我在这里有二传手和吸气剂

1 个答案:

答案 0 :(得分:0)

按如下所示更改您的query,以便仅通过ID获得offlineData

@Query("SELECT offlineData FROM news_table WHERE id =:id")
String loadSingle(int id);

然后按如下所示获取它:

String a = FavNewsDatabase.getInstance(
           getApplicationContext()).noteDao().loadSingle(1);

注意::当您从data项通过1获得data时,应该使用intent而不是硬编码的RecyclerView点击。