How to add Line Break on ViewText? - java

I'm a newbie. I'm editing Searchable Dictionary given to sample on SDK.
Dictionary follows a database on \res\raw\definitions.txt
when searching word shows result (defination) like below-
line1 line2 line3
But I want to add line break on result and show (defination) like below-
line1
line2
line3
code of WordActivity.java is here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word);
Uri uri = getIntent().getData();
Cursor cursor = managedQuery(uri, null, null, null, null);
if (cursor == null) {
finish();
} else {
cursor.moveToFirst();
TextView word = (TextView) findViewById(R.id.word);
TextView definition = (TextView) findViewById(R.id.definition);
int wIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_WORD);
int dIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_DEFINITION);
word.setText(cursor.getString(wIndex));
definition.setText(cursor.getString(dIndex));
}}
public void onBackPressed() {
onSearchRequested();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// TODO Auto-generated method stub
case R.id.search:
onSearchRequested();
return true;
case R.id.about:
setContentView(R.layout.abouttanzil);
return true;
case R.id.exit:
moveTaskToBack(true);
return true;
default:
return false;
}
}
}
Please let me know what should i add and where to make line break??
Thanks in advance.

Display it as HTML and use \n.
yourTextView.setText(Html.fromHtml(someText + "\n" + someOtherText));
Obviously there are smarter ways. Just showing you the Html.fromHtml() method.

Related

How to make calls and visit website from context menu on long clicking listview items?

I am trying to learn the Android onLongclick context menu actions. When clicking an item on list it displays two action image one for calling and another for website url. But I am having null pointer exception. When toasting using the toast method it can display number and url. But this is not what i want to to. Its just for test. I want to dial the number when phone action is clicked and visit website when url action is clicked. I have commented toast for doing so. And tried to create perform call and performUrl() methods. I took idea from the example with toast so i tried to modify it but its simply not working so i commented the performCall() and performUrl() methods for now. Could anyone suggest how to make these things happen?
I have a department class which is a pure java class.
public class DepartmentActivity extends Activity {
//Department dept = new Department();
private ListView listView;
ArrayAdapter<Department> adapter;
//String list_item;
Object mActionMode;
private Department[] myDepartment = {
new Department("CS", "cs#yahoo.edu", "405.111.2222"),
new Department("Biology", "bio#yahoo.edu", "405.222.3333"),
new Department("Business", "business#yahoo.com", "405.333.4444"),
new Department("Music", "music#yahoo.com", "405.444.5555"),
new Department("Engineering", "engg#ucoll.com", "405.555.6666"),
new Department("Nursing", "nursing#yahoo.com", "213.555.6666")
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_department);
listView =(ListView) findViewById(R.id.list);
//adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.deptlist, deptList);
adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.deptlist, myDepartment);
listView.setAdapter(adapter);
//listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//listener = new listView.OnItemLongClickListener(this);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//list_item = myDepartment.toString();
if (mActionMode != null){
return false;
}
mActionMode = DepartmentActivity.this.startActionMode(mActionModeCallback);
return true;
}
});
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//mode.setTitle(list_item);
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
//return false;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.action_phone:
performCall();
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.action_www:
//performUrl();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
/*
private void performCall() {
SparseBooleanArray selected = listView.getCheckedItemPositions();
String selectedNames ="";
for (int i = 0; i < selected.size(); i++) {
if (selected.valueAt(i)) {
int pos = selected.keyAt(i);
selectedNames += " " + myDepartment[pos].getPhone();
}
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:"+selectedNames));
startActivity(callIntent);
//Toast.makeText(DepartmentActivity.this, "Call: " + selectedNames,
// Toast.LENGTH_SHORT).show();
}
*/
/*
private void performUrl() {
SparseBooleanArray selected = listView.getCheckedItemPositions();
String selectedNames = "";
for (int i = 0; i < selected.size(); i++) {
if (selected.valueAt(i)) {
int pos = selected.keyAt(i);
selectedNames += " " + myDepartment[pos].getUrl();
}
}
//Toast.makeText(DepartmentActivity.this, "Url: " + selectedNames,
//Toast.LENGTH_SHORT).show();
}
*/
Stack trace
....PID: 3250
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.util.SparseBooleanArray.size()' on a null object reference
at esu.uco.rawal.p4rabina.DepartmentActivity.performCall(DepartmentActivity.java:108)
at esu.uco.rawal.p4rabina.DepartmentActivity.access$100(DepartmentActivity.java:18)
at esu.uco.rawal.p4rabina.DepartmentActivity$2.onActionItemClicked(DepartmentActivity.java:85)
at com.android.internal.policy.PhoneWindow$DecorView$ActionModeCallback2Wrapper.onActionItemClicked(PhoneWindow.java:3540)
at com.android.internal.app.WindowDecorActionBar$ActionModeImpl.onMenuItemSelected(WindowDecorActionBar.java:1093)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at android.widget.ActionMenuView.invokeItem(ActionMenuView.java:616)
at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:141)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Thank You

Switch statement just returning the last case

Switch statment fix:
The switch statement is only returning the last case i.e case 4, "#0R0dfdf0FF". how can i fix this so the text view shows the the one clicked in the dialogue box?
I'm a total newbie so yes help would really be appreciated.
public class NoteEdit extends Activity {
public EditText mTitleText;
public EditText mBodyText;
public EditText mColor;
private NotesDbAdapter mDbHelper;
private static final int DIALOG_ALERT = 10;
Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.done);
mTitleText = (EditText) findViewById(R.id.editTitle);
mBodyText = (EditText) findViewById(R.id.editNote);
mColor = (EditText) findViewById(R.id.editColor);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
setupActionBar();
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
setResult(RESULT_OK);
finish();
}
return super.onOptionsItemSelected(item);
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
mColor.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_COLOR)));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String color = mColor.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, color);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, color);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
showDialog(DIALOG_ALERT);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);
final String[] colors = {"Blue", "Green", "Yellow", "Red", "Purple"};
builder.setTitle(R.string.body);
builder.setItems(colors, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which){
case 0:
mColor.setText("#000000");
case 1:
mColor.setText("#0000FF");
case 2:
mColor.setText("#0R00FF");
case 3:
mColor.setText("#0R00dsdFF");
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}
} });
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
}
You are missing break; at the end of the switch branches.
Fall Through.
You have to add the break.
case 0:
mColor.setText("#000000");
break;
You can find that in docs
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
You need a break when you don't have a return otherwise it causes fall through
You need the break; after all cases except for the last one or else it'll fall through case by case
switch (which){
case 0:
mColor.setText("#000000");
break;
case 1:
mColor.setText("#0000FF");
break;
case 2:
mColor.setText("#0R00FF");
break;
case 3:
mColor.setText("#0R00dsdFF");
break;
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}

Android: How to show context menu of activity while keeping soft keyboard shown

I would like to show the context menu of my activity while keeping the soft keyboard shown. Here is my code in creating menu for my main activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
MenuItem m = menu.add(0, LOGIN_MENU_ITEM, 0, "Login");
m.setIcon(android.R.drawable.ic_menu_preferences);
m = menu.add(0, CONFIGURE_MENU_ITEM, 0, R.string.menu_settings);
m.setIcon(android.R.drawable.ic_menu_preferences);
m = menu.add(0, EXIT_MENU_ITEM, 0, R.string.menu_exit);
m.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
m = menu.add(0, ABOUT_MENU_ITEM, 0, R.string.menu_about);
m.setIcon(android.R.drawable.ic_menu_info_details);
return result;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = super.onOptionsItemSelected(item);
Intent intent = null;
switch (item.getItemId()) {
case ABOUT_MENU_ITEM:
if (m_AlertDlg != null)
{
m_AlertDlg.cancel();
}
final SpannableString s = new SpannableString(getString(R.string.about).replace("\\n","\n").replace("${VERSION}", getVersion(this)));
Linkify.addLinks(s, Linkify.WEB_URLS);
m_AlertDlg = new AlertDialog.Builder(this)
// .setMessage(getString(R.string.about).replace("\\n","\n").replace("${VERSION}", getVersion(this)))
.setMessage(s)
.setTitle(getString(R.string.menu_about))
.setIcon(R.drawable.icon22_click)
.setCancelable(true)
.show();
((TextView)m_AlertDlg.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
break;
case EXIT_MENU_ITEM:
on(this,false);
// final Boolean exit_rem = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Settings.PREF_REMEMBER, false);
// if (!exit_rem){
// Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
// edit.putString(Settings.PREF_USERNAME, "");
// edit.putString(Settings.PREF_PASSWORD, "");
// edit.commit();
// }
Receiver.pos(true);
Receiver.engine(this).halt();
Receiver.mSipdroidEngine = null;
Receiver.reRegister(0);
stopService(new Intent(this,RegisterService.class));
finish();
break;
case CONFIGURE_MENU_ITEM:
try {
intent = new Intent(this, org.sparksoftsip.sipua.ui.Settings.class);
startActivity(intent);
} catch (ActivityNotFoundException e) {
}
break;
case LOGIN_MENU_ITEM:
LoginScreen();
break;
}
return result;
}
In my main activity, I've built a custom AutoCompleteTextView, wherein it receives focus on start. I listen to key presses here, and plans to open the context menu by listening to the menu button. However nothing is happening to my current code:
public class InstantAutoCompleteTextView extends AutoCompleteTextView {
public InstantAutoCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
private Activity getActivity() {
Context context = getContext();
if (context instanceof Activity) {
return (Activity) context;
} else {
return null;
}
}
#Override
public boolean enoughToFilter() {
return true;
}
#Override
public boolean dispatchKeyEventPreIme(KeyEvent event)
{
Activity activity = getActivity();
if (KeyEvent.KEYCODE_BACK == event.getKeyCode() && event.getAction () == KeyEvent.ACTION_DOWN)
{
Log.v("", "Back Pressed");
activity.onBackPressed();
//Want to call this method which will append text
//init();
}
if (KeyEvent.KEYCODE_MENU == event.getKeyCode() && event.getAction () == KeyEvent.ACTION_DOWN)
{
Log.e("hello", event.toString());
activity.openContextMenu(activity.getWindow().getDecorView().findViewById(android.R.id.content));
}
return true;
//return super.dispatchKeyEventPreIme(event);
}
}
I have tried using
openContextMenu(activity.getWindow().getDecorView().findViewById(android.R.id.content))
however, nothing is happening. I have also tried (activity.findViewById(android.R.id.content)) and (activity.findViewById(android.R.id.content).getViewRoot()), but nothing shows up. How do I remedy this?
It looks I made a foolish mistake. I did not use a context menu, but rather an options menu. So, the code for my on key press should be
openOptionsMenu()
instead of using
openContextMenu(View)

Changing a icon in ActionBar depending on a condition

I am updating a record in a SQLite database when the user presses an icon on the ActionBar. The information being updated is a flag that adds a record to a Favourites page.
PROBLEM
When the user adds or removes the record to favourites, I would like the icon in the ActionBar to change. I have a full star icon and a empty star icon.
The setIcon method displays the the full star icon if the record is a favourite, and a empty star icon if the record is not a favourite.
In the code below you will see I am using a boolean isInFavourite, which is true when String fav = "y".
When entering the Activity, the icon displayed is correct.
When the user clicks on the icon to invoke the onMenuItemClick() method, the record is successfully updated but the icon does not change.
I am unable to change the boolean isInFavourite when the record has been updated because Eclipse wants all the variables to be set as final
Can anyone help me change the icon to once the record has been updated.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
db = new DBHelper(this);
db.createDataBase();
db.openDataBase();
Bundle bundle = getIntent().getExtras();
final String rowid = bundle.getString("id");
final String fav = bundle.getString("fav");
//Boolean to check if record is a favourite
final boolean isInFavourite = fav.contentEquals("y");
menu.add("Add to Favourites")
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
String toggle;
String message;
//Logic to add or remove row from recording.
if (isInFavourite) {
toggle = "n";
message = "Recipe removed from Favourites";
} else {
toggle = "y";
message = "Recipe added to Favourites";
}
//Update favourite record in database
db.updateFavourite(rowid, toggle);
db.close();
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
return true;
}
})
//Set icon depending on whether record is a favourite or not.
.setIcon(isInFavourite ? R.drawable.fav_true : R.drawable.fav_false)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
Thanks to #dmon for the solution
SOLUTION
private DBHelper db = null;
public String fav = null;
public String rowid = null;
public boolean isFav;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Bundle bundle = getIntent().getExtras();
rowid = bundle.getString("id");
fav = bundle.getString("fav");
if (fav.contentEquals("y")) {
isFav = true;
} else {
isFav = false;
}
try {
db = new DBHelper(this);
db.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu_settings, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem fave = menu.findItem(R.id.add);
MenuItem unfave = menu.findItem(R.id.remove);
fave.setVisible(isFav);
unfave.setVisible(!isFav);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.add:
fav = "n";
isFav = false;
updateFav();
supportInvalidateOptionsMenu();
Toast("Removed from Favourites");
return true;
case R.id.remove:
fav = "y";
isFav = true;
updateFav();
supportInvalidateOptionsMenu();
Toast("Added to Favourites");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void updateFav (){
db.openDataBase();
db.updateFavourite(rowid, fav);
db.close();
}
XML File: res/menu/menu_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/add"
android:icon="#drawable/good"
android:showAsAction="always"
/>
<item
android:id="#+id/remove"
android:icon="#drawable/bad"
android:showAsAction="always"/>
The easiest way is to just provide two different buttons and hide/show them accordingly:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inf = new MenuInflater(this);
inf.inflate(R.menu.menu_xml, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem fave = menu.findItem(R.id.favorite);
MenuItem unfave = menu.findItem(R.id.unfavorite);
fave.setVisible(!isFave);
unfave.setVisible(isFave);
return true;
}
Then you invalidate the options menu when the state has changed. Note that you have to have a global variable that has the current state of the item (where isFave is coming from)
invalidateOptionsMenu();
Make the isInFavourite variable a global field (declare it outside of the method, just in the class). Any local variables must be final for a scope below them to use them. However, if you make it global, and declare it above, it doesn't need to be final.

SQlite error when restarting android app

I'm using SQlite database to store my listview data.
I added opportunities to change listview items, delete them by swiping etc. Everything works fine when I run my app using IDE - data can be deleted or changed, but when I'm trying to restart it using my phone, I get this error:
02-04 22:13:03.276 31682-31682/com.example.jeavie.deadlineyesterday E/InputEventReceiver: Exception dispatching input event.
02-04 22:13:03.276 31682-31682/com.example.jeavie.deadlineyesterday E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
02-04 22:13:03.278 31682-31682/com.example.jeavie.deadlineyesterday E/MessageQueue-JNI: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.jeavie.deadlineyesterday.MainActivity$2.onTouch(MainActivity.java:411)
at android.view.View.dispatchTouchEvent(View.java:11772)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2962)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2643)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:448)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1829)
at android.app.Activity.dispatchTouchEvent(Activity.java:3307)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:410)
at android.view.View.dispatchPointerEvent(View.java:12015)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4795)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4609)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4293)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4350)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6661)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6635)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6596)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6764)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:186)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:325)
at android.os.Looper.loop(Looper.java:142)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.
My MainActivity class:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public final static int INTENT_REQUEST_CODE = 1;
public final static int INTENT_REQUEST_CODE_TWO = 2;
public static int INTENT_RESULT_CODE = 1;
public static int INTENT_RESULT_CODE_TWO = 2;
public final static int INTENT_EMPTY_CODE = 0;
public static Integer listNumber = 0;
public static Integer dataNumber = 1;
public static Integer editNumber = 1;
//Swiping
private boolean mSwiping = false; // detects if user is swiping on ACTION_UP
private boolean mItemPressed = false; // Detects if user is currently holding down a view
private ListView listView;
DeadlineActivityAdapter deadlineActivityAdapter;
List<DeadlineActivity> list;
String summary, getData, getTime;
DbActivity db;
Cursor fullData;
boolean full;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
db = new DbActivity(this);
fullData = db.getAllData();
if (fullData.getCount() > 0){
if (fullData.moveToFirst()) {
list = new ArrayList<>();
do {
String check = fullData.getString(7);
if (check.startsWith("li")){
summary=fullData.getString(2);
getData=fullData.getString(3);
getTime=fullData.getString(4);
String deadline=fullData.getString(5);
String tags=fullData.getString(6);
list.add(new DeadlineActivity(String.valueOf(dataNumber - 1), summary, getData, getTime, deadline,
tags));
full = true;
listNumber++;
}
} while (fullData.moveToNext());
}
}
if (!full) list = new ArrayList<>();
Toolbar toolbar = findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
FloatingActionButton addTask = findViewById(R.id.addTask);
addTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, AddTaskActivity.class);
startActivityForResult(intent, INTENT_REQUEST_CODE);
}
});
DrawerLayout drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
listView = findViewById(R.id.listDeadlines);
TextView emptyText = findViewById(android.R.id.empty);
listView.setEmptyView(emptyText);
deadlineActivityAdapter = new DeadlineActivityAdapter(this, list, mTouchListener);
listView.setAdapter(deadlineActivityAdapter);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == INTENT_RESULT_CODE){
if(resultCode == INTENT_RESULT_CODE) {
Cursor newDeadline = db.getAllData();
newDeadline.moveToLast();
summary=newDeadline.getString(2);
getData=newDeadline.getString(3);
getTime=newDeadline.getString(4);
String deadline=newDeadline.getString(5);
String tags=newDeadline.getString(6);
list.add(new DeadlineActivity(String.valueOf(dataNumber), summary, getData, getTime, deadline,
tags));
dataNumber++;
deadlineActivityAdapter.notifyDataSetChanged();
super.onActivityResult(requestCode, resultCode, data);
}
}
else if (requestCode == INTENT_RESULT_CODE_TWO){
if (resultCode == INTENT_RESULT_CODE_TWO) {
String a = list.get(editNumber).getId();
Cursor newDeadline = db.getData(a);
String id = newDeadline.getString(0);
summary=newDeadline.getString(1);
getData=newDeadline.getString(2);
getTime=newDeadline.getString(3);
String deadline=newDeadline.getString(4);
String tags=newDeadline.getString(5);
list.remove(Integer.valueOf(id) - 1);
list.add(Integer.valueOf(id) - 1, new DeadlineActivity(id, summary, getData, getTime, deadline, tags));
deadlineActivityAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.toWeek:
startActivity(new Intent(this, WeekActivity.class));
return true;
case R.id.history:
startActivity(new Intent(this, HistoryActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.tags:
startActivity(new Intent(this, TagsActivity.class));
return true;
case R.id.notifications:
// startActivity(new Intent(this, HistoryActivity.class));
return true;
case R.id.info:
// startActivity(new Intent(this, HistoryActivity.class));
return true;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private View.OnTouchListener mTouchListener = new View.OnTouchListener()
{
float mDownX;
private int mSwipeSlop = -1;
boolean swiped;
#Override
public boolean onTouch(final View v, MotionEvent event) {
if (mSwipeSlop < 0) {
mSwipeSlop = ViewConfiguration.get(MainActivity.this).getScaledTouchSlop();
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mItemPressed) return false; // Doesn't allow swiping two items at same time
mItemPressed = true;
mDownX = event.getX();
swiped = false;
break;
case MotionEvent.ACTION_CANCEL:
v.setTranslationX(0);
mItemPressed = false;
break;
case MotionEvent.ACTION_MOVE:
{
float x = event.getX() + v.getTranslationX();
float deltaX = x - mDownX;
float deltaXAbs = Math.abs(deltaX);
if (!mSwiping) {
if (deltaXAbs > mSwipeSlop) {
mSwiping = true; // tells if user is actually swiping or just touching in sloppy manner
listView.requestDisallowInterceptTouchEvent(true);
}
}
if (mSwiping && !swiped) { // Need to make sure the user is both swiping and has not already completed a swipe action (hence mSwiping and swiped)
v.setTranslationX((x - mDownX)); // moves the view as long as the user is swiping and has not already swiped
if (deltaX > v.getWidth() / 3) { // swipe to right
mDownX = x;
swiped = true;
mSwiping = false;
mItemPressed = false;
v.animate().setDuration(300).translationX(v.getWidth()/3);
int i = listView.getPositionForView(v);
String a = list.get(i).getId();
Cursor newDeadline = db.getData(a);
String id = newDeadline.getString(0);
summary=newDeadline.getString(1);
getData=newDeadline.getString(2);
getTime=newDeadline.getString(3);
String deadline=newDeadline.getString(4);
String tags=newDeadline.getString(5);
boolean isInserted = db.updateData(id, id, summary, getData, getTime, deadline, tags, "history");
if (isInserted)
Toast.makeText(getApplicationContext(), "Deadline completed", Toast.LENGTH_SHORT).show();
list.remove(i);
deadlineActivityAdapter.notifyDataSetChanged();
return true;
}
else if (deltaX < -1 * (v.getWidth() / 3)) { // swipe to left
mDownX = x;
swiped = true;
mSwiping = false;
mItemPressed = false;
v.animate().setDuration(300).translationX(-v.getWidth()/3);
int i = listView.getPositionForView(v);
String a = list.get(i).getId();
Cursor newDeadline = db.getData(a);
String id = newDeadline.getString(0);
summary=newDeadline.getString(1);
getData=newDeadline.getString(2);
getTime=newDeadline.getString(3);
String deadline=newDeadline.getString(4);
String tags=newDeadline.getString(5);
boolean isInserted = db.updateData(id, id, summary, getData, getTime, deadline, tags, "history");
if (isInserted)
Toast.makeText(getApplicationContext(), "Deadline completed", Toast.LENGTH_SHORT).show();
list.remove(i);
deadlineActivityAdapter.notifyDataSetChanged();
return true;
}
}
}
break;
case MotionEvent.ACTION_UP: {
if (mSwiping) { // if the user was swiping, don't go to the and just animate the view back into position
v.animate().setDuration(300).translationX(0).withEndAction(new Runnable() {
#Override
public void run() {
mSwiping = false;
mItemPressed = false;
listView.setEnabled(true);
}
});
}
else { // user was not swiping; registers as a click
//set item click "animation"
ColorDrawable[] color = {
new ColorDrawable(getColor(R.color.grey)),
new ColorDrawable(getColor(R.color.dark_dark_grey))
};
TransitionDrawable trans = new TransitionDrawable(color);
v.setBackground(trans);
trans.startTransition(1000); // duration 2 seconds
// Go back to the default background color of Item
ColorDrawable[] color2 = {
new ColorDrawable(getColor(R.color.dark_dark_grey)),
new ColorDrawable(getColor(R.color.the_darkest_grey))
};
TransitionDrawable trans2 = new TransitionDrawable(color2);
v.setBackground(trans2);
trans2.startTransition(1000); // duration 2 seconds
editNumber = listView.getPositionForView(v);
String a = list.get(editNumber).getId();
Cursor newDeadline = db.getData(a);
String id = newDeadline.getString(0);
Intent intent = new Intent();
intent.putExtra("number", id);
intent.setClass(MainActivity.this, EditTaskActivity.class);
startActivityForResult(intent, INTENT_REQUEST_CODE_TWO);
mItemPressed = false;
listView.setEnabled(true);
return true;
}
}
default:
return false;
}
return true;
}
};
}
I added OnTouch method.
At a guess you may be a little confused with how to handle cursors.
The rule so very often found as broken is that a Cursor, unless specifically set to null, will NEVER be null. Any check for a null Cursor is more than likely unnecessary.
Additionally moveToFirst without then doing something with that first row may well result in handling issues.
As such I'd suggest that you change the getData method to be something like :-
public Cursor getData(String id) {
SQLiteDatabase db = this.getReadableDatabase();
return dq.query(true,
new String[] { DB_NUMBER, DB_SUMMARY,
DB_DATE, DB_TIME, DB_DEADLINE, DB_TAGS},
DB_ID + "=?",
new String[]{id},
null,null,null,null
);
}
i.e. just return the cursor as the null check is useless, moveToFirst is quite likely to result in issues.
In the code that calls the getData method, as it's finding by id and thus only find 1 row then :-
Cursor csr = mydbhlpr.getData();
if(csr.moveToFirst) {
//your code to retrieve and act upon the data from the cursor
} else {
//your code, if needed, to handle no row being found.
}
My guess is that you've assumed done something like :-
Cursor csr = mydbhlpr.getData(); // assuming it is not empty and moved to first row
String mydata = csr.getString(whatever_column_offset);
Note, this is just guessing at what your issue may be (see comment re adding onTouch)
your data base is empty and you are requesting for a row from it
that's what the error says
populate your database before querying it for rows
else include a if statement by checking the cursor size
call the DatabaseHelper insertData function from your MainActivity to populate the database
From your MainActivity you are just querying data from database
I do not see anywhere that you have inserted data to you database

Categories