Search Results

Search found 135 results on 6 pages for 'listactivity'.

Page 6/6 | < Previous Page | 2 3 4 5 6 

  • Android SQLlite crashes after trying retrieving data from it

    - by Pavel
    Hey everyone. I'm kinda new to android programming so please bear with me. I'm having some problems with retrieving records from the db. Basically, all I want to do is to store latitudes and longitudes which GPS positioning functions outputs and display them in a list using ListActivity on different tab later on. This is how the code for my DBAdapter helper class looks like: public class DBAdapter { public static final String KEY_ROWID = "_id"; public static final String KEY_LATITUDE = "latitude"; public static final String KEY_LONGITUDE = "longitude"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "coords"; private static final String DATABASE_TABLE = "coordsStorage"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table coordsStorage (_id integer primary key autoincrement, " + "latitude integer not null, longitude integer not null);"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } 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); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS titles"); onCreate(db); } } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertCoords(int latitude, int longitude) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_LATITUDE, latitude); initialValues.put(KEY_LONGITUDE, longitude); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_LATITUDE, KEY_LONGITUDE}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_LATITUDE, KEY_LONGITUDE}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- /*public boolean updateTitle(long rowId, int latitude, int longitude) { ContentValues args = new ContentValues(); args.put(KEY_LATITUDE, latitude); args.put(KEY_LONGITUDE, longitude); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) 0; }*/ } Now my question is - am I doing something wrong here? If yes could someone please tell me what? And how I should retrieve the records in organised list manner? Help would be greatly appreciated!!

    Read the article

  • android Xml-List view with filter

    - by harisali
    Hi, android is new for me. I am trying to develop a program on 1.5 platform but still in progress, plz guide me. I have some information in following format "item1","description1" "item2","description2" "item3","description3" "item4","description4" . . . . I want to show them on screen, I dont know which is recommended way to do this. After google I found 2 method. but I failed to successfully implement any of one. Method 1 I break both columns data into 2 different arrays, then populate listactivity with array of column 1, enable filter & on clicked event I want to raise alert which should show Text clicked in tilte & desc from 2nd array as msg body based on position. But here is problem if using filter index becomes reinitialize :-(, and there didnot find another way to get text of that row. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Names)); getListView().setTextFilterEnabled(true); } public void onListItemClick(ListView parent, View v, int position, long id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle(Names[position]); builder.setMessage(description[position] + " -> " + position ); builder.setPositiveButton("ok", null); builder.show(); } <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> its not picking right item from position if filter used :-(, plz guide Can you share source code of this Method B Here I tried to generate list row from XML , but giving error that 1.5 jar file didnot allow modification :-( public View getView(int position, View convertView, ViewGroup parent) { /* ViewInflate inflater=context.getViewInflate(); View row=inflater.inflate(R.layout.row, null, null); */ View row = (View) convertView; if (row==null) { LayoutInflater inflater=context.getLayoutInflater(); // LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.row,null); } TextView label=(TextView)row.findViewById(R.id.label); label.setText(items[position]); TextView description=(TextView)row.findViewById(R.id.description); description.setText(items[position]); // ImageView icon=(ImageView)row.findViewById(R.id.icon); // icon.setImageResource(R.drawable.delete); return(row); } Plz suggest what is a right way to acconplish this, so app can show desc of item , has filter too. Plz share If you have any shouce code for this

    Read the article

  • NetworkOnMainThread exception occuring

    - by Akshat
    I got a code from Android Hive to parse JSON data from url. Then I am trying to implement the same code on Rotten Tomatoes Upcoming Movies Api. I have implemented the same code with almost modifying all the xml files according to my needs. But the problem is when I am trying to run the code, its showing NetworkOnMainThread Exception. This is my code.. public class Upcoming extends ListActivity { String url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=yvvgsv722gy2zkey3ebkda5t"; final String TAG_MOVIES = "movies"; final String TAG_ID = "id"; final String TAG_TITLE = "title"; final String TAG_YEAR = "year"; final String TAG_MPAA_RATING = "mpaa_rating"; final String TAG_RUNTIME = "runtime"; final String TAG_RELEASE_DATES = "release_dates"; final String TAG_RATINGS = "ratings"; final String TAG_CRITIC_RATING = "critics_ratings"; final String TAG_AUDIENCE_RATING = "audience_ratings"; final String TAG_SYNOPSIS = "synopsis"; final String TAG_POSTERS = "posters"; JSONArray upcomings = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upcoming_list); ArrayList<HashMap<String, String>> UpcomingList = new ArrayList<HashMap<String, String>>(); // Creating JSON Parser instance JSONParser jParser = new JSONParser(); // getting JSON string from URL JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of Contacts upcomings = json.getJSONArray(TAG_MOVIES); // looping through All Contacts for(int i = 0; i < upcomings.length(); i++){ JSONObject c = upcomings.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_ID); String title = c.getString(TAG_TITLE); String year = c.getString(TAG_YEAR); String mpaa_rating = c.getString(TAG_MPAA_RATING); String runtime = c.getString(TAG_RUNTIME); JSONObject release_dates = c.getJSONObject(TAG_RELEASE_DATES); JSONObject ratings = c.getJSONObject(TAG_RATINGS); String critic_rating = c.getString(TAG_CRITIC_RATING); String audience_rating = c.getString(TAG_AUDIENCE_RATING); String synopsis = c.getString(TAG_SYNOPSIS); JSONObject posters = c.getJSONObject(TAG_POSTERS); HashMap<String, String> map = new HashMap<String, String>(); map.put(TAG_TITLE, title); map.put(TAG_YEAR, year); map.put(TAG_CRITIC_RATING, critic_rating); map.put(TAG_AUDIENCE_RATING, audience_rating); UpcomingList.add(map); } } catch (JSONException e) { e.printStackTrace(); } ListAdapter adapter = new SimpleAdapter(this, UpcomingList, R.layout.activity_upcoming, new String[] { TAG_TITLE, TAG_YEAR, TAG_CRITIC_RATING, TAG_AUDIENCE_RATING }, new int[] { R.id.title, R.id.year, R.id.critic_rating, R.id.audience_rating }); setListAdapter(adapter); // selecting single ListView item ListView lv = getListView(); // Launching new screen on Selecting Single ListItem lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String name = ((TextView) view.findViewById(R.id.title)).getText().toString(); String cost = ((TextView) view.findViewById(R.id.year)).getText().toString(); String critic_rating = ((TextView) view.findViewById(R.id.critic_rating)).getText().toString(); String audience_rating = ((TextView) view.findViewById(R.id.audience_rating)).getText().toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), Upcoming.class); in.putExtra(TAG_TITLE, name); in.putExtra(TAG_YEAR, cost); in.putExtra(TAG_CRITIC_RATING, critic_rating); in.putExtra(TAG_AUDIENCE_RATING, audience_rating); startActivity(in); } }); } } Can anyone please help me with anything I am missing.? I am totally blind on it now. Thanx in advance.

    Read the article

  • Change ListView background - strage behaviour

    - by Beasly
    Hi again, I have a problem with changing the background of a view in a ListView. What I need: Change the background image of a row onClick() What actually happens: The background gets changed (selected) after pressing e.g. the first entry. But after scrolling down the 8th entry is selected too. Scroll back to the top the first isn't selected anymore. The second entry is selected now. Continue scrolling and it continues jumping... What i'm dong in the Code: I have channels, and onClick() I toggle an attribute of channel boolean selected and then I change the background. I'm doing this only onClick() thats why I don't get why it's actuelly happening on other entries too. One thing I notices is: It seems to be only the "drawing"-part because the item which get selected "by it self" has still the selected value on false I think it seems to have something to do with the reuse of the views in the custom ListAdapters getView(...) Code of onClick() in ListActivity: @Override protected ViewHolder createHolder(View v) { // createHolder will be called only as long, as the ListView is not // filled TextView title = (TextView) v .findViewById(R.id.tv_title_channel_list_adapter); TextView content = (TextView) v .findViewById(R.id.tv_content_channel_list_adapter); ImageView icon = (ImageView) v .findViewById(R.id.icon_channel_list_adapter); if (title == null || content == null || icon == null) { Log.e("ERROR on findViewById", "Couldn't find Title, Content or Icon"); } ViewHolder mvh = new MyViewHolder(title, content, icon); // We make the views become clickable // so, it is not necessary to use the android:clickable attribute in // XML v.setOnClickListener(new ChannelListAdapter.OnClickListener(mvh) { public void onClick(View v, ViewHolder viewHolder) { // we toggle the enabled state and also switch the the // background MyViewHolder mvh = (MyViewHolder) viewHolder; Channel ch = (Channel) mvh.data; ch.setSelected(!ch.getSelected()); // toggle if (ch.getSelected()) { v.setBackgroundResource(R.drawable.row_blue_selected); } else { v.setBackgroundResource(R.drawable.row_blue); } // TESTING Log.d("onClick() Channel", "onClick() Channel: " + ch.getTitle() + " selected: " + ch.getSelected()); } }); return mvh; } Code of getView(...): @Override public View getView(int position, View view, ViewGroup parent) { ViewHolder holder; // When view is not null, we can reuse it directly, there is no need // to reinflate it. // We only inflate a new View when the view supplied by ListView is // null. if (view == null) { view = mInflater.inflate(mViewId, null); // call own implementation holder = createHolder(view); // TEST // we set the holder as tag view.setTag(holder); } else { // get holder back...much faster than inflate holder = (ViewHolder) view.getTag(); } // we must update the object's reference holder.data = getItem(position); // call the own implementation bindHolder(holder); return view; } I really would appreciate any idea how to solve this! :) If more information is needed please tell me. Thanks in advance!

    Read the article

  • RadioGroup onCheckedChanged function won't fire

    - by user1758088
    First time/long time. My app keeps track of restaurant servers' shift sales to help them budget. In the activity that displays past shifts, I've created a RadioGroup under the ListView so the server can choose lunch, dinner, or both. I've implemented RadioGroup.onCheckedChangeListener, but onCheckChanged never gets called. I also tried an anonymous inner class as listener, same result. I tried to copy/modify code from this answer: http://stackoverflow.com/a/9595528 ...but when I added the @Override to the callback function, the Eclipse compiler gave me an error (not warning) that the method must override a superclass, and the quick fix was to remove the override. I'm pretty sure the signatures are correct, as they were made with Eclipse's autocomplete and implement methods facilities. I then followed instructions to move my java compiler from 1.5 to 1.6, and none of the above listed behavior seemed to change. Here's the code I thing is relavent: public class DataActivity extends ListActivity implements OnCheckedChangeListener{ RadioButton rbBoth; RadioButton rbDinnerOnly; RadioButton rbLunchOnly; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.database); ... final RadioGroup rgGroup = (RadioGroup)findViewById(R.id.DataRadioGroup); rbBoth = (RadioButton)findViewById(R.id.RadioBoth); rbDinnerOnly = (RadioButton)findViewById(R.id.RadioDinnerOnly); rbLunchOnly = (RadioButton)findViewById(R.id.RadioLunchOnly); rgGroup.setOnCheckedChangeListener(this); populateAllShifts(); } ... public void onCheckedChanged(RadioGroup group, int checkedId) { rbLunchOnly.setText("Click!"); Toast.makeText(getApplicationContext(), "Lunch Only", Toast.LENGTH_LONG).show(); if(group.getCheckedRadioButtonId() == R.id.RadioBoth){ populateAllShifts(); return; } if(group.getCheckedRadioButtonId() == R.id.RadioLunchOnly){ populatLunchShifts(); return; } if(group.getCheckedRadioButtonId() == R.id.RadioDinnerOnly){ populateDinnerShifts(); return; } } There is a ListView in this class with a custom adapter, but if my understanding and my XML are correct, the RadioGroup should be outside of the list: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/llDataLayout" android:weightSum="5" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ListView android:layout_weight="4" android:layout_width="fill_parent" android:id="@android:id/list" android:layout_height="wrap_content"></ListView> <RadioGroup android:layout_weight="1" android:id="@+id/DataRadioGroup" android:orientation="horizontal" android:layout_height="wrap_content" android:layout_width="fill_parent"> <RadioButton android:text="Lunch and Dinner" android:textSize="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/RadioBoth"/> <RadioButton android:text="Dinner Only" android:textSize="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/RadioDinnerOnly"/> <RadioButton android:text="Lunch Only" android:textSize="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/RadioLunchOnly"/> </RadioGroup> </LinearLayout> Any ideas out there?

    Read the article

  • click buttons error

    - by sara
    I will retrieve student information (id -number- name) from a database (MySQL) as a list view, each student have 2 buttons (delete - alert ) and radio buttons Every thing is ok, but how can I make an onClickListener, for example for the delete button because I try lots of examples, I heard that I can use (custom list or get view or direct onClickListener as in my code (but it is not working ) or Simple Cursor Adapter) I do not know what to use, I looked around for examples that can help me, but in my case but I did not find any so I hope this be reference for anyone have the same problem. this is my code which I use direct onClick with Simple Adapter public class ManageSection extends ListActivity { //ProgresogressDialog pDialog; private ProgressDialog pDialog; // Creating JSON Parser object // Creating JSON Parser object JSONParser jParser = new JSONParser(); //class boolean x =true; Button delete; ArrayList<HashMap<String, String>> studentList; //url to get all products list private static String url_all_student = "http://10.0.2.2/SmsPhp/view_student_info.php"; String cl; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_student = "student"; private static final String TAG_StudentID = "StudentID"; private static final String TAG_StudentNo = "StudentNo"; private static final String TAG_FullName = "FullName"; private static final String TAG_Avatar="Avatar"; HashMap<String, String> selected_student; // course JSONArray JSONArray student = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.manage_section); studentList = new ArrayList<HashMap<String, String>>(); ListView list1 = getListView(); list1.setAdapter(getListAdapter()); list1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) { selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity. delete =(Button)view.findViewById(R.id.DeleteStudent); cl=selected_student.get(TAG_StudentID); Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show(); delete.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d("id: ",cl); Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show(); } }); } }); new LoadAllstudent().execute(); } /** * Background Async Task to Load all student by making HTTP Request * */ class LoadAllstudent extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(ManageSection.this); pDialog.setMessage("Loading student. Please wait..."); pDialog.setIndeterminate(false); } /** * getting All student from u r l * */ @Override protected String doInBackground(String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_student, "GET", params); // Check your log cat for JSON response Log.d("All student : ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // student found // Getting Array of course student = json.getJSONArray(TAG_student); // looping through All courses for (int i = 0; i < student.length(); i++)//course JSONArray { JSONObject c = student.getJSONObject(i); // read first // Storing each json item in variable String StudentID = c.getString(TAG_StudentID); String StudentNo = c.getString(TAG_StudentNo); String FullName = c.getString(TAG_FullName); // String Avatar = c.getString(TAG_Avatar); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_StudentID, StudentID); map.put(TAG_StudentNo, StudentNo); map.put(TAG_FullName, FullName); // adding HashList to ArrayList studentList.add(map); } } else { x=false; } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); if (x==false) Toast.makeText(getBaseContext(),"no student" ,Toast.LENGTH_LONG).show(); ListAdapter adapter = new SimpleAdapter( ManageSection.this, studentList, R.layout.list_student, new String[] { TAG_StudentID, TAG_StudentNo,TAG_FullName}, new int[] { R.id.StudentID, R.id.StudentNo,R.id.FullName}); setListAdapter(adapter); // Updating parsed JSON data into ListView } } } So what do you think, why doesn't the delete button work? There is no error in my log cat. What is the alternative way ?.. what should I do ?

    Read the article

  • How to obtain listview information without refreshing the page?

    - by user1808098
    I am currently developing an Android Application for my Final Year Project. But to be honest I do not have any basic knowledges and everything started from scratch and referring to online tutorials a lot. Here is my question, I was trying to retrieve data from listview activity. There are two listview in my page using button. I was able to display the first listview but when it get data for the second listview, the data for first listview is disappeared because the page is refreshed, vice versa. What code should I modified to get both the data in the page? (Database not implemented yet) Please help, thanks a lot. Below are my codings. Codings for XML. <!-- Location --> <TextView android:id="@+id/TextViewLocation" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:layout_marginBottom="10dip" android:text="Location Information" android:gravity="center" android:textSize="15dip" android:textColor="#025f7c"/> <!-- Condition Label --> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#372c24" android:text="Traffic Condition"/> <Button android:id="@+id/inputListView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:layout_marginBottom="10dip" android:text="choose one..."/> <!-- Comment Label --> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#372c24" android:text="What's Happening?"/> <Button android:id="@+id/inputListView2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:layout_marginBottom="10dip" android:text="choose one..."/> <!-- Suggestion Label --> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#372c24" android:text="Comments / Suggestion"/> <EditText android:layout_width="fill_parent" android:layout_height="80dp" android:layout_marginTop="5dip" android:layout_marginBottom="10dip" android:singleLine="true"/> <!-- Image button --> <Button android:id="@+id/btnImage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:text="Upload Image"/> <!-- Report button --> <Button android:id="@+id/btnReportCheckin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:text="Report"/> <!-- Link to Logout --> <TextView android:id="@+id/linkLogout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:layout_marginBottom="40dip" android:text="Log Out" android:gravity="center" android:textSize="20dip" android:textColor="#025f7c"/> </LinearLayout> <!-- Check or Report Form Ends --> Codings for Activity Class public class CheckinActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set View to checkin.xml setContentView(R.layout.checkin); /* TextView LocationView = (TextView) findViewById(R.id.TextViewLocation); Intent h = getIntent(); // getting attached intent data String address = h.getStringExtra("address"); // displaying selected product name LocationView.setText(address); */ Button ListViewScreen = (Button) findViewById(R.id.inputListView); //Listening to Button ListViewScreen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Switching to ListView Screen Intent i = new Intent(getApplicationContext(), ListViewActivity.class); startActivity(i); } } ); Button SelectedView = (Button) findViewById(R.id.inputListView); Intent i = getIntent(); // getting attached intent data String product = i.getStringExtra("product"); // displaying selected product name SelectedView.setText(product); Button ListView2Screen = (Button) findViewById(R.id.inputListView2); //Listening to Button ListView2Screen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Switching to ListView Screen Intent j = new Intent(getApplicationContext(), ListView2Activity.class); startActivity(j); } } ); Button SelectedView2 = (Button) findViewById(R.id.inputListView2); Intent j = getIntent(); // getting attached intent data String product2 = j.getStringExtra("product2"); // displaying selected product name SelectedView2.setText(product2); TextView Logout = (TextView) findViewById(R.id.linkLogout); // Listening to Log out Logout.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // Closing menu screen // Switching to Login Screen/closing register screen finish(); } }); } } Coding for listview class public class ListViewActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // storing string resources into Array String[] traffic_condition = getResources().getStringArray(R.array.traffic_condition); // Binding resources Array to ListAdapter this.setListAdapter(new ArrayAdapter<String>(this, R.layout.listitem, R.id.listViewLayout, traffic_condition)); ListView lv = getListView(); // listening to single list item on click lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // selected item String product = ((TextView) view).getText().toString(); // Launching new Activity on selecting single List Item Intent i = new Intent(getApplicationContext(), CheckinActivity.class); // sending data to new activity i.putExtra("product", product); startActivity(i); } }); } } Hope I made myself clear, I can provide a screen shot of my apps if it is required, thanks!

    Read the article

  • Android strange behavior with listview and custom cursor adapter

    - by Michael Little
    I have a problem with a list view and a custom cursor adapter and I just can't seem to figure out what is wrong with my code. Basically, in my activity I call initalize() that does a bunch of stuff to handle getting the proper data and initializing the listview. On first run of the activity you can see from the images that one of the items is missing from the list. If I go to another activity and go back to this activity the item that was missing shows up. I believe it has something to do with setContentView(R.layout.parent). If I move that to my initialize() then the item never shows up even when returning from another activity. So, for some reason, returning from another activity bypasses setContentView(R.layout.parent) and everything works fine. I know it's impossible for me to bypass setContentView(R.layout.parent) so I need to figure out what the problem is. Also, I did not include the layout because it is nothing more then two textviews. Also, the images I have attached do not show that the missing item is the last one on the list. Custom Cursor Adapter: public class CustomCursorAdapter extends SimpleCursorAdapter { private Context context; private int layout; public CustomCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context; this.layout = layout; } public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(layout, parent, false); return view; } @Override public void bindView(View v, Context context, Cursor c) { if (c.getColumnName(0).matches("section")){ int nameCol = c.getColumnIndex("section"); String section = c.getString(nameCol); TextView section_text = (TextView) v.findViewById(R.id.text1); if ((section.length() > 0)) { section_text.setText(section); } else { //so we don't have an empty spot section_text.setText(""); section_text.setVisibility(2); section_text.setHeight(1); } } else if (c.getColumnName(0).matches("code")) { int nameCol = c.getColumnIndex("code"); String mCode = c.getString(nameCol); TextView code_text = (TextView) v.findViewById(R.id.text1); if (code_text != null) { int i = 167; byte[] data = {(byte) i}; String strSymbol = EncodingUtils.getString(data, "windows-1252"); mCode = strSymbol + " " + mCode; code_text.setText(mCode); code_text.setSingleLine(); } } if (c.getColumnName(1).matches("title")){ int nameCol = c.getColumnIndex("title"); String mTitle = c.getString(nameCol); TextView title_text = (TextView) v.findViewById(R.id.text2); if (title_text != null) { title_text.setText(mTitle); } } else if (c.getColumnName(1).matches("excerpt")) { int nameCol = c.getColumnIndex("excerpt"); String mExcerpt = c.getString(nameCol); TextView excerpt_text = (TextView) v.findViewById(R.id.text2); if (excerpt_text != null) { excerpt_text.setText(mExcerpt); excerpt_text.setSingleLine(); } } } The Activity: public class parent extends ListActivity { private static String[] TITLE_FROM = { SECTION, TITLE, _ID, }; private static String[] CODE_FROM = { CODE, EXCERPT, _ID, }; private static String ORDER_BY = _ID + " ASC"; private static int[] TO = { R.id.text1, R.id.text2, }; String breadcrumb = null; private MyData data; private SQLiteDatabase db; CharSequence parent_id = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); data = new MyData(this); db = data.getReadableDatabase(); setContentView(R.layout.parent); initialize(); } public void initialize() { breadcrumb = null; Bundle bun = getIntent().getExtras(); TextView tvBreadCrumb; tvBreadCrumb = (TextView)findViewById(R.id.breadcrumb); if (bun == null) { //this is the first run tvBreadCrumb.setText(null); tvBreadCrumb.setHeight(0); parent_id = "0"; try { Cursor cursor = getData(parent_id); showSectionData(cursor); } finally { data.close(); } } else { CharSequence state = bun.getString("state"); breadcrumb = bun.getString("breadcrumb"); tvBreadCrumb.setText(breadcrumb); CharSequence code = bun.getString("code"); parent_id = code; if (state.equals("chapter")) { try { Cursor cursor = getData(parent_id); showSectionData(cursor); } finally { data.close(); } } else if (state.equals("code")) { try { Cursor cursor = getCodeData(parent_id); showCodeData(cursor); } finally { data.close(); } } } } @Override public void onStart() { //initialize(); super.onResume(); } @Override public void onResume() { initialize(); super.onResume(); } private Cursor getData(CharSequence parent_id) { Cursor cTitles = db.query(TITLES_TABLE_NAME, TITLE_FROM, "parent_id = " + parent_id, null, null, null, ORDER_BY); Cursor cCodes = db.query(CODES_TABLE_NAME, CODE_FROM, "parent_id = " + parent_id, null, null, null, ORDER_BY); Cursor[] c = {cTitles, cCodes}; Cursor cursor = new MergeCursor(c); startManagingCursor(cursor); return cursor; } private Cursor getCodeData(CharSequence parent_id2) { Bundle bun = getIntent().getExtras(); CharSequence intent = bun.getString("intent"); CharSequence searchtype = bun.getString("searchtype"); //SQLiteDatabase db = data.getReadableDatabase(); if (intent != null) { String sWhere = null; if(searchtype.equals("code")) { sWhere = "code LIKE '%"+parent_id2+"%'"; } else if(searchtype.equals("within")){ sWhere = "definition LIKE '%"+parent_id2+"%'"; } //This is a search request Cursor cursor = db.query(CODES_TABLE_NAME, CODE_FROM, sWhere, null, null, null, ORDER_BY); startManagingCursor(cursor); return cursor; } else { Cursor cursor = db.query(CODES_TABLE_NAME, CODE_FROM, "parent_id = "+ parent_id2, null, null, null, ORDER_BY); startManagingCursor(cursor); return cursor; } } private void showSectionData(Cursor cursor) { CustomCursorAdapter adapter= new CustomCursorAdapter(this, R.layout.item, cursor, TITLE_FROM, TO); setListAdapter(adapter); } private void showCodeData(Cursor cursor) { CustomCursorAdapter adapter = new CustomCursorAdapter(this, R.layout.item, cursor, CODE_FROM, TO); setListAdapter(adapter); Bundle bun = getIntent().getExtras(); CharSequence intent = bun.getString("intent"); if (intent != null) { Cursor cursor1 = ((CursorAdapter)getListAdapter()).getCursor(); startManagingCursor(cursor1); TextView tvBreadCrumb; tvBreadCrumb = (TextView)findViewById(R.id.breadcrumb); tvBreadCrumb.setText(cursor1.getCount() + " Records Found"); //cursor1.close(); //mdl } }

    Read the article

  • Android App crashing on Back Button (performResumeActivity)

    - by Rutger
    My App consists of 2 Activities at the moment. . the MAIN activity with a Gallery View . a FriendsListActivity with a ListView When the user moves away from the FriendsListActivity with the back button, and returns to the MAIN activity the following error keeps popping up in debug mode. DalvikVM[localhost:8676] Thread [<1 main] (Suspended (exception RuntimeException)) ActivityThread.performResumeActivity(IBinder, boolean) line: 2095 ActivityThread.handleResumeActivity(IBinder, boolean, boolean) line: 2110 BinderProxy(ActivityThread$H).handleMessage(Message) line: 954 ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 123 ActivityThread.main(String[]) line: 3647 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 507 ZygoteInit$MethodAndArgsCaller.run() line: 839 ZygoteInit.main(String[]) line: 597 NativeStart.main(String[]) line: not available [native method] Thread [<8 Binder Thread #2] (Running) Thread [<7 Binder Thread #1] (Running) With the LogCat 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): FATAL EXCEPTION: main 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): java.lang.RuntimeException: Unable to resume activity {com.package.MAIN/com.package.MAIN.MAIN}: java.lang.NullPointerException 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2095) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2110) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:954) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.os.Handler.dispatchMessage(Handler.java:99) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.os.Looper.loop(Looper.java:123) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.main(ActivityThread.java:3647) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at java.lang.reflect.Method.invokeNative(Native Method) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at java.lang.reflect.Method.invoke(Method.java:507) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at dalvik.system.NativeStart.main(Native Method) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): Caused by: java.lang.NullPointerException 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.package.MAIN.MAIN.onResume(MAIN.java:91) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.Activity.performResume(Activity.java:3833) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2085) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): ... 10 more Further info in the Variables panel states: this: ActivityThread e: NullPointerException cause: NullPointerException detailMessage: null stackTrace: null r: ActivityThread$ActivityClientRecord activity: MAIN detailMessage after one Eclipse Resume: Unable to resume activity (MAIN) The code from the FriendsListActivity looks like this public class FriendsListActivity extends ListActivity { // =========================================================== // Fields // =========================================================== private ArrayList<Friend> friends = new ArrayList<Friend>(); private FriendsArrayAdapter friendsArrayAdapter; private ListView listView; // =========================================================== // onCreate // =========================================================== @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.friends_list); registerForContextMenu(getListView()); setButtonNewFriendClickListener(); } public void generateFriendsList() { FriendsService fs = new FriendsService(this); friends = fs.getFriendsList(); listView = (ListView) findViewById(android.R.id.list); friendsArrayAdapter = new FriendsArrayAdapter( this, R.layout.friend_list_item, friends); listView.setAdapter(friendsArrayAdapter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.friends_context_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); FriendsService fs = new FriendsService(this); Friend f = new Friend(); f = friends.get(info.position); switch (item.getItemId()) { case R.id.edit: Intent i = new Intent(this, FriendEditActivity.class); i.putExtra("userid", f.userId); startActivity(i); return true; case R.id.delete: fs.deleteFriend(f.userId); generateFriendsList(); return true; default: return super.onContextItemSelected(item); } } // =========================================================== // onPause // =========================================================== protected void onPause() { super.onPause(); finish(); } // =========================================================== // onResume // =========================================================== protected void onResume() { super.onResume(); generateFriendsList(); } // =========================================================== // onStop // =========================================================== protected void onStop() { super.onStop(); } // =========================================================== // onDestroy // =========================================================== @Override protected void onDestroy() { super.onDestroy(); } // =========================================================== // Activity methods // =========================================================== private void setButtonNewFriendClickListener() { Button clickButton = (Button)findViewById(R.id.button_add_friend); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(v.getContext(), FriendNewActivity.class); startActivity(i); } }); } The AndroidManifest looks like this <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.package.mypackage"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="com.package.mypackage.mypackage" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".FriendsListActivity"></activity> <activity android:name=".FriendEditActivity"></activity> <activity android:name=".FriendNewActivity"></activity> <activity android:name=".TakePictureActivity"></activity> <activity android:name=".FriendsService"></activity> <activity android:name=".MyService"></activity> </application> <uses-sdk android:minSdkVersion="9" /> The MAIN activity looks like this: package com.package.mypackage; import java.util.ArrayList; import com.package.domain.Domain; import com.package.service.MyService; import com.package.viewadapter.myImageAdapter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.Gallery; import android.widget.Toast; public class myActivity extends Activity { // =========================================================== // Fields // =========================================================== private MyImageAdapter myImageAdapter; private ArrayList<Domain> domain = new ArrayList<Domain>(); // =========================================================== // onCreate // =========================================================== @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); /* Set Buttons to listen for any click event. */ setButtonFriendsClickListener(); setButtonCameraClickListener(); setButtonPreferencesClickListener(); } // =========================================================== // onStart // =========================================================== @Override public void onStart() { super.onStart(); /* Find the gallery defined in the main.xml */ Gallery g = (Gallery) findViewById(R.id.gallery); /* Show a Toast message when image is clicked */ g.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { MyImageAdapter image_ID = new MyImageAdapter(myActivity.this, position, null); if (image_ID.getItemId(position) == 0) { Toast test_toast = Toast.makeText(myActivity.this, "This is the New Image click", Toast.LENGTH_SHORT); test_toast.show(); } else { Toast test_toast = Toast.makeText(myActivity.this, "The clicked image has image number " + image_ID.getItemId(position) + " in the imageadapter.", Toast.LENGTH_SHORT); test_toast.show(); } } }); g.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { MyImageAdapter image_ID = new MyImageAdapter(myActivity.this, position, null); Toast test_toast = Toast.makeText(myActivity.this, "The long clicked image has image number " + image_ID.getItemId(position) + " in the imageadapter.", Toast.LENGTH_SHORT); test_toast.show(); return true; } }); } // =========================================================== // onPause // =========================================================== protected void onPause() { super.onPause(); } // =========================================================== // onResume // =========================================================== protected void onResume() { super.onResume(); generateMyGallery(); } // =========================================================== // onStop // =========================================================== protected void onStop() { super.onStop(); } // =========================================================== // onDestroy // Is also called when user changes from horizontal // to vertical orientation and back // =========================================================== @Override protected void onDestroy() { super.onDestroy(); } // =========================================================== // Save and Restore UI states // =========================================================== @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } // =========================================================== // Main Activity methods // =========================================================== public void generateMyGallery() { MyService cs = new MyService(this); domain = cs.getDomainList(); // Add the new_image drawable to the ArrayList Domain d = new Domain(); d.photoLocation = "drawable"; d.photoName = "new_image"; d.extra1 = "no_text"; d.extra2 = "no_text"; domain.add(0, d); myImageAdapter = new MyImageAdapter(this, R.layout.text_overlay_image_view, domain); /* Find the gallery defined in the main.xml */ Gallery g = (Gallery) findViewById(R.id.gallery); g.setSpacing(10); /* Apply a new (custom) ImageAdapter to it. */ g.setAdapter(myImageAdapter); g.setSelection(1); } private void setButtonFriendsClickListener() { Button clickButton = (Button)findViewById(R.id.button_friends_list); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setContentView(R.layout.friends_list); Intent myIntent = new Intent(v.getContext(), FriendsListActivity.class); startActivity(myIntent); } }); } private void setButtonCameraClickListener() { Button clickButton = (Button)findViewById(R.id.button_take_picture); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setContentView(R.layout.take_picture); Intent myIntent = new Intent(v.getContext(), TakePictureActivity.class); startActivity(myIntent); } }); } private void setButtonPreferencesClickListener() { Button clickButton = (Button)findViewById(R.id.button_preferences); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent myIntent = new Intent(v.getContext(), MyPreferencesActivity.class); startActivity(myIntent); } }); } }; Anyone has an idea why the App crashes. Any help is much appreciated. I did find out that, when I finish() the MAIN activity when I start the FriendListActivity and restart the MAIN activity when closing the FriendListActivity, that the crash does not occur. However, this basically restarts the App and that is not the intention. Thanks all, I got the problem solved. This is what I did. . When moving all gallery related actions to the onCreate, the creash didn't happen anymore. But then after returning to the MAIN activity, the activity wasn't shown. . I then moved all the onCreate (except the super), the generateGallery, and the onStart() to the onResume. Now it works fine!

    Read the article

  • Database Tutorial: The method open() is undefined for the type MainActivity.DBAdapter

    - by user2203633
    I am trying to do this database tutorial on SQLite Eclipse: https://www.youtube.com/watch?v=j-IV87qQ00M But I get a few errors at the end.. at db.ppen(); i get error: The method open() is undefined for the type MainActivity.DBAdapter and similar for insert record and close. MainActivity: package com.example.studentdatabase; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { /** Called when the activity is first created. */ //DBAdapter db = new DBAdapter(this); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button addBtn = (Button)findViewById(R.id.add); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, addassignment.class); startActivity(i); } }); try { String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB"; File f = new File(destPath); if (!f.exists()) { CopyDB( getBaseContext().getAssets().open("mydb"), new FileOutputStream(destPath)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } DBAdapter db = new DBAdapter(); //---add an assignment--- db.open(); long id = db.insertRecord("Hello World", "2/18/2012", "DPR 224", "First Android Project"); id = db.insertRecord("Workbook Exercises", "3/1/2012", "MAT 100", "Do odd numbers"); db.close(); //---get all Records--- /* db.open(); Cursor c = db.getAllRecords(); if (c.moveToFirst()) { do { DisplayRecord(c); } while (c.moveToNext()); } db.close(); */ /* //---get a Record--- db.open(); Cursor c = db.getRecord(2); if (c.moveToFirst()) DisplayRecord(c); else Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG).show(); db.close(); */ //---update Record--- /* db.open(); if (db.updateRecord(1, "Hello Android", "2/19/2012", "DPR 224", "First Android Project")) Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show(); db.close(); */ /* //---delete a Record--- db.open(); if (db.deleteRecord(1)) Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show(); db.close(); */ } private class DBAdapter extends BaseAdapter { private LayoutInflater mInflater; //private ArrayList<> @Override public int getCount() { return 0; } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { return null; } } public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException { //---copy 1K bytes at a time--- byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); } public void DisplayRecord(Cursor c) { Toast.makeText(this, "id: " + c.getString(0) + "\n" + "Title: " + c.getString(1) + "\n" + "Due Date: " + c.getString(2), Toast.LENGTH_SHORT).show(); } public void addAssignment(View view) { Intent i = new Intent("com.pinchtapzoom.addassignment"); startActivity(i); Log.d("TAG", "Clicked"); } } DBAdapter code: package com.example.studentdatabase; public class DBAdapter { public static final String KEY_ROWID = "id"; public static final String KEY_TITLE = "title"; public static final String KEY_DUEDATE = "duedate"; public static final String KEY_COURSE = "course"; public static final String KEY_NOTES = "notes"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "AssignmentsDB"; private static final String DATABASE_TABLE = "assignments"; private static final int DATABASE_VERSION = 2; private static final String DATABASE_CREATE = "create table if not exists assignments (id integer primary key autoincrement, " + "title VARCHAR not null, duedate date, course VARCHAR, notes VARCHAR );"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(DATABASE_CREATE); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a record into the database--- public long insertRecord(String title, String duedate, String course, String notes) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_DUEDATE, duedate); initialValues.put(KEY_COURSE, course); initialValues.put(KEY_NOTES, notes); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular record--- public boolean deleteContact(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the records--- public Cursor getAllRecords() { return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, null, null, null, null, null); } //---retrieves a particular record--- public Cursor getRecord(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a record--- public boolean updateRecord(long rowId, String title, String duedate, String course, String notes) { ContentValues args = new ContentValues(); args.put(KEY_TITLE, title); args.put(KEY_DUEDATE, duedate); args.put(KEY_COURSE, course); args.put(KEY_NOTES, notes); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } addassignment code: package com.example.studentdatabase; public class addassignment extends Activity { DBAdapter db = new DBAdapter(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add); } public void addAssignment(View v) { Log.d("test", "adding"); //get data from form EditText nameTxt = (EditText)findViewById(R.id.editTitle); EditText dateTxt = (EditText)findViewById(R.id.editDuedate); EditText courseTxt = (EditText)findViewById(R.id.editCourse); EditText notesTxt = (EditText)findViewById(R.id.editNotes); db.open(); long id = db.insertRecord(nameTxt.getText().toString(), dateTxt.getText().toString(), courseTxt.getText().toString(), notesTxt.getText().toString()); db.close(); nameTxt.setText(""); dateTxt.setText(""); courseTxt.setText(""); notesTxt.setText(""); Toast.makeText(addassignment.this,"Assignment Added", Toast.LENGTH_LONG).show(); } public void viewAssignments(View v) { Intent i = new Intent(this, MainActivity.class); startActivity(i); } } What is wrong here? Thanks in advance.

    Read the article

< Previous Page | 2 3 4 5 6