Doing this works fine:
class DBHelper : SQLiteOpenHelper(GLOBAL_CONTEXT, DATABASE_NAME,null, DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "database.db"
private const val DATABASE_VERSION = 1
}
}
But this doesn't work:
object DBHelper : SQLiteOpenHelper(GLOBAL_CONTEXT, DATABASE_NAME,null, DATABASE_VERSION) {
private const val DATABASE_NAME = "database.db"
private const val DATABASE_VERSION = 1
}
Why is this the case and how to work around it (other than converting the object to class)?
Move the constants outside the object. They can't be used in its constructor because they are not initialized until the object is.
private const val DATABASE_NAME = "database.db"
private const val DATABASE_VERSION = 1
object DBHelper : SQLiteOpenHelper(GLOBAL_CONTEXT, DATABASE_NAME,null, DATABASE_VERSION) {
}
Related
I'm a little confused to convert my SQL to criteria query which needs me to get last actual status.
select r.id, s.CODE, rs.CREATE_DATE
from request r
join request_status rs on r.id = rs.request_id
join status s on rs.STATUS_ID = s.ID
join (SELECT rss.REQUEST_ID, max(rss.CREATE_DATE) lastDate
FROM REQUEST_STATUS rss GROUP BY rss.REQUEST_ID) lastStatus ON r.ID = lastStatus.REQUEST_ID AND rs.CREATE_DATE = lastStatus.lastDate;
#Entity
public class Request {
#Id
private UUID id;
#OneToMany(mappedBy = "request", fetch = LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<RequestStatus> requestStatuses = new ArrayList<>();
}
#Entity
public class RequestStatus {
#Id
private UUID id;
#ManyToOne(fetch = LAZY, optional = false)
private Request request;
#ManyToOne(fetch = LAZY, optional = false)
private Status status;
private OffsetDateTime createDate;
}
#Data
#AllArgsConstructor
public class LastRow {
private UUID id;
private OffsetDateTime date;
}
So, I do like:
public void run() {
var builder = entityManager.getCriteriaBuilder();
var query = builder.createQuery(RequestAsCreatedEvent.class);
var root = query.from(Request.class);
query.select(builder.construct(RequestAsCreatedEvent.class,
root.get(Request_.id),
root.get(Request_.template).get(Template_.id)));
var subQuery = query.subquery(LastRow.class);
subQuery.correlate(root);
var subRoot = subQuery.from(RequestStatus.class);
subQuery.groupBy(subRoot.get(RequestStatus_.id));
subQuery.select(builder.construct(LastRow.class, subRoot.get(RequestStatus_.request).get(Request_.id),
builder.greatest(subRoot.get(RequestStatus_.createDate))));
entityManager.createQuery(query).getResultList();
}
And I can't do that because subQuery.select expect Expression, but I need to select multiple values, and I try to do it like root query via object constructor (but it return CompoundSelection)
I am working with android studio and in Kotlin. I am working with a Singleton class so my confusion is that my getInstance function is not being called when I am trying to add that into my setupRecyclerView function and it keeps saying it is an unresolved reference. I also have the issue that my NewsListActivity.SimpleItemRecyclerViewAdapter also keeps getting an unresolved reference when I try to reference it. Any help would be greatly appreciated.
package edu.uw.amjadz.material_news
import android.content.Context
import android.graphics.Bitmap
import android.util.LruCache
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley
class Singleton private constructor(context: Context){
private var INSTANCE: edu.uw.amjadz.material_news.Singleton? = null
fun getInstance(context: Context): edu.uw.amjadz.material_news.Singleton {
if(INSTANCE == null){
INSTANCE = Singleton(context)
}
return INSTANCE as edu.uw.amjadz.material_news.Singleton
}
val requestQueue: RequestQueue by lazy {
Volley.newRequestQueue(context.applicationContext)
}
val imageLoader: ImageLoader by lazy {
ImageLoader(requestQueue,
object : ImageLoader.ImageCache{
private val cache = LruCache<String, Bitmap>(20)
override fun getBitmap(url: String?): Bitmap {
return cache.get(url)
}
override fun putBitmap(url: String?, bitmap: Bitmap?) {
cache.put(url, bitmap)
}
}
)
}
fun <T> add(req: Request<T>){
requestQueue.add(req)
}
}
private fun setupRecyclerView(recyclerView: RecyclerView) {
recyclerView.setAdapter(null)
val key = getString(R.string.NEWS_API_KEY)
val url = "https://newsapi.org/v2/everything?q=bitcoin&from=2018-10-01&sortBy=publishedAt&apiKey=$key"
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET, url, null,
Response.Listener { response ->
recyclerView.adapter = NewsListActivity.SimpleItemRecyclerViewAdapter(this, DummyContent.parseData(response.toString()), twoPane)
},
Response.ErrorListener { error ->
}
)
Singleton.getInstance(this).add(jsonObjectRequest)
if (twoPane){
recyclerView.layoutManager = LinearLayoutManager(this)
} else {
recyclerView.layoutManager = GridLayoutManager(this, 2)
}
}
}
class SimpleItemRecyclerViewAdapter(
private val parentActivity: NewsListActivity,
private val values: List<DummyContent.DummyItem>,
private val twoPane: Boolean
) :
RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder>() {
private val onClickListener: View.OnClickListener
init {
onClickListener = View.OnClickListener { v ->
val item = v.tag as DummyContent.DummyItem
if (twoPane) {
val fragment = NewsDetailFragment().apply {
arguments = Bundle().apply {
putString(NewsDetailFragment.ARG_ITEM_ID, item.id)
}
}
parentActivity.supportFragmentManager
.beginTransaction()
.replace(R.id.news_detail_container, fragment)
.commit()
} else {
val intent = Intent(v.context, NewsDetailActivity::class.java).apply {
putExtra(NewsDetailFragment.ARG_ITEM_ID, item.id)
}
v.context.startActivity(intent)
}
}
}
Let's get straight.
I have interface and class like this:
public interface IDataBase
{
DataTable GetSomeTableData();
}
My class:
public class DataBase : IDataBase
{
private readonly string _connectionString;
public DataBase(string connectionString)
{
this._connectionString = connectionString;
}
public DataTable GetSomeTableData()
{
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
// some select
}
}
}
I'm using Autofac to inject that class:
var builder = new ContainerBuilder();
builder.RegisterType<DataBase>().As<IDataBase>).WithParameter("connectionString", "my connection string");
var container = builder.Build();
var database = container.Resolve<IDataBase>();
var tableData1 = database.GetSomeTableData();
// change connection string ?????????????????
var tableData2 = database.GetSomeTableData();
I need to get table data from one DB and another DB. How can I change connection string after have registered class? You may give another exapmle..
There are many ways to do it. One would be to create and inject a service instead of just plain connection string.
public interface IConnectionStringProvider
{
public string ConnectionString { get; set }
}
public class ConnectionStringProvider
{
public string ConnectionString { get; set }
}
var builder = new ContainerBuilder();
builder.RegisterType<DataBase>()
.As<IDataBase>);
builder.RegisterType<ConnectionStringProvider>)
.As<IConnectionStringProvider>
.SingleInstance();
var container = builder.Build();
var database = container.Resolve<IDataBase>();
var connStringProvider = container.Resolve<IConnectionStringProvider>();
var tableData1 = database.GetSomeTableData();
connStringProvider.ConnectionString = "...";
var tableData2 = database.GetSomeTableData();
The DataBase would then use that service:
public class DataBase : IDataBase
{
private readonly IConnectionStringProvider _connectionStringProvider;
public DataBase(IConnectionStringProvider connectionStringProvider)
{
this._connectionStringProvider = connectionStringProvider;
}
public DataTable GetSomeTableData()
{
using (SqlConnection cn = new SqlConnection(_connectionStringProvider.ConnectionString))
{
cn.Open();
// some select
}
}
}
I have a following code
public void ShowForm(String EName, String phoneNumber, String dnis, String mode, String callid)
{
objCallParams.EventName = EName;
objCallParams.ANI = phoneNumber;
objCallParams.DNIS = dnis;
objCallParams.Mode = mode;
objCallParams.CallId = callid;
UIThreadContext.Post(InComing_Callback, (object)objCallParams);
}
private void InComing_Callback(object objCallParams)
{
/*want to access phone number i.e.objCallParams.ANI*/
}
How do I access phoneNumber in InComing_Callback(object objCallParams) method?
If you know the type of the object you can use casting
private void InComing_Callback(object objCallParams)
{
// If you know that objCallParams will always be of the type FormParameters:
var params = (FormParameters)objCallParams;
// if you are not so sure about that
var notSoSureParams = objCallParams as FormParameters;
if (notSoSureParams != null)
{
}
}
Hi I have to different classes with Same properties and I want to access the peoperties of my classes Dynamically.
public Class1
{
public const prop1="Some";
}
public Class2
{
public const prop1="Some";
}
And in my code I am getting my class name like this
string classname="Session["myclass"].ToString();";//Say I have Class1 now.
And I want to get the prop1 value .
Something like
string mypropvalue=classname+".prop1";//my expected result is Some
///
Type typ=Type.GetType(classname);
Please help me in getting this
Reflection
var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
for static:
var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);
Class reference from string
EDIT (I made example):
class Program
{
static void Main(string[] args)
{
var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
//This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
var prop1
= ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);
Console.WriteLine(prop1.GetValue(ty.Name, null));
Console.ReadLine();
}
}
public static class Foo
{
private static string a = "hello world";
public static string Temp
{
get
{
return a;
}
}
}
Msdn
you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}