logo
down
shadow

Access SQLite Helper From Adapter


Access SQLite Helper From Adapter

Content Index :

Access SQLite Helper From Adapter
Tag : java , By : kbrust
Date : November 28 2020, 04:01 AM

To fix the issue you can do The following will likely cause some of your issues. That is you are saying that the method should be passed a MesagesAdapter, when as it stands there is no reason to pass anything into the getAllQuestions3 method.
public Cursor getAllQuestions3(MessagesAdapter usageSettings2) {
    return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
public Cursor getAllQuestions3() {
    return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
ChatData mHelper = new ChatData(this);
Cursor csr = mHelper.getAllQuestions3();
final ChatData mHelper = new ChatData(this,ChatData.DATABASE_NAME,null,ChatData.DATABASE_VERSION);
final Cursor csr = mHelper.getAllQuestions3(this);
public ChatData(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
} 
public class ChatData extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "MessagePlus";
    public static final String TABLE_CHAT_DATA = "chatdata";
    public static final String COL_CHATDATA_ID = BaseColumns._ID;
    public static final String COL_CHATDATA_TIMESTAMP = "timestamp";
    public static final String COL_CHATDATA_MESSAGE = "message";
    public static final String COL_CHATDATA_USER = "user";

    public ChatData(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        String crt_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_CHAT_DATA + "(" +
                COL_CHATDATA_ID + " INTEGER PRIMARY KEY, " +
                COL_CHATDATA_TIMESTAMP + " TEXT DEFAULT CURRENT_TIMESTAMP," +
                COL_CHATDATA_MESSAGE + " TEXT, " +
                COL_CHATDATA_USER + " INTEGER" +
                ")";
        db.execSQL(crt_sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public Cursor getAllQuestions3() {
        return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
    }

    public long addMessage(String message, long user) {
        ContentValues cv = new ContentValues();
        cv.put(COL_CHATDATA_MESSAGE,message);
        cv.put(COL_CHATDATA_USER,user);
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert(TABLE_CHAT_DATA,null,cv);
    }
}
public class MessageAdapter extends CursorAdapter {
    public MessageAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        return super.getView(position, convertView, parent);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View rv = LayoutInflater.from(context).inflate(
                R.layout.messagelist_item,
                parent,
                false
        );
        return rv;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        TextView mUser = view.findViewById(R.id.user);
        TextView mTimestamp = view.findViewById(R.id.timestamp);
        TextView mMessage = view.findViewById(R.id.message);

        mUser.setText(cursor.getString(cursor.getColumnIndex(ChatData.COL_CHATDATA_USER)));
        mTimestamp.setText(cursor.getString(cursor.getColumnIndex(ChatData.COL_CHATDATA_TIMESTAMP)));
        mMessage.setText(cursor.getString(cursor.getColumnIndex(ChatData.COL_CHATDATA_MESSAGE)));
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/user"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/timestamp"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/message"
        android:layout_width="0dp"
        android:layout_weight="8"
        android:layout_height="wrap_content" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {

    ChatData mDBHlpr;
    Cursor mCsr;
    MessageAdapter mMesaageAdapter;
    ListView mMessageList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMessageList = this.findViewById(R.id.messagelist);
        mDBHlpr = new ChatData(this);
        addSomeData();
        mCsr = mDBHlpr.getAllQuestions3();
        mMesaageAdapter = new MessageAdapter(this,mCsr,false);
        mMessageList.setAdapter(mMesaageAdapter);

    }

    private void addSomeData() {
        mDBHlpr.addMessage("Hello",1);
        mDBHlpr.addMessage("Hi",2);
        mDBHlpr.addMessage("How are you?",1);
        mDBHlpr.addMessage("I'm OK thanks, and you?",2);
        mDBHlpr.addMessage("Good.",1);
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

MVC3: Calling a strongly typed helper from custom helper by a dynamic field access


Tag : asp.net-mvc-3 , By : Xander
Date : March 29 2020, 07:55 AM
I wish this helpful for you I have strongly typed custom helper (it does nothing - just sample): , Ok i just simply returned
    MvcHtmlString.Create(oValue.ToString()).toHtmlString();

SQLite/ADO.NET- Data Adapter doesn't write correct number of rows to SQLite file


Tag : chash , By : Jouni
Date : March 29 2020, 07:55 AM
Does that help As it is the code posted here is correct, the problem with fewer rows is from exiting the application before the inserts are done.
The issue with the integers showing up as decimals was due to the tool being used to view the SQLite file, not the actual database itself.

SQLite database not created by SQLite Open Helper


Tag : android , By : user119985
Date : March 29 2020, 07:55 AM
To fix this issue I have created this class in my android application. But when I'm going to retrieve data from created database, it's showing the database not available. Please help me to do this. , For db operations, I use a helper class like this:
public class DBAdapter {
private static final String DATABASE_NAME = "DBNAME";
private static final int DATABASE_VERSION = 1;

private static DBAdapter sInstance;

private final Context mContext; 

public DatabaseHelper DBHelper;
public SQLiteDatabase mDb;

private DBAdapter(Context ctx)     {
    this.mContext = ctx.getApplicationContext();
    DBHelper = new DatabaseHelper(mContext);
} 

public static DBAdapter getInstance(Context context) {
    if (sInstance == null) {
      sInstance = new DBAdapter(context.getApplicationContext());
    }
    return sInstance;
  }

public static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        ...
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {          
        ...
    }



 }    

//---opens the database---
public DBAdapter open() throws SQLException {
    mDb = DBHelper.getWritableDatabase();
    return this;
}
//add any db functions you want here


 public Cursor getCursor(int var) {
    ...do stuff here with the mDb database
}
DBAdapter mDb = DBAdapter.getInstance(getApplicationContext());  
mDb.open();
    Cursor cur= mDb.getCursor(2);
public void close() {
    DBHelper.close();
}

How to access Sqlite Adapter class to MainActivity using Arraylist?


Tag : java , By : Yohan Lee
Date : March 29 2020, 07:55 AM
wish helps you I am creating a sample gallery app, I am trying to store Gallery Items in local sqlite database
MuAdapter= new muadapter(Activityname.this);
//  this line is broke. Use something like "MuAdapter muAdapter = new ..." 

mudapter.open();
// then this line can work

ArrayList<String> list =getImagePath();
// not sure about this, but don't you need an objectrefernece here, that you call getImagePath() on?!

How to access a controller helper method from a helper test in Rails 4?


Tag : ruby-on-rails , By : user116330
Date : March 29 2020, 07:55 AM
To fix the issue you can do AFAIK (As far as I know), you cannot fix this without stubbing, or doing some change in your code, as essentially a helper file is just a module of itself that should be treated independent of where it's gonna be included. Who knows you might want to include such helper file inside your model files for example, in which incidentally the model file also has a method named can_access_participant_contact_data? but does differently from that one defined in the ApplicationController, therefore you cannot unit test this without specifying the context / base.
Possible Workarounds:
test "should return an asterisked string with spaces" do
  ParticipantsHelper.class_eval do
    define_method :can_access_participant_contact_data? do |arg|
      true
    end
  end

  redacted_contact_data(Participant.first, :name)
end
# helpers/application_helper.rb
module ApplicationHelper
  def can_access_participant_contact_data?(participant)
    # YOUR CODE
  end
end

# helpers/participants_helper.rb
module ParticipantHelper
  include ApplicationHelper

  def redacted_contact_data participant, attribute_name
    attribute = participant.try(:contact_data).try(attribute_name)
    return attribute if can_access_participant_contact_data?(participant)
    return nil       if attribute.blank?
    return attribute.gsub(/\S/i, '*') # Asterisked string
  end
end
class ParticipantsController
  def show
    helpers.can_access_participant_contact_data?(@participant)
  end
end
class ApplicationController < ActionController::Base
  include ApplicationHelper
end

class ParticipantsController < ApplicationController
  def show
    can_access_participant_contact_data?(@participant)
  end
end
Related Posts Related QUESTIONS :
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • Ignite persisting a Set: Cannot find metadata for object with compact footer
  • Maven cannot resolve Jacob dependency using eclipse
  • testcontainers oracle database container starts before database user is created
  • Launching two spring boot apps in integration test
  • Is there a way to add a HashMap's value that is a integer array into a ArrayList?
  • Is there any way that I can get a parameter in paintComponent?
  • Empty stack with one recursive method and one iterative method
  • What's the behavior of onBackpressureBuffer in RxJava2
  • Java regex can only use 1 quantifier in a lookback (need 2)
  • How to fix error in native query : it is showing syntax error near or at
  • How to retrieve nested object from a document and display it in FirestoreRecyclerOptions?
  • Why not use ListIterator for full LinkedList Operation?
  • Android Webview EvaluateJavascript sometimes does not return a response
  • Matcher java doesn't work but regex seems to be good
  • Finding dimensions of a .gif file
  • Java Number format how to change +/- sign to custom text
  • Entity partially saved when using JOINED inheritance strategy and setting spring.jpa.properties.hibernate.jdbc.batch_siz
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com