I am trying the tutorial notepadv2 for android. I did everything the tutorial said (and used only the code they gave me)and i am getting errors all over the place. Help!!!!
this is my NoteEdit.java file in /src
package com.android.demo.notepad2;
import android.app.Activity;
import android.os.Bundle;
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_edit);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (title != null) {
mTitleText.setText(title);
}
if (body != null) {
mBodyText.setText(body);
}
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
if (mRowId != null) {
bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
}
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
});
}
this is my Notepadv2.java file in /src
package com.android.demo.notepad2;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Notepadv2 extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private NotesDbAdapter mDbHelper;
private Cursor mNotesCursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_list);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, mNotesCursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID,0, R.string.menu_insert);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createNote();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(Menu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createNote() {
Intent i = new Intent(this, NoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.createNote(title, body);
fillData();
break;
case ACTIVITY_EDIT:
Long mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (mRowId != null) {
String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.updateNote(mRowId, editTitle, editBody);
}
fillData();
break;
}
}
}
These are the two files that the errors are coming from
NoteEdit will not compile because it has no class declaration...
package com.android.demo.notepad2;
import android.app.Activity;
import android.os.Bundle;
//missing this line:
//public class NoteEdit extends Activity {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_edit);
Without a class declaration, the parser will spit up errors all over the place, as nothing will make sense anymore.
I am not sure if there are any errors in Notepadv2 just by looking at it.
Related
I'm trying to retrieve my data from database into checkbox list view, but I'm unable to do so. Below is the code that I'm already using to retrieve data from database into list view. But what I want is to retrieve into checkbox list view type so that I can check it. How can I do that?
public class StudentDetailActivity extends Activity implements OnClickListener, OnItemClickListener {
private ListView uGraduateNamesListView;
private Button addNewUndergraduateButton;
private ListAdapter uGraduateListAdapter;
private ArrayList<UndergraduateDetailsPojo> pojoArrayList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_detail);
uGraduateNamesListView = (ListView) findViewById(R.id.uGraduateListView);
uGraduateNamesListView.setOnItemClickListener(this);
addNewUndergraduateButton = (Button) findViewById(R.id.namesListViewAddButton);
addNewUndergraduateButton.setOnClickListener(this);
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}
#Override
public void onClick(View v) {
Intent addNewUndergraduateIntent = new Intent(this, AddNewUndergraduateActivity.class);
startActivity(addNewUndergraduateIntent);
}
public List<String> populateList(){
List<String> uGraduateNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String ugName = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME));
String ugUniId = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_UNI_ID));
double ugGpa = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLLUMN_NAME_UNDERGRADUATE_GPA));
UndergraduateDetailsPojo ugPojoClass = new UndergraduateDetailsPojo();
ugPojoClass.setuGraduateName(ugName);
ugPojoClass.setuGraduateUniId(ugUniId);
ugPojoClass.setuGraduateGpa(ugGpa);
pojoArrayList.add(ugPojoClass);
uGraduateNamesList.add(ugName);
}
sqliteDatabase.close();
return uGraduateNamesList;
}
#Override
protected void onResume() {
super.onResume();
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}
#Override
protected void onStart() {
super.onStart();
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}
public void onClick1 (View view)
{
Intent newIntent;
newIntent=new Intent(this,HomePageActivity.class);
startActivity(newIntent);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Clicked on :" + arg2, Toast.LENGTH_SHORT).show();
Intent updateDeleteUgraduateIntent = new Intent(this, UpdateDeleteUndergraduateActivity.class);
UndergraduateDetailsPojo clickedObject = pojoArrayList.get(arg2);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedUgraduateName", clickedObject.getuGraduateName());
dataBundle.putString("clickedUgraduateUniId", clickedObject.getuGraduateUniId());
dataBundle.putDouble("clickedUgraduateGpa", clickedObject.getuGraduateGpa());
updateDeleteUgraduateIntent.putExtras(dataBundle);
startActivity(updateDeleteUgraduateIntent);
}
}
You can use ListActivity Provided in Android.
You only have to manage your data to required format for this ListActivity.
You Can place action on button instead of Menu Option.
package your_package_name;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class your_activity_name extends ListActivity {
private static final int checkedItem= 0;
private String[] databaseContent;
String checkedItems = new String(); // comma separated
String uncheckedItems = new String(); // comma separated
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseContent = your_data_from_database // this array should contain your data from database.
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, databaseContent));
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, checkedItem, 0, R.string."String you want to show");
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
switch(item.getItemId())
{
case checked:
{
int reqlength = getListAdapter().getCount();
for (int i = 0; i < reqlength ; i++)
{
if (getListView().isItemChecked(i)) {
checkedItems = checkedItems.concat(databaseContent[i]).concat(",");
}
else {
uncheckedItems = uncheckedItems.concat(databaseContent[i]).concat(",");
}
}
Thread thread = new Thread(){
#Override
public void run() {
if ( checkedItems.length() > 0 ||
uncheckedItems.length() > 0
)
{
//Here is your desired output in checkedItems & uncheckedItems
}
}
};
thread.start();
Toast.makeText(your_activity_name.this, R.string.your_string, Toast.LENGTH_SHORT).show();
finish();
return true;
}
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
}
}
For other way please see Link
Android ListView With Checkbox choice without using Built-in AistActivity
Hope this will resolve your problem.
I have an activity with a ViewPager containing 3 fragments.
Each fragment is to hold a listview, and I wish to start a new activity when a list item is clicked.
I am unable to run the startActivity() method from the onItemClickListener. Help!
BTListDevice.java
package com.example.pager;
import java.util.Set;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class BTListDevice extends FragmentActivity {
// Fragments
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
// Return Intent extra
public static String DEVICE_DET = "dev";
private static final int REQUEST_ENABLE_BT = 7;
// Member fields
private static BluetoothAdapter mBtAdapter;
private static DevicesCursor devicesAdapter;
private static ChatDBHelper dbHelper;
private static ListView pairedListView;
private ListView newDevicesListView;
private static ListView homeList;
private static HomeListAdapter iAdap;
boolean buttonState;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Default Adapter for the device
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
dbHelper = new ChatDBHelper(this);
if (mBtAdapter.isEnabled())
buttonState=true;
else
buttonState=false;
invalidateOptionsMenu();
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_navigator);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setCurrentItem(1);
// Set result CANCELED in case the user backs out
setResult(Activity.RESULT_CANCELED);
}
#Override
protected void onResume() {
super.onResume();
if (mBtAdapter.isEnabled())
buttonState=true;
else
buttonState=false;
invalidateOptionsMenu();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_screen_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()) {
case R.id.menu_BT :
{
if (!mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//Toast.makeText(getApplicationContext(), "Enabling Bluetooth..", Toast.LENGTH_SHORT).show();
}
else {
if (mBtAdapter.isEnabled()) {
mBtAdapter.disable();
buttonState=false;
invalidateOptionsMenu();
//Toast.makeText(getApplicationContext(), "Disabling Bluetooth..", Toast.LENGTH_SHORT).show();
}
}
}
return true;
default :
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem BT = menu.findItem(R.id.menu_BT);
if(buttonState)
{
BT.setIcon(R.drawable.bt_on);
return true;
}
else
BT.setIcon(R.drawable.bt_off);
return super.onPrepareOptionsMenu(menu);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode)
{
case REQUEST_ENABLE_BT : {
if(resultCode==RESULT_OK)
{
buttonState=true;
invalidateOptionsMenu();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
String text = String.valueOf(pairedDevices.size());
Toast.makeText(getApplicationContext(),text, Toast.LENGTH_SHORT).show();
if (pairedDevices.size() > 0)
{
dbHelper.DTdelAllData();
for (BluetoothDevice device : pairedDevices)
{
dbHelper.DTinsertData(device.getAddress(), device.getName());
}
}
}
else
{
buttonState=false;
invalidateOptionsMenu();
}
}
break;
}
}
public void searchForDevices(View v)
{
if (mBtAdapter == null) {
Toast.makeText(getApplicationContext(), "Device not supported!", Toast.LENGTH_LONG).show();
return;
}
else
{
if (!mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//Toast.makeText(getApplicationContext(), "Enabling Bluetooth..", Toast.LENGTH_LONG).show();
}
else
{
doDiscovery();
v.setVisibility(View.GONE);
}
}
}
private void doDiscovery() {
//if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle("Scanning");
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
static OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
Cursor c = dbHelper.DTgetAllData();
c.moveToPosition(arg2);
String device = c.getString(0);
// Create the result Intent and include the MAC address
Intent intent = new Intent(BTListDevice.this,ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
BTListDevice.this.startActivity(intent);
}
};
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
Fragment frag;
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0 :
frag = new PairedDevicesFragment();
break;
case 2 :
frag = new NewDevicesFragment();
break;
case 1 :
frag = new HomeScreenFragment();
break;
default :
frag = new HomeScreenFragment();
}
return frag;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
switch(position)
{
case 0 : title = "Paired Devices";
break;
case 1 : title = "Chats";
break;
case 2 : title = "New Devices";
break;
}
return (CharSequence)title;
}
}
public static class PairedDevicesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.paired_devices, container, false);
// Find and set up the ListView for paired devices
pairedListView = (ListView) rootView.findViewById(R.id.paired_devices);
pairedListView.setOnItemClickListener(mDeviceClickListener);
new Handler().post(new Runnable() {
#Override
public void run() {
devicesAdapter = new DevicesCursor(getActivity().getApplicationContext(), dbHelper.DTgetAllData());
pairedListView.setAdapter(devicesAdapter);
}
});
return rootView;
}
}
public static class NewDevicesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.new_devices, container, false);
// Find and set up the ListView for paired devices
pairedListView = (ListView) rootView.findViewById(R.id.new_devices);
pairedListView.setOnItemClickListener(BTListDevice.mDeviceClickListener);
return rootView;
}
}
public static class HomeScreenFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_screen, container, false);
homeList = (ListView)rootView.findViewById(android.R.id.list);
Cursor cur = dbHelper.CTgetChatDevices();
cur.moveToFirst();
if(cur.getCount()>0)
{
new Handler().post(new Runnable() {
#Override
public void run() {
iAdap = new HomeListAdapter(getActivity().getApplicationContext());
homeList.setAdapter(iAdap);
}
});
}
else
{
TextView empty = (TextView)rootView.findViewById(android.R.id.empty);
empty.setText("There is No Cheese!");
empty.setVisibility(View.VISIBLE);
homeList.setVisibility(View.GONE);
}
return rootView;
}
}
}
EDIT :
When i try to call startActivity(), I get this error in onItemClickListener.
Cannot make a static reference to the non-static method startActivity(Intent) from the type Activity.
Just Change the code for each fragment
public static class PairedDevicesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.paired_devices, container, false);
// Find and set up the ListView for paired devices
pairedListView = (ListView) rootView.findViewById(R.id.paired_devices);
pairedListView.setOnItemClickListener(mDeviceClickListener);
new Handler().post(new Runnable() {
#Override
public void run() {
devicesAdapter = new DevicesCursor(getActivity().getApplicationContext(), dbHelper.DTgetAllData());
pairedListView.setAdapter(devicesAdapter);
}
});
pairedListView .setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Cursor c = dbHelper.DTgetAllData();
c.moveToPosition(arg2);
String device = c.getString(0);
// Create the result Intent and include the MAC address
Intent intent = new Intent(getActivity(),ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
getActivity().startActivity(intent);
}
});
return rootView;
}
}
Give this a try,
Instead of doing it this way, getActivity().startActivity(intent);
try this,
BTListDevice.this.startActivity(intent);
Change the onItemClick Code as following
static OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
Cursor c = dbHelper.DTgetAllData();
c.moveToPosition(arg2);
String device = c.getString(0);
// Create the result Intent and include the MAC address
Intent intent = new Intent(getActivity(),ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
getActivity().startActivity(intent);
}
};
Try this fragment of code
// Create the result Intent and include the MAC address
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
startActivity(intent);
I'm trying to convert Activity to a fragment and can't override this methods : onCreateOptionsMenu,onOptionsItemSelected,onContextItemSelected.
,maybe some import statements are missing ? don't know what to do.Her is my Class file :
package com.wts.ui;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainFragment extends Fragment {
protected final static int REQUEST_CODE = 1;
public static WordsDBAdapter dbAdapter;
private CustomAdapter cDataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
// context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
private final static int IDM_INFO = 103;
// options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
private static final int IDM_SETTINGS = 203;
private static final int IDM_QUESTION = 204;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbAdapter = new WordsDBAdapter(getActivity());
dbAdapter.open();
displayListView();
registerForContextMenu(listView);
// ================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor) listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(WordsDBAdapter.ID_COL);
return false;
}
});
// ================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if (word.length() > 0 && translate.length() >= 0) {
Cursor cursor = dbAdapter.fetchWordsByName(word);// chek is
// word
// repeat
if (cursor.moveToFirst()) {
Toast.makeText(getActivity().getApplicationContext(),
getResources().getString(R.string.word_exist),
Toast.LENGTH_SHORT).show();
} else if (!CheckWordInput(word)
|| !CheckTranslateInput(translate)) {
Toast.makeText(
getActivity().getApplicationContext(),
getResources().getString(
R.string.incorrect_input),
Toast.LENGTH_SHORT).show();
} else {
dbAdapter.insertWord(word, translate, " ",
String.valueOf(false), 0, 0, new Date());
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
button = (Button) view.findViewById(R.id.buttonAddWord);
listView = (ListView) view.findViewById(R.id.listWords);
editWord = (EditText) view.findViewById(R.id.editWord);
editTranslate = (EditText) view.findViewById(R.id.editTranslate);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// setContentView(R.layout.activity_main);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_EDIT]);
menu.add(Menu.NONE, IDM_INFO, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_INFO]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_DELETE]);
}
}
//
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT: {
Intent intent = new Intent(getActivity(), EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(WordsDBAdapter.WORD_COL));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(WordsDBAdapter.TRANS_COL));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(WordsDBAdapter.DESC_COL));
startActivityForResult(intent, REQUEST_CODE);
}
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
case IDM_INFO: {
Intent intent = new Intent(getActivity(), InformationActivity.class);
for (int i = 1; i <= InformationActivity.nListItems; i++)
intent.putExtra(String.valueOf(i), cursor.getString(i));
startActivity(intent);
}
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
private void displayListView() {
// Cursor cursor = dbAdapter.fetchAllTranslated();
Cursor cursor = dbAdapter.fetchAllTranslated();
String[] columns = new String[] { WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION, WordsDBAdapter.KEY_SUCCEEDED, };
int[] to = new int[] { R.id.textViewTranslate, R.id.textViewWord,
R.id.textViewSuccessPoints };
cDataAdapter = new CustomAdapter(getActivity(), R.layout.word_info,
cursor, columns, to);
listView.setAdapter(cDataAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_ABOUT: {
Intent intent = new Intent(getActivity(), AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT: {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
break;
}
case IDM_SETTINGS: {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
break;
}
case IDM_QUESTION: {
if (!StartActivity.isMainActivitySart)
getActivity().onBackPressed();
else {
Intent intent = new Intent(getActivity(),
QuestionActivity.class);
startActivity(intent);
}
}
break;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
if (intent.hasExtra(getResources().getString(R.string.fstRow))) {
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(
getResources().getString(R.string.fstRow)),
intent.getExtras().getString(
getResources().getString(R.string.scndRow)),
intent.getExtras().getString(
getResources().getString(R.string.thrdRow)),
null, null, null, null);
displayListView();
}
}
}
#Override
public void onResume() {
super.onResume();
SettingsManager.setPreferedLanguage(getActivity());// set language
displayListView();
}
public static boolean CheckTranslateInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{0,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
public static boolean CheckWordInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{1,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
#Override
public void onDetach() {
super.onDetach();
dbAdapter.close();
}
}
You have to think about what you want your Fragment to be - Fragment or SherlockFragment?
You import this:
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
And so, your overrides aren't overrides because Menu & friends are different classes right now than what Fragment needs - they are ActionBarSherlock's classes.
If you extend SherlockFragment instead, your overrides should work, and it is recommended to extend SherlockFragment if you are using ActionBarSherlock (which based on your tags, you are).
If you want to keep this as a regular fragment, then import:
android.view.Menu
android.view.MenuItem
android.view.MenuInflater
I have been trying for hours to figure out why android crashes after loading Profile activity. The line that is causing the issue is :
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID): null;
located in Profile.java. so I have firstly
OvertheLimit.java which puts extras via a menu option intent:
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Overthelimit extends ListActivity {
private OverLimitDbAdapter dbHelper;
private static final int USER_CREATE = 0;
private static final int USER_EDIT = 1;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getListView();
dbHelper = new OverLimitDbAdapter(this);
dbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void fillData() {
cursor = dbHelper.fetchAllUserDrinks();
startManagingCursor(cursor);
String[] from = new String[] { OverLimitDbAdapter.KEY_USERNAME };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.user_row, cursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
Intent myIntent1 = new Intent(Overthelimit.this, Profile.class);
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
startActivityForResult(myIntent1, 0);
return true;
case R.id.myusual:
Intent myIntent2 = new Intent(Overthelimit.this, MyUsual.class);
startActivityForResult(myIntent2, 0);
return true;
case R.id.trackme:
Intent myIntent3 = new Intent(Overthelimit.this, TrackMe.class);
startActivityForResult(myIntent3, 0);
return true;
case R.id.moreinfo:
Intent myIntent4 = new Intent(Overthelimit.this, MoreInfo.class);
startActivityForResult(myIntent4, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
}
then selecting the profile menu option takes me to Profile, which crashes trying to get extras.
I have checked data using toast and it's there. any ideas?
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
public class Profile extends Activity{
private EditText mUserName;
private RadioGroup mGender;
private EditText mAge;
private EditText mHeight;
private EditText mWeight;
private Spinner mDrinkerType;
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.profile);
mUserName = (EditText) findViewById(R.id.userName);
mAge = (EditText) findViewById(R.id.age);
mHeight = (EditText) findViewById(R.id.height);
mWeight = (EditText) findViewById(R.id.weight);
mGender = (RadioGroup) findViewById(R.id.gender);
mDrinkerType = (Spinner) findViewById(R.id.drinkerType);
Button next = (Button) findViewById(R.id.NextUsualDrinks);
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID)
: null;
}
populateFields();
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
//finish();
Intent myIntent = new Intent(view.getContext(), MyUsual.class);
startActivityForResult(myIntent, 0);
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor todo = mDbHelper.fetchUserDrinks(mRowId);
startManagingCursor(todo);
mUserName.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_USERNAME)));
String gender = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_GENDER));
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String bn = (String) b.getText();
if (bn.equalsIgnoreCase(gender)) {
if(gender == "male")
((RadioButton) findViewById(R.id.male)).setChecked(true);
else if (gender == "female")
((RadioButton) findViewById(R.id.female)).setChecked(true);
}
mAge.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_AGE)));
mHeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_HEIGHT)));
mWeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_WEIGHT)));
String drinkerType = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_TYPE));
for (int i = 0; i < mDrinkerType.getCount(); i++) {
String s = (String) mDrinkerType.getItemAtPosition(i);
Log.e(null, s + " " + drinkerType);
if (s.equalsIgnoreCase(drinkerType)) {
mDrinkerType.setSelection(i);
}
}
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String username = mUserName.getText().toString();
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String gender = (String) b.getText();
String age = mAge.getText().toString();
String height = mHeight.getText().toString();
String weight = mWeight.getText().toString();
String type = (String) mDrinkerType.getSelectedItem();
if (mRowId == null) {
long id = mDbHelper.createUserProfile(username, gender, age, height, weight, type);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateUserProfile(mRowId, username, gender, age, height, weight, type);
}
}
}
Your problem is most likely that you add a String extra (as cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)) returns a String) - but try to get a Long extra - which does not compute.
The following should fix the problem:
mRowId = extras != null ? Long.parseLong( extras.getString(OverLimitDbAdapter.KEY_ROWID) ) : null;
In your Overthelimit class you set the value with the following line:
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
This puts a String value into the intent extras. Trying to get the same value as a Long value will make you applications crash, as it does not exist as a Long value. If you instead convert the value you get from your cursor object (or gets it directly as a Long from your cursor), your application should not crash anymore. Alternatively, you can get your value from the intent extras by using getString(), not getLong().
I think it giving type casting error as you store the value as string in put try to type cast at putting the value time or get the as string and then convert to long value but for type casting may be you getting type casting error in this so put into the try catch block and see the logcat details to detecting the error
type cast here from string to long or
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID,cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
or get as string here and then type cast from string to long
String s = extras.getString(OverLimitDbAdapter.KEY_ROWID);
mRowId = extras != null ? Long.parseLong(s): null;
i am really stuck. I am familiar in Java and Android development but i do not have any experience with databases. This is my first time. I have been going through multiple tutorials but i cannot figure out how return all the values from a specific row and set it to a single string.
Below is my database console. I was able to get all the items and display it in my view but i intended on writing a specific function to do something with all the data in only the TITLE column. Can anyone shed any light or provide a small routine to get all the items from the TITLE column into a single string? The very last function is my getTitleList that is where i would like to gather the data
Here is the function:
public void getTitleList(){
cursor = db.rawQuery("SELECT TITLE FROM table", null);
cursor.close();
}
Here is my class
package edu.asu;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.view.View;
import android.app.ListActivity;
import static android.provider.BaseColumns._ID;
public class DbBookConsole extends ListActivity {
private static String[] FROM = { _ID, DbConstants.TITLE, DbConstants.PRICE,
DbConstants.ISBN, DbConstants.CHECKIN };
private DbCreate books;
private static SQLiteDatabase db;
private static int[] TO = { R.id.rowid, R.id.name, R.id.price, R.id.isbn, R.id.checkin};
private ListView lv1;
private static String itemId;
private static String titles;
private static String test;
private Cursor cursor;
static final int BOOK_CANCELED = 0;
static final int BOOK_ADDED = 1;
static final int BOOK_MODIFIED = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showDatabaseContent();
lv1 = getListView();
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
cursor = (Cursor) a.getItemAtPosition(position);
itemId = cursor.getString(0);
openOptionsMenu();
}
});
lv1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
// selected item index from ListView
public void showDialogItemId(long itemId) {
Toast.makeText(this,
"Menu item selected index is" + Long.toString(itemId),
Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.modifyitem:
if (null != itemId) {
Bundle bookToModify = new Bundle();
bookToModify.putString("cTitle", cursor.getString(1));
bookToModify.putString("cPrice", cursor.getString(2));
bookToModify.putString("cISBN", cursor.getString(3));
bookToModify.putString("cCheckin", cursor.getString(4));
bookToModify.putString("mod_type", "modifyBook");
Intent intent = new Intent(this, BookDetails.class);
intent.setClass(this, BookDetails.class);
intent.putExtras(bookToModify);
startActivityForResult(intent, BOOK_MODIFIED);
} else {
Toast
.makeText(this, "Select Book to modify",
Toast.LENGTH_LONG).show();
}
break;
case R.id.additem:
Intent i = new Intent(this, BookDetails.class);
Bundle bun = new Bundle();
bun.putString("mod_type", "addBook");
i.setClass(this, BookDetails.class);
i.putExtras(bun);
startActivityForResult(i, BOOK_ADDED);
break;
case R.id.removeitem:
if (null != itemId) {
removeBook(itemId);
showDatabaseContent();
} else {
Toast
.makeText(this, "Select Book to delete",
Toast.LENGTH_LONG).show();
}
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
// See which child activity is calling us back.
switch (resultCode) {
case BOOK_ADDED:
// This is the standard resultCode that is sent back if the
// activity crashed or didn't doesn't supply an explicit result.
if (resultCode == RESULT_FIRST_USER) {
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("bookData");
addBook(bundle);
showDatabaseContent();
} else {
Toast.makeText(this, "CANCEL BOOK BUTTON PRESSED",
Toast.LENGTH_LONG).show();
}
break;
case BOOK_MODIFIED:
if (resultCode == 2) {
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("bookData");
modifyBook(bundle);
showDatabaseContent();
} else {
Toast.makeText(this, "MODIFY BOOK FAILED", Toast.LENGTH_LONG)
.show();
}
break;
default:
break;
}
}
// method removes item from database
private void removeBook(String itemId) {
db = books.getWritableDatabase();
db.delete(DbConstants.TABLE_NAME, "_ID=" + itemId, null);
}
private void addBook(Bundle bundle) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
db = books.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.TITLE, bundle.getString("bookTitle"));
vals.put(DbConstants.PRICE, bundle.getString("bookPrice"));
vals.put(DbConstants.ISBN, bundle.getString("bookISBN"));
vals.put(DbConstants.CHECKIN, bundle.getString("bookCheck"));
db.insertOrThrow(DbConstants.TABLE_NAME, null, vals);
}
// method should modify existing Contact
private void modifyBook(Bundle bundle) {
db = books.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.TITLE, bundle.getString("bookTitle"));
vals.put(DbConstants.PRICE, bundle.getString("bookPrice"));
vals.put(DbConstants.ISBN, bundle.getString("bookISBN"));
vals.put(DbConstants.CHECKIN, bundle.getString("bookCheck"));
db.update(DbConstants.TABLE_NAME, vals, _ID + "=" + itemId, null);
}
private Cursor getBooks() {
db = books.getReadableDatabase();
cursor = db.query(DbConstants.TABLE_NAME, FROM, null, null, null, null, null,
null);
startManagingCursor(cursor);
return cursor;
}
public void showDatabaseContent() {
books = new DbCreate(this);
try {
cursor = getBooks();
showBooks(cursor);
} finally {
books.close();
db.close();
}
}
private void showBooks(Cursor cursor) {
// set up data binding
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
public void getTitleList(){
cursor = db.rawQuery("SELECT TITLE FROM table", null);
cursor.close();
}
}
unless i missunderstood the Question to get all items from your query in a cursor, loop through all items and concatenate into a string you would do something like this:
// constants of column indexes
int INDEX_ROWID = 0;
int INDEX_TITLE = 1;
...
db = new MyDBAdapter(this);
db.open();
Cursor c = db.getTitleList();
startManagingCursor(c);
String allTitles;
// loop through cursor
while(c.moveToNext()) {
allTitles += c.getString(INDEX_TITLE);
}
Hope that helps