How to fix "cannot be aplied to" error in activity class? - java

I'm making a database on SQLite, but have a error with adding it in Main Activity. I'm sure I made all right in building database.
Tried to change on activity name - nothing changed. Tried change on getActivity() - got a new error.
Code from Main activity (part with error):
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
dbHelper = new DBHelper(this);
}
...
Database code (called DBHelper in my project):
package com.gov.work;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "contactDb";
public static final String TABLE_CONTACTS = "contacts";
public static final String KEY_ID = "_id";
public static final String KEY_MAIL = "mail";
public static final String KEY_PASSWORD = "password";
public DBHelper(Context context, String name, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_CONTACTS + "(" + KEY_ID + " integer primary key,"+ KEY_MAIL + " text," + KEY_PASSWORD + " text" + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_CONTACTS);
onCreate(db);
}
}
When I try to run project it gives me compilation error.

It's because you're trying to instantiate your DBHelper with:
dbHelper = new DBHelper(this);
but you didn't have a matching constructor in your DBHelper. You only have the following constructor:
public DBHelper(Context context, String name, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
So, you need to add a constructor to DBHelper with Context as its only parameter to solve your problem, like this:
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

You can use getActivity() instead this
dbHelper = new DBHelper(this);
to
dbHelper = new DBHelper(getActivity());

Related

Access SQLite Helper From Adapter

Code
public class ChatData extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "MessagePlus";
public ChatData(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getAllQuestions3(MessagesAdapter usageSettings2) {
return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
}
Adapter
final ChatData mHelper = new ChatData(this);
final Cursor csr = mHelper.getAllQuestions3(this);
Nothing is working for context in adapter. This shows message to change the Helper classes context to the Adapters name and if i do that theres a red line under context in the helper... If i directly try to access like ChatData.getWritableDatabase it shows that u cant access a non static method from a static class and if i make that method in helper static it shows error there saying class cant be static... one error is leading to another and i dont know what to do so can someone help me out please
EDIT
Full Adapter Code
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MessageViewHolder>{
private List<SQLiteHelper> mMessagesHelperList;
private FirebaseAuth mAuth;
ChatData mHelper = new ChatData(this);
Cursor csr = mHelper.getAllQuestions3();
public MessagesAdapter(List<SQLiteHelper> mMessagesHelperList) {
this.mMessagesHelperList = mMessagesHelperList;
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView messageText;
public MessageViewHolder(View view) {
super(view);
messageText = (TextView)view.findViewById(R.id.message_text_layout);
}
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_chat,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(V);
}
#Override
public void onBindViewHolder(final MessageViewHolder holder, int position) {
String mSender = null;
String mMessage = null;
String mTime;
String mSeen = null;
String mTimer;
String mType;
while (csr.moveToNext()) {
mSender = csr.getString(csr.getColumnIndex(KEY_SENDER));
mMessage = csr.getString(csr.getColumnIndex(KEY_MESSAGE));
mTime = csr.getString(csr.getColumnIndex(KEY_TIME));
mSeen = csr.getString(csr.getColumnIndex(KEY_SEEN));
mTimer = csr.getString(csr.getColumnIndex(KEY_TIMER));
mType = csr.getString(csr.getColumnIndex(KEY_TYPE));
}
SQLiteHelper messagesHelper = mMessagesHelperList.get(position);
#Override
public int getItemCount() {
return mMessagesHelperList.size();
}
}
Activity
final MainData mHelper = new MainData(this); //Change the name to your Helper Class name
final Cursor csr = myDBHlpr.getAllQuestions3(this);
messageList.setAdapter(mAdapter);
while (csr.moveToNext()) {
String mSender = csr.getString(csr.getColumnIndex(KEY_SENDER));
String mMessage = csr.getString(csr.getColumnIndex(KEY_MESSAGE));
String mTime = csr.getString(csr.getColumnIndex(KEY_TIME));
String mSeen = csr.getString(csr.getColumnIndex(KEY_SEEN));
String mTimer = csr.getString(csr.getColumnIndex(KEY_TIMER));
String mType = csr.getString(csr.getColumnIndex(KEY_TYPE));
messages.add(new SQLiteHelper(mSender, mMessage, mTime, mSeen, mTimer, mType));
}
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);
}
Trying changing the above to
public Cursor getAllQuestions3() {
return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
and use
ChatData mHelper = new ChatData(this);
Cursor csr = mHelper.getAllQuestions3();
instead of
final ChatData mHelper = new ChatData(this,ChatData.DATABASE_NAME,null,ChatData.DATABASE_VERSION);
final Cursor csr = mHelper.getAllQuestions3(this);
Noting that the above lines should be in the Activity's onCreate method or a method invoked from onCreate so that you have a valid context (i.e. this).
Edit 1
Note that the above has been changed as according to ChatData you need to provided 4 parameters for the instantiation of a ChatData object.
I'd suggest changing the constructor to :-
public ChatData(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and then you could use ChatData mHelper = new ChatData(this);.
Working Example
The following is a working example based upon the code you have given.
The database helper ChatData.java
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);
}
}
Note modified to crate a table and to allow rows to be added to the table.
Note the constructor.
The Custom Adapter (Cursor Adapter) MessageAdapter.java
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)));
}
}
The layout used in the list messagelist_item.xml
<?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>
The code in the Activity to list the messages via the adapter (MainActivty.java)
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);
}
}
Result

Pass value of one application to other package application in background like facebook & facebook messenger app

I have two app APP1(Package name-: com.abc.q) and APP2(Package name -:com.xyz.y) in APP1 there is an activity which will open another APP2 activity which has notification comes from parse.com .I actually want that whenever any APP2 gets the notification it should show "1" in APP1 in small red oval.In gist when APP2 gets notification from parse.com it should show red oval notification in APP1 in the activity which i have decided.
APP1 Acivity
1.)gkk.java
public class gkk extends Activity {
MediaPlayer ourSong;
private static final String TAG = "gkk";
Button button;private ProgressDialog pDialog;
private WebView webView;
private WebView webView1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.lgin);
webView = (WebView) findViewById(R.id.webView1);
webView1 = (WebView) findViewById(R.id.webView11);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new InsideWebViewClient());
webView1.getSettings().setJavaScriptEnabled(true);
webView1.setWebViewClient(new myWebClient());
webView.loadUrl("www.xyz.comm");
webView1.loadUrl("www.xyz.comm");
ourSong=MediaPlayer.create(gkk.this, R.raw.rollver);
FloatingActionButton fabButton = new FloatingActionButton.Builder(this)
.withDrawable(getResources().getDrawable(R.drawable.float_button))
.withButtonColor(Color.WHITE)
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 12, 12)
//.withButtonSize(180)
.create();
fabButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//Intent intent = new Intent(gkk.this,St.class);
Intent intent = new Intent(gkk.this,LoginActivity.class);
startActivity(intent);
overridePendingTransition( R.anim.down, R.anim.toup );
}
});
FloatingActionButton fabButton2 = new FloatingActionButton.Builder(this)
.withDrawable(getResources().getDrawable(R.drawable.n19))
.withButtonColor(Color.TRANSPARENT)
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 12, 85)
.create();
fabButton2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.xyz.y");
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
startActivity(intent);
}
}
});
webView.setBackgroundColor(0x00000000);
webView1.setBackgroundColor(0x00000000);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("fetching Notice's..");
pDialog.show();
addListenerOnButton();
webView.setWebViewClient(new InsideWebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error1.html");
pDialog.dismiss();
}
});
webView1.setWebViewClient(new myWebClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView1.loadUrl("file:///android_asset/notification.html");
pDialog.dismiss();
}
});
}
public class InsideWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".pdf"))
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
public void onPageFinished(WebView view, String url)
{
Log.i(TAG, "Finished loading URL: " +url);
if (pDialog.isShowing()) { pDialog.dismiss(); } } }
class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}}
public void onLunchAnotherApp() {
final String appPackageName = getApplicationContext().getPackageName();
Intent intent = getPackageManager().getLaunchIntentForPackage(appPackageName);
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
onGoToAnotherInAppStore(intent, appPackageName);
}
}
public void onGoToAnotherInAppStore(Intent intent, String appPackageName) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.cc.vv=en" + appPackageName));
startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName));
startActivity(intent);
}
}
public void addListenerOnButton() {
final Context context = this;
Button tut4= (Button) findViewById(R.id.button18);
}
}
APP2 Activity
2.)DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_TITLE = "title";
public static final String KEY_MESSAGE = "message";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID,
KEY_DATE, KEY_TITLE, KEY_MESSAGE };
public static final String DATABASE_NAME = "dbNotif";
public static final String TABLE_NAME = "notif";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ TABLE_NAME + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_DATE
+ " TEXT NOT NULL, " + KEY_TITLE + " TEXT NOT NULL, " + KEY_MESSAGE
+ " TEXT NOT NULL" + ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
// insert data
public long insertNotif(String date, String title, String message) {
long result = 0;
open();
ContentValues cv = new ContentValues();
cv.put(KEY_DATE, date);
cv.put(KEY_TITLE, title);
cv.put(KEY_MESSAGE, message);
result = db.insert(TABLE_NAME, null, cv);
close();
return result;
}
public Cursor getAllNotif() {
open();
Cursor c = db.query(true, TABLE_NAME, ALL_KEYS, null, null, null,
null, KEY_DATE + " DESC", null, null);
if (c != null) {
c.moveToFirst();
}
close();
return c;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
_db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(_db);
}
}
}
3.)lgin.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="0dip" >
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:background="#FFFFFF"
android:layout_above="#+id/button1"
android:layout_below="#+id/button18" >
</WebView>
<Button
android:id="#+id/button18"
android:layout_width="match_parent"
android:layout_height="69dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#333366"
android:gravity="center"
android:paddingBottom="37dip"
android:text="xyz"
android:textColor="#FFFFFF"
android:textSize="19dip"
android:textStyle="bold" />
<WebView
android:id="#+id/webView11"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_alignBottom="#+id/button18"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:background="#333366" />
<ImageView
android:id="#+id/webView11qwd"
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button18"
android:layout_weight="1"
android:background="#drawable/card_depth" />
</RelativeLayout>
4.)Main.java
public class Main extends AppCompatActivity {
private static String TAG = Main.class.getSimpleName();
private Toolbar mToolbar;
private DBAdapter db;
private ListView list;
private ListView listView;
private List<Message> listMessages = new ArrayList<>();
private MessageAdapter adapter;
private PrefManager pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
adapter = new MessageAdapter(this);
pref = new PrefManager(getApplicationContext());
listView.setAdapter(adapter);
Intent intent = getIntent();
String email = pref.getEmail();
if (email != null) {
ParseUtils.subscribeWithEmail(pref.getEmail());
}else{
Log.e(TAG, "Email is null. Not subscribing to parse!");
}
initView();
setNotif();
}
private void initView() {
this.db = new DBAdapter(this);
this.list = (ListView) findViewById(R.id.list_view);
}
private void setNotif() {
Cursor cNotif = db.getAllNotif();
if (cNotif.getCount() > 0) {
String[] data = new String[] { DBAdapter.KEY_ROWID, DBAdapter.KEY_DATE, DBAdapter.KEY_TITLE, DBAdapter.KEY_MESSAGE };
int[] view = new int[] { R.id._id, R.id.date, R.id.title, R.id.message };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, cNotif,
data, view, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
this.list.setAdapter(adapter);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String message = intent.getStringExtra("message");
Message m = new Message(message, System.currentTimeMillis());
listMessages.add(0, m);
adapter.notifyDataSetChanged();
}
private class MessageAdapter extends BaseAdapter {
LayoutInflater inflater;
public MessageAdapter(Activity activity) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listMessages.size();
}
#Override
public Object getItem(int position) {
return listMessages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.list_row, null);
}
TextView txtMessage = (TextView) view.findViewById(R.id.message);
TextView txtTimestamp = (TextView) view.findViewById(R.id.timestamp);
Message message = listMessages.get(position);
txtMessage.setText(message.getMessage());
CharSequence ago = DateUtils.getRelativeTimeSpanString(message.getTimestamp(), System.currentTimeMillis(),
0L, DateUtils.FORMAT_ABBREV_ALL);
txtTimestamp.setText(String.valueOf(ago));
return view;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
pref.logout();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
when there is a new notification in DBAdapter.java it should show notification oval in gkk.java of other package app activity.
Here is your Content of GKK.java file should be. Note that i created new File just to check the flow. You can replace the content from this file inside you file where you wish to receive the notification. Note that from comments i used sendBroadcast instead of LocalBroadcastManager because you are sending notification across different application. So just to check whether all was working fine or now run this command from terminal
adb shell am broadcast -a in.ashish29agre.stackoverflow.retrofit.appnotify.NEW_ROW_INSERTED
package in.ashish29agre.notificationreceverapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_ACTION = "in.ashish29agre.stackoverflow.retrofit.appnotify.NEW_ROW_INSERTED";
private NotificationBroadcastReceiver receiver;
private IntentFilter filter;
private TextView notificationStatusTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new NotificationBroadcastReceiver();
filter = new IntentFilter(NOTIFICATION_ACTION);
notificationStatusTv = (TextView) findViewById(R.id.notification_status_tv);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
private class NotificationBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && intent.getAction().equals(NOTIFICATION_ACTION)) {
if (intent.hasExtra("VALUE")) {
notificationStatusTv.setText("" + intent.getIntExtra("VALUE", -1));
} else {
notificationStatusTv.setText("Notification received successfully with no data");
}
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="in.ashish29agre.notificationreceverapp.MainActivity">
<TextView
android:id="#+id/notification_status_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tye this is in terminal to check notification\nadb shell am broadcast -a in.ashish29agre.stackoverflow.retrofit.appnotify.NEW_ROW_INSERTED" />
</RelativeLayout>
This is you new updated DBAdapter.java
package in.ashish29agre.stackoverflow.retrofit.appnotify;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String NOTIFICATION_ACTION = "in.ashish29agre.stackoverflow.retrofit.appnotify.NEW_ROW_INSERTED";
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_TITLE = "title";
public static final String KEY_MESSAGE = "message";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID,
KEY_DATE, KEY_TITLE, KEY_MESSAGE };
public static final String DATABASE_NAME = "dbNotif";
public static final String TABLE_NAME = "notif";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ TABLE_NAME + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_DATE
+ " TEXT NOT NULL, " + KEY_TITLE + " TEXT NOT NULL, " + KEY_MESSAGE
+ " TEXT NOT NULL" + ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
// insert data
public long insertNotif(String date, String title, String message) {
long result = 0;
open();
ContentValues cv = new ContentValues();
cv.put(KEY_DATE, date);
cv.put(KEY_TITLE, title);
cv.put(KEY_MESSAGE, message);
result = db.insert(TABLE_NAME, null, cv);
close();
Intent notificationIntent = new Intent(NOTIFICATION_ACTION);
notificationIntent.putExtra("VALUE", 1);
context.sendBroadcast(notificationIntent);
Log.d("NOTIFICATION", "Broadcast sent");
return result;
}
public Cursor getAllNotif() {
open();
Cursor c = db.query(true, TABLE_NAME, ALL_KEYS, null, null, null,
null, KEY_DATE + " DESC", null, null);
if (c != null) {
c.moveToFirst();
}
close();
return c;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
_db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(_db);
}
}
}

get the data when an Item is clicked in recyclerview

How to access data after clicking an Item of RecyclerView. What I need is the logic behind on how to get the expanded Items from the database.
Currently for adapter using CursorRecyclerViewAdapter to get data from database https://gist.github.com/skyfishjy/443b7448f59be978bc59
RemindersAdapter.java
public class RemindersAdapter extends CursorRecyclerViewAdapter<RemindersAdapter.ItemViewHolder> {
private final LayoutInflater inflater;
List<ListInfo> data = Collections.emptyList();
private Context context;
ListInfo temporaryBucket;
public RemindersAdapter(Context context, Cursor cursor){
super(context, cursor);
inflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.reminder_item, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
temporaryBucket = new ListInfo();
return holder;
}
#Override
public void onBindViewHolder(ItemViewHolder viewHolder, Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(MyDBHandler.COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_TITLE_REMINDER));
String desc = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DESC_REMINDER));
String date = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DATE_REMINDER));
viewHolder.title.setText(title);
}
class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
public ItemViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.reminderTitle);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
}
}
}
MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "paroah.db";
public static final String TABLE_REMINDER = "reminders";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE_REMINDER = "title";
public static final String COLUMN_DESC_REMINDER = "desc";
public static final String COLUMN_DATE_REMINDER = "date_created";
private Cursor allReminders;
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = " CREATE TABLE "
+TABLE_REMINDER+ "(" +
COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"+
COLUMN_TITLE_REMINDER + " TEXT ,"+
COLUMN_DESC_REMINDER + " TEXT ,"+
COLUMN_DATE_REMINDER + " TEXT "+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("aoi", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
try {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_REMINDER);
onCreate(db);
} catch (SQLException e) {
Log.d("aoi", "getting exception "
+ e.getLocalizedMessage().toString());
}
}
public void addReminder(ListInfo reminder ){
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE_REMINDER, reminder.getTitle());
values.put(COLUMN_DESC_REMINDER, reminder.getDesc());
values.put(COLUMN_DATE_REMINDER, reminder.getDate());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_REMINDER, null, values);
db.close();
}
public Cursor getAllReminders() {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+TABLE_REMINDER;
allReminders = db.rawQuery(query, null);
return allReminders;
}
}
In my onBindViewHolder I'm getting "id, title, desc and date" but only showing the title which when clicked will show the desc and date. For testing just showing a Toast for now on click of item.
You can set the onClickListener in onBindViewHolder() with holder.itemView.setOnClickListener(new OnClickListener({...}), and you can access all data you need.
You can bind view holder with all the data even if you just show the title
#Override
public void onBindViewHolder(ItemViewHolder viewHolder, Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(MyDBHandler.COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_TITLE_REMINDER));
String desc = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DESC_REMINDER));
String date = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DATE_REMINDER));
viewHolder.bind(id, title, desc, date);
}
class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
int idData;
String titleData;
String descData;
String dateData;
TextView title;
public ItemViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.reminderTitle);
itemView.setOnClickListener(this);
}
public void bind(int id, String title, String desc, String date){
this.idData = id;
this.titleData = title;
this.descData = desc;
this.dateData = date;
this.title.setText(title);
}
#Override
public void onClick(View v) {
// You can access all the data here
Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
}
}
}

How to delete a particular row from SQLite database

I have created a list view. On button click the data is added in list and also stored in an SQLite database. I have also added the image on the right-hand side of list, on click of which a particular row data is deleted, but I also want to delete data from SQLite. How could I do this?
Main Activity.Java
public class MainActivity extends Activity {
EditText editText;
Button Button,Button1;
ListView listView;
ArrayList<String> listItems;
BaseAdapter adapter;
private DataBaseHandler mHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper=new DataBaseHandler(this);
editText = (EditText) findViewById(R.id.editText);
Button = (Button) findViewById(R.id.Button);
listView = (ListView) findViewById(R.id.listview);
listItems = new ArrayList<String>();
adapter =new BaseAdapter()
{
#Override
public View getView(final int arg0, View arg1, ViewGroup arg2)
{
LayoutInflater inflater = getLayoutInflater();
arg1 = inflater.inflate(R.layout.custom, null);
TextView textview = (TextView)arg1. findViewById(R.id.textView1);
textview.setText(listItems.get(arg0));
ImageView image = (ImageView)arg1. findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
listItems.remove(arg0);
listView.setAdapter(adapter);
Toast.makeText(MainActivity.this, "Item has been successfully deleted", Toast.LENGTH_LONG)
.show();
}
});
return arg1;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public int getCount() {
//code to set the list item size according to array data size
return listItems.size();
}
};
listView.setAdapter(adapter);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
listItems= mHelper.addListItem(editText.getText().toString());
adapter.notifyDataSetChanged();
listView.setSelection(listView.getAdapter().getCount()-1);
editText.getText().clear();
}
});
}
}
DATABASE HANDLER.JAVA
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MyDatabase.db";
private static final String TABLE_LIST = "MyListItem";
private static final String KEY_ID = "id";
private static final String KEY_ListItem = "listitem";
public static final String KEY_NAME = null;
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_LIST_TABLE = "CREATE TABLE " + TABLE_LIST + "(" + KEY_ID
+ " integer primary key autoincrement," + KEY_ListItem + " TEXT" + ")";
db.execSQL(CREATE_LIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);
onCreate(db);
}
ArrayList<String> addListItem(String listItem)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ListItem, listItem);
db.insert(TABLE_LIST, null, values);
ArrayList<String> items=new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LIST;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
items.add(cursor.getString(1));
cursor.moveToNext();
}
cursor.close();
db.close();
return items;
}
Cursor getListItem()
{
String selectQuery = "SELECT * FROM " + TABLE_LIST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
}
To delete single data entry(i.e. Row) make a method in database handler:
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + "=?",
new String[] { String.valueOf(id) }); // KEY_ID= id of row and third parameter is argument.
db.close();
}
This method will delete single row which ID is given.
You will need to make a method deleteItem in your DataBaseHandler class. Which will do something like,
db.delete(TABLE_LIST , KEY_ID + "=" + yourIdToBeDeleted, null);
And make a call to this method from your delete button/image's onClick as:
mHelper.deleteItem(idOfItemToBeDeleted);
Hope it helps.

How to use or instantiate Sqlite Database Helper class instance inside a custom dapter class in Android?

I am absolute beginner to Android. Now I am creating a tutorial project. In my project I am using ListView with custom adapter. But I created the custom adapter as a different and standalone file to make my activity clean. But when I create it in a different file, I cannot use my database helper class inside the custom adapter.
The problem is I cannot pass the Activity context to the database helper class instance. In fragment, I can pass by calling this method.getActivity(). Then pass it to the constructor of my database helper class. How can I do the same thing in my custom adapter class?
This is my database helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "todo.db";
private static final String TABLE_NAME = "task";
private static final String COLUMN_ID = "id";
private static final String COLUMN_DESCRIPTION = "description";
private static final String COLUMN_DATE ="date";
private static final String COLUMN_DONE = "done";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COLUMN_DESCRIPTION+" TEXT,"+
COLUMN_DATE+" DATE,"+COLUMN_DONE+" BOOLEAN)";
SQLiteDatabase db;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
this.db = db;
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
public void insertTask(Task task)
{
db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DESCRIPTION,task.getDescription());
values.put(COLUMN_DATE,task.getDate());
values.put(COLUMN_DONE, Boolean.FALSE.toString());
db.insert(TABLE_NAME, null, values);
db.close();
}
public ArrayList<Task> getAllTasks()
{
ArrayList<Task> items = new ArrayList<Task>();
db = getReadableDatabase();
String query = "SELECT * FROM "+TABLE_NAME;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst())
{
do{
Task item = new Task();
item.setId(cursor.getInt(0));
item.setDescription(cursor.getString(1));
item.setDate(cursor.getString(2));
item.setDone(Boolean.valueOf(cursor.getString(3)));
items.add(item);
}
while (cursor.moveToNext());
}
return items;
}
public void markAsDone(int id){
db = getWritableDatabase();
ContentValues updatedData = new ContentValues();
updatedData.put(COLUMN_DONE, String.valueOf(Boolean.TRUE));
String where = COLUMN_ID+" = "+String.valueOf(id);
db.update(TABLE_NAME,updatedData,where,null);
}
}
This is my custom adapter class for listView (TaskListAdapter.java):
public class TaskListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
private DatabaseHelper dbHelper;
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.task_list_row,parent, false);
rowView.setTag(values.get(position).getId());
TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
rowDescription.setText(values.get(position).getDescription());
ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);
Long currentDateMillSec= System.currentTimeMillis();
Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
if(values.get(position).getDone()==Boolean.TRUE)
{
rowStatusIcon.setImageResource(R.drawable.done_icon);
}
else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
{
rowStatusIcon.setImageResource(R.drawable.failed_icon);
}
else{
rowStatusIcon.setImageResource(R.drawable.todo_icon);
}
TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
dateTf.setText(values.get(position).getDate());
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//how can I instantiate the dbHelper class
//Then use the merkAsDone method here
}
});
return rowView;
}
}
How can I instantiate the dbHelper property in my custom adapter and then call the markAsDone method in the done button click event. How can I achieve it whereas the adapter is not created within Activity?
Does not look like a big problem, instantiate it in your constructor:
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.dbHelper = new DatabaseHelper(context.getApplicationContext());
this.context = context;
this.values = values;
}
Then use it in your OnClickListener:
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setTag(values.get(position).getId());
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(v.getTag());
}
});
Don't forget to close your Database in DatabaseHelper.markAsDone
Firstly if you want to use the db inside the adapter , you can use CursorAdapter not ArrayAdapter ,
if you want to stay on arrayAdapter , then you can pass th db Object in the construcor
You should make the DatabaseHelper class as thread-safe Singleton and then get that instance from the adapter.
public class DatabaseHelper extends SQLiteOpenHelper{
private static DatabaseHelper dbHelper;
public static DatabaseHelper getInstance() {
if(dbHelper == null)
{
synchronized (DatabaseHelper.class)
{
if(dbHelper == null)
{
dbHelper = new DatabaseHelper(MyApplicationInstance.getAppContext());
}
}
}
return dbHelper;
}
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
And then in the CustomAdapter just execute your commands as DatabaseHelper.getInstance().insert()
Hope this helps.

Categories