[Q] Updating Image in list adapter - Java for Android App Development

I have the following code that successfully updates parts of my layout from values in an SQLite table
Code:
helper = new TaskDBHelper(Overview.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.sum_view,
cursor,
new String[]{TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
new int[]{R.id.taskTextView, R.id.txtData, R.id.txtIP, R.id.txtStatus},
0
);
this.setListAdapter(listAdapter);
I am trying to set an image based on the value of one of the fields. The status column will return 1, 2 or 3 and I have 3 images that correspond, to display. Can anyone help me and explain how I can fit this into what I am already doing please?

calnaughtonjnr said:
I have the following code that successfully updates parts of my layout from values in an SQLite table
Code:
helper = new TaskDBHelper(Overview.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.sum_view,
cursor,
new String[]{TaskContract.Columns.TASK, TaskContract.Columns.BAL, TaskContract.Columns.IP, TaskContract.Columns.STATUS},
new int[]{R.id.taskTextView, R.id.txtData, R.id.txtIP, R.id.txtStatus},
0
);
this.setListAdapter(listAdapter);
I am trying to set an image based on the value of one of the fields. The status column will return 1, 2 or 3 and I have 3 images that correspond, to display. Can anyone help me and explain how I can fit this into what I am already doing please?
Click to expand...
Click to collapse
can u explain more .
but what i understand is , u need to implement custom adapter so it will be good to set

hisee said:
can u explain more .
but what i understand is , u need to implement custom adapter so it will be good to set
Click to expand...
Click to collapse
The code I used works great and one of the textboxes it fills will be a number. 1, 2 or 3. I want to display an image in the row also. I have 3 images in my drawables folder (one.png, two.png, three.png). I want to display the correct one depending on the number that was returned to R.id.txtStatus

What i would do is as follows:
Create a new class named Item for example which contains five attributes: four strings which contain the texts for the four textviews and one int where you save the image number.
Then you need a custom implementation of ArrayAdapter, using an arraylist of Items (or however you name your holder class).
In the adapter you can then assign the textviews their corresponding contents by using item.getStatus etc and you check the int that contains the image number and assign the imageview the correct image.
Edit:
Here is the implementation i am using in my app with "Row" as my custom holder class, i don't use an imageview but you can easily add this:
package com.masrepus.vplanapp;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by samuel on 27.07.14.
*/
public class MySimpleArrayAdapter extends ArrayAdapter implements Serializable {
private final ArrayList<Row> list;
/**
* Constructor for the custom arrayadapter
*
* @param activity used for method-calls that require a context parameter
* @param list a Row ArrayList that has to be parsed into a listview
*/
public MySimpleArrayAdapter(Activity activity, ArrayList<Row> list) {
super(activity, R.layout.vplan_list, list);
this.list = list;
}
/**
* Puts the klasse, stunde and status attributes of a row object into the right textviews in a listview item
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder view;
if (rowView == null) {
//get a new instance of the row layout view
rowView = View.inflate(getContext(), R.layout.vplanlist_element, null);
//hold the view objects in an object, that way they don't need to be "re- found"
view = new ViewHolder();
view.klasseView = (TextView) rowView.findViewById(R.id.grade);
view.stundeView = (TextView) rowView.findViewById(R.id.stunde);
view.statusView = (TextView) rowView.findViewById(R.id.status);
rowView.setTag(view);
} else {
view = (ViewHolder) rowView.getTag();
}
//put data to the views
Row item = list.get(position);
view.klasseView.setText(item.getKlasse());
view.stundeView.setText(item.getStunde());
view.statusView.setText(item.getStatus());
return rowView;
}
/**
* Used to distribute klasse, stunde, status to the right textviews
*/
protected static class ViewHolder {
protected TextView klasseView;
protected TextView stundeView;
protected TextView statusView;
}
}
Click to expand...
Click to collapse
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

Related

[Q] Making selected spinner items into array references

Hello, i'm making an app, and i need for the app to populate a list view, i've got this to work, the listview is populated by arrays in the values resources folder. the name for this array is defined by the selected items of two spinners combined with a "_" in the middle. How do i set this custom array ID?
here is my current main activity code: (i've used a existing array id to test that it works "tener_future")
Code:
package org.townsend.spanish.donate;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
public class Main extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View conjugateButton = findViewById(R.id.conjugate_button);
conjugateButton.setOnClickListener(this);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void verbAndTense() {
Resources res = getResources();
String[] listItems = res.getStringArray(R.array.tener_conditional);
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.conjugate_button:
verbAndTense();
break;
}
}
}
If I understand your question correctly, you are trying to get a reference to an Id stored in the R class, but which reference you need changes at runtime?
If that is the case, I think you may want to program a custom utility/method that can return the correct R reference for you. R is just a static generated class of ints, so it cannot evaluate something like R.id.dynamicterm1_dynamicterm2 where dynamicterm1 and dynamicterm2 change at runtime.
One way to do this might be a static util class like this:
Code:
package org.townsend.spanish.donate.util;
import org.townsend.spanish.donate.R;
public class ReferenceFinder
{
public static int find(String prefixName, String suffixName)
{
int returnValue = -1; // -1 indicates an error
if ( prefixName.equals("verb") && suffixName.equals("tense") )
{
returnValue = R.id.verb_tense;
}
else if( prefixName.equals("adj") && suffixName.equals("tense") )
{
returnValue = R.id.adjective_tense;
}
return returnValue;
}
Then you would call it like so:
Code:
Resources res = getResources();
int resourceID = ReferenceFinder.find("verb", "tense") ;
String[] listItems = res.getStringArray( resourceID );
I'm sure there are other ways to do this, but this is the first that came to mind. Hope that helps
would that mean that in the resource finder class that i'd have to define every possible outcome? because i'll have hundreds of outcomes once i have loaded the full list's and their outcome array's
and i think you have understood me correctly, basically it's and app (for spanish) where in one spinner you input a verb, in another you input a tense, and when you press a button it fills a list view with the 6 conjugations.
also it seems like in the second snippet of code i would have to actually set the "verb" and "tense" or could i put something dynamic like
Code:
verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem
Thanks for the help
hmm.... you might be able to do it via reflection actually, so that you wouldnt have to define each one.
I'm not 100% sure what the code would be but it would probably looks something like this:
Code:
String className= "com.example.myapp.R.id";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
int resourceID = f.getInt ( new Object() );
ok thanks i'm trying to get it to fit in, and i believe i have:
Code:
@SuppressWarnings({ "unchecked", "rawtypes" })
private void verbAndTense() {
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
verb_tenses.getSelectedItem();
String className= "org.townsend.spanish.donate.R.array";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
int resourceID = f.getInt ( new Object() );
String[] listItems = f.getStringArray( resourceID );
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));
}
where it says :
Code:
String[] listItems = f.getStringArray( resourceID );
is it correct to put the "f" in there? and second is asks to define "Field" what should i import it as? or do i need to declare it in another format?
should be something like
String[] listItems = getResources.getStringArray( resourceID );
resourceID is an int just like R.id.something_something
i changed getResources to res, since it was defined as:
Code:
Resources res = getResources();
however my problem with "Field" in the line:
Code:
Field f = cl.getDeclaredField ( fieldName );
still exists, it says "Field cannot be resolved to a type" and gives me a load of options including imports, making a new class, interface, enum or adding a parameter. what should i do? I've tried several of the imports but then other segments suchs as:
Code:
cl.getDeclaredField ( fieldName );
become errored.
Thank you for all your guys' help so far
If you're using the Field class and don't IMPORT it, well, that's a problem
You're best friend --> http://developer.android.com/reference/java/lang/reflect/Field.html
thank you yes my porblem was i was unsure which to import it as, although i was more confident about it being that one (i had about 8 options from eclipse)
previous code however has now given me errors, :
Code:
Class cl = [U]Class.forName( className )[/U];
this section saying : "Unhandled exception type ClassNotFoundException"
Code:
Field f = [U]cl.getDeclaredField ( fieldName )[/U];
this with: "Unhandled exception type NoSuchFieldException"
and
Code:
int resourceID = [U]f.getInt ( new Object() )[/U];
with: "Unhandled exception type IllegalAccessException"
I looked through the field resource page and the last one where it says this error occurs when the field is not accesible....:/
I then checked the Class resources page and the first one said that type ClassNotFoundException is thrown when requested class cannot be found, and i thought i had declarred it in the previous
Code:
String className= "org.townsend.spanish.donate.R.array";
I know that in the example you provided me you put R.id, howeve this is a value array so it should be array right?
and the second says its thrown when the field cannot be found.
Im guessing that means that the first one is affecting the rest? how could i correct this,
if you wish to see the entire void it is here
Code:
@SuppressWarnings({ "rawtypes", "unchecked" })
private void verbAndTense() {
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
verb_tenses.getSelectedItem();
String className= "org.townsend.spanish.donate.R.array";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
Resources res = getResources();
int resourceID = f.getInt ( new Object() );
String[] listItems = res.getStringArray( resourceID );
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));
}
Thank you
Yes, sorry it should be R.array or whatever
As for the "unhandled exceptions", if you use eclipse, just do the "recommended fix" and it will add a try/catch for you.
You may have to define some fields outside the try catch block and move some stuff around a bit after eclipse adds the try/catch.
Also, just as an aside, you may want to read a tutorial or two on reflection in Java so what I am saying doesnt sound as new/strange. Not required but it always helps to know a bit of reflection I think

[Q] How to add function to toggle switches?

I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Makbrar3215 said:
I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Click to expand...
Click to collapse
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Problem!
vijai2011 said:
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Click to expand...
Click to collapse
I did what you said. Yet I encountered a problem. Please see the attached screenshot.
When I hover over the X it says "Attribute name "public" associated with an element type "RadioButton" must be followed by the ' = '
character."
Where do I put the "="
Thanks by the way. You helped me out a lot!
you are mixing java with XML. Honestly, I suggest you start on a few beginner tutorials.
Just tell me what to do. I can't go through the guide. I need this app done by August 14.
Sent from my SGH-I337M using xda app-developers app
Bad Attitude to have. This isn't a "do my work for me" forum.
And like zalez was kind enough to point out, your putting java in xml. If you expect to make an app you need to read some beginner guides first.
you have almost a month to do it.
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Makbrar3215 said:
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Click to expand...
Click to collapse
http://developer.android.com/training/index.html
But you should probably start with generic Java 101 stuff
Set Switch status from incoming JSON data
Sorry to bump this thread after such a long time but I am facing a problem with switches myself and would appreciate some help. I have a JSON parser class which is retrieving data from a database. The retrieved info contains 'ID', 'name' and 'status' fields related to a device. I can display ID and name of each of the devices (there are several rows) using a listview but I don't know how to use the 'status' field value (it is either 1 or 0) to set an associated Switch component. I have to set the Switch associated with each listview item to ON if incoming 'status' value is 1 and set it OFF if 'status' is 0. I am lost on where to put the 'setChecked' method for every listview item. Here's the code of activity that shows these list items:
Code:
package com.iotautomationtech.androidapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ToggleButton;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
public class AllDevicesActivity extends ListActivity {
Switch mySwitch = (Switch) findViewById(R.id.switchButton);
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "external_link_removed";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "devices";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_devices);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditDeviceActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllDevicesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String status = c.getString(TAG_STATUS);
int toggleValue = Integer.parseInt(c.getString(TAG_STATUS));
boolean sBool = false;
if (toggleValue == 1) {
sBool = true;
}
if (status.equals("1")) {
status = "Status: ON";
}
else {
status = "Status: OFF";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewDeviceActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} 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();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllDevicesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_STATUS},
new int[] { R.id.pid, R.id.name, R.id.status });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The XML file:
Code:
<RelativeLayout xmlns:android="schemas.android"
android:layout_width="fill_parent"
android:layout_height="65dip"
android:orientation="vertical"
android:layout_centerVertical="true"
>
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:textSize="17dip"
android:layout_below="@+id/name"
/>
<Switch
android:id="@+id/switchButton"
android:layout_alignParentRight="true"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginRight="6dip"
android:layout_centerVertical="true"
android:textOff="OFF"
android:textOn="ON"
android:onClick="onSwitchClicked"
/>
</RelativeLayout>
I have reached thus far with the code: [attached-image]
Now I only have to set those Switches according to status values from database. I have tried putting the setChecked in doInBackground method and onPostExecute method but it doesn't work. Do I have to save all status values in an array and start a loop to set all Switches? Where would that code go?
ANY kind of help/guidance here is appreciated!

[Q]How to hand different Strings to dynamically created Fragments using ViewPager?

I can't seem to find a way to give different text to a dynamically created fragment for my pageviewer-supoorted application. I've came to a point of my codding where I got stuck. For my application I want to have 400-500 dynamically created fragments, where you can horizontally slide thru them and every content of the fragment to be the same (repeating the same fragment) and the only different thing to be the text on them.
Here's where I got stuck at my codding :
Code:
package com.example.testarearg;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
[user=439709]@override[/user]
public void onPageSelected(int position) {
}
});
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
[user=439709]@override[/user]
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
[user=439709]@override[/user]
public int getCount() {
// Show 3 total pages.
return 3;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/ private String mText; // display this text in your fragment
public static Fragment getInstance(String text) {
Fragment f = new Fragment();
Bundle args = new Bundle();
args.putString("text", text);
f.setArguments(args);
return f;
}
public void onCreate(Bundle state) {
super.onCreate(state);
setmText(getArguments().getString("text"));
// rest of your code
}
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
}
}
featyhu James
I wanted to first off introduce you to a widget called Viewpagerindicator by Jake Wharton if you haven't already come across it. It is a very popular viewpager extension.
You can download a demo from google play (this I recommend), search for "viewpager indicator"
To give you a back of the envelope solution, I would suggest you try creating at least 2 fragments and then page between them updating the text in on resume(). Do these fragment words need to be remembered? For instance if the user swipes back and forth are the same words meant to reappear?
hgpb said:
I wanted to first off introduce you to a widget called Viewpagerindicator by Jake Wharton if you haven't already come across it. It is a very popular viewpager extension.
You can download a demo from google play (this I recommend), search for "viewpager indicator"
To give you a back of the envelope solution, I would suggest you try creating at least 2 fragments and then page between them updating the text in on resume(). Do these fragment words need to be remembered? For instance if the user swipes back and forth are the same words meant to reappear?
Click to expand...
Click to collapse
Ohh, I was not aware about this extension. I'm gonna try it and see what I get out of it. Yes, the words need to be remembered. Thank you for the heads-up about 'viewpager indicator' .
Feciuc said:
Ohh, I was not aware about this extension. I'm gonna try it and see what I get out of it. Yes, the words need to be remembered. Thank you for the heads-up about 'viewpager indicator' .
Click to expand...
Click to collapse
When you get the Viewpager indicator setup with a couple of fragments initialised you need to track the words you create. You could use a SparseArray/ArrayList or such like to track the position of frag and word perhaps. Then you should be able to move through the array depending on the swipe you receive. The swipe would move you up or down the array giving you access.
Code:
SparseArray<String> sa = new SparseArray<String>();
As I said this is a back of the envelope solution but it may just do the trick.

[Q] Code not bringing desired results

good day,
i'm trying to create an app that will create options in a listview on an an activity based on the option a user selects in the previous activity
below is the code i came up with but it doesn't work.
please what am i doing wrong?
thanks in advance
package com.inveniotech.moneyventure;
/**
* Created by BolorunduroWB on 9/3/13.
*/
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import java.util.*;
import android.content.Intent;
public class menu_options extends Activity {
SimpleAdapter simpleAdpt;
Intent intent = getIntent();
public String message = intent.getStringExtra(football.EXTRA_MESSAGE);
String[] menuList;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuoptionsview);
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, optionList, android.R.layout.simple_list_item_1, new String[] {"options"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(menu_options.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// The data to show
List<Map<String, String>> optionList = new ArrayList<Map<String,String>>();
private void initList() {
// We populate the planets
if (message.equals("5")){
menuList = new String[]{"News", "Fixtures","Results","Standings"," "};
}
else if (message.equals("6")){
menuList = new String[]{"News", "Tables"," "," "," "};
}
else if (message.equals("7")){
menuList = new String[]{"Done Deals", "Rumours","Latest News","Live","Transfer Centre"};
}
else {
menuList = new String[] {"News","Teams","Fixtures","Results","Table"};
}
optionList.add(createOptions("options", menuList[0]));
optionList.add(createOptions("options", menuList[1]));
optionList.add(createOptions("options", menuList[2]));
optionList.add(createOptions("options", menuList[3]));
optionList.add(createOptions("options", menuList[4]));
}
private HashMap<String, String> createOptions(String key, String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put(key, name);
return options;
}
}
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
SimplicityApks said:
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
Click to expand...
Click to collapse
Thank you. Wanted to post the link, too. :laugh:

[Tutorial] Learn to save data with SQLite on Android

Hello,
I create that thread to present you a tutorial learning you to save data with SQLite on Android. This tutorial is also available in video on Youtube :
Learn to save data with SQLite on Android
On Android, there are several solutions to persist data between users’ sessions. One solution is to use a relational database to persist data and then to be able to query easily these data. In standard, Android SDK comes with a SQLite implementation. Biggest advantage of SQLite integration to Android OS is the fact that there is no need to to setup the database. So, no administration of this database. SQLite is embedded in standard and each application can have its SQLite database.
The only job that developers must make is to define SQL tables and statements for creating and updating data. Access to an SQLite database involves accessing the file system. So, it can be a slow operation. To avoid ANR (Application Not Responding) errors, it’s recommended to perform database operations asynchronously.
When an application creates and uses a SQLite database, it will be saved by default in the directory : DATA/data/APP_PACKAGE/databases/FILENAME .
1. Architecture
All classes needed to manage databases in Android SDK are contained in the package android.database . The package android.database.sqlite contains the SQLite specific classes.
SQLite API is centered around 2 main classes :
SQLiteOpenHelper that is an helper class to extend to manage database operations.
SQLiteDatabase that is the base class for working with a SQLite database in Android.
2. SQLiteOpenHelper
When you want to work with a SQLite database in Android, you must extend SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
You need also to override the following methods :
onCreate() that is called when database is accessed but not yet created.
onUpgrade() called when you choose to increment the version number of the database. In this method you can manage the migration process between two databases versions.
Both methods get and SQLiteDatabase instance in parameter which is the way to communicate with the database.
Furthermore, SQLiteOpenHelper provides 2 methods to get access to an SQLiteDatabase instance object respectively in read and in write modes :
getReadableDatabase() for read mode.
getWriteableDatabase() for write mode.
3. SQLiteDatabase
SQLiteDatabase is the class used to communicate with a SQLite database. It exposes several methods to interact with database like insert(), update() or delete().
In addition, it lets you to make queries via rawQuery() to queries made directly in SQL or via query() method. This last method provides a structured interface for specifying a SQL query.
4. Practice
Now, you know theory about SQLite in Android context. We can put in practice all the concepts. To achieve that, we’re going to make a database with a players table letting us to store NBA players.
To start, we create a simple Player Java POJO :
Code:
public class Player {
private int id;
private String name;
private String position;
private int height;
public Player() {
}
public Player(int id, String name, String position, int height) {
this.id = id;
this.name = name;
this.position = position;
this.height = height;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return name + " - " + position + " - " + height + " cm";
}
}
Then, we must create the SQLiteOpenHelper extended class to manage our application database. Code is here :
Code:
package com.ssaurel.samples.sqlite;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteDatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "PlayersDB";
private static final String TABLE_NAME = "Players";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_POSITION = "position";
private static final String KEY_HEIGHT = "height";
private static final String[] COLUMNS = { KEY_ID, KEY_NAME, KEY_POSITION,
KEY_HEIGHT };
public SQLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATION_TABLE = "CREATE TABLE Players ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT, "
+ "position TEXT, " + "height INTEGER )";
db.execSQL(CREATION_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// you can implement here migration process
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
public void deleteOne(Player player) {
// Get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "id = ?", new String[] { String.valueOf(player.getId()) });
db.close();
}
public Player getPlayer(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null)
cursor.moveToFirst();
Player player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
return player;
}
public List<Player> allPlayers() {
List<Player> players = new LinkedList<Player>();
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Player player = null;
if (cursor.moveToFirst()) {
do {
player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
players.add(player);
} while (cursor.moveToNext());
}
return players;
}
public void addPlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
// insert
db.insert(TABLE_NAME,null, values);
db.close();
}
public int updatePlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
int i = db.update(TABLE_NAME, // table
values, // column/value
"id = ?", // selections
new String[] { String.valueOf(player.getId()) });
db.close();
return i;
}
}
Database is created in the constructor of the extended class. Players table is created in the onCreate() method thanks to a SQL statement.
In our class, we add methods to add a new player, to delete an existing one, to update and then a method to get all the players in the table. In this last method, we use a Cursor object to iterate on rows and then build equivalent Player instances.
To use our class to create some players then display on a simple ListView, we can use the following code :
Code:
public class MainActivity extends Activity {
private SQLiteDatabaseHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create our sqlite helper class
db = new SQLiteDatabaseHandler(this);
// create some players
Player player1 = new Player(1, "Lebron James", "F", 203);
Player player2 = new Player(2, "Kevin Durant", "F", 208);
Player player3 = new Player(3, "Rudy Gobert", "C", 214);
// add them
db.addPlayer(player1);
db.addPlayer(player2);
db.addPlayer(player3);
// list all players
List<Player> players = db.allPlayers();
if (players != null) {
String[] itemsNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
itemsNames[i] = players.get(i).toString();
}
// display like string instances
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, itemsNames));
}
}
}
Execution result can be seen here :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
SQLite implementation in Android is simple and really powerful. You can now use it in your Android application to persist data.
Don't hesitate to give it a try and give me your feedbacks about this tutorial.
Thanks.
Sylvain
Hey, I have made a preview for SQLite database earlier this month for my friend.
If anyone's interested then it's there at https://www.GitHub.com/Fifa2151/SQLiteTest
Thanks,
Raj.
Sent from my Pixel using Tapatalk
sylsau said:
Hello,
I create that thread to present you a tutorial learning you to save data with SQLite on Android. This tutorial is also available in video on Youtube :
Learn to save data with SQLite on Android
On Android, there are several solutions to persist data between users’ sessions. One solution is to use a relational database to persist data and then to be able to query easily these data. In standard, Android SDK comes with a SQLite implementation. Biggest advantage of SQLite integration to Android OS is the fact that there is no need to to setup the database. So, no administration of this database. SQLite is embedded in standard and each application can have its SQLite database.
The only job that developers must make is to define SQL tables and statements for creating and updating data. Access to an SQLite database involves accessing the file system. So, it can be a slow operation. To avoid ANR (Application Not Responding) errors, it’s recommended to perform database operations asynchronously.
When an application creates and uses a SQLite database, it will be saved by default in the directory : DATA/data/APP_PACKAGE/databases/FILENAME .
1. Architecture
All classes needed to manage databases in Android SDK are contained in the package android.database . The package android.database.sqlite contains the SQLite specific classes.
SQLite API is centered around 2 main classes :
SQLiteOpenHelper that is an helper class to extend to manage database operations.
SQLiteDatabase that is the base class for working with a SQLite database in Android.
2. SQLiteOpenHelper
When you want to work with a SQLite database in Android, you must extend SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
You need also to override the following methods :
onCreate() that is called when database is accessed but not yet created.
onUpgrade() called when you choose to increment the version number of the database. In this method you can manage the migration process between two databases versions.
Both methods get and SQLiteDatabase instance in parameter which is the way to communicate with the database.
Furthermore, SQLiteOpenHelper provides 2 methods to get access to an SQLiteDatabase instance object respectively in read and in write modes :
getReadableDatabase() for read mode.
getWriteableDatabase() for write mode.
3. SQLiteDatabase
SQLiteDatabase is the class used to communicate with a SQLite database. It exposes several methods to interact with database like insert(), update() or delete().
In addition, it lets you to make queries via rawQuery() to queries made directly in SQL or via query() method. This last method provides a structured interface for specifying a SQL query.
4. Practice
Now, you know theory about SQLite in Android context. We can put in practice all the concepts. To achieve that, we’re going to make a database with a players table letting us to store NBA players.
To start, we create a simple Player Java POJO :
Code:
public class Player {
private int id;
private String name;
private String position;
private int height;
public Player() {
}
public Player(int id, String name, String position, int height) {
this.id = id;
this.name = name;
this.position = position;
this.height = height;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return name + " - " + position + " - " + height + " cm";
}
}
Then, we must create the SQLiteOpenHelper extended class to manage our application database. Code is here :
Code:
package com.ssaurel.samples.sqlite;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteDatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "PlayersDB";
private static final String TABLE_NAME = "Players";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_POSITION = "position";
private static final String KEY_HEIGHT = "height";
private static final String[] COLUMNS = { KEY_ID, KEY_NAME, KEY_POSITION,
KEY_HEIGHT };
public SQLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATION_TABLE = "CREATE TABLE Players ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT, "
+ "position TEXT, " + "height INTEGER )";
db.execSQL(CREATION_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// you can implement here migration process
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
public void deleteOne(Player player) {
// Get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "id = ?", new String[] { String.valueOf(player.getId()) });
db.close();
}
public Player getPlayer(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null)
cursor.moveToFirst();
Player player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
return player;
}
public List<Player> allPlayers() {
List<Player> players = new LinkedList<Player>();
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Player player = null;
if (cursor.moveToFirst()) {
do {
player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
players.add(player);
} while (cursor.moveToNext());
}
return players;
}
public void addPlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
// insert
db.insert(TABLE_NAME,null, values);
db.close();
}
public int updatePlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
int i = db.update(TABLE_NAME, // table
values, // column/value
"id = ?", // selections
new String[] { String.valueOf(player.getId()) });
db.close();
return i;
}
}
Database is created in the constructor of the extended class. Players table is created in the onCreate() method thanks to a SQL statement.
In our class, we add methods to add a new player, to delete an existing one, to update and then a method to get all the players in the table. In this last method, we use a Cursor object to iterate on rows and then build equivalent Player instances.
To use our class to create some players then display on a simple ListView, we can use the following code :
Code:
public class MainActivity extends Activity {
private SQLiteDatabaseHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create our sqlite helper class
db = new SQLiteDatabaseHandler(this);
// create some players
Player player1 = new Player(1, "Lebron James", "F", 203);
Player player2 = new Player(2, "Kevin Durant", "F", 208);
Player player3 = new Player(3, "Rudy Gobert", "C", 214);
// add them
db.addPlayer(player1);
db.addPlayer(player2);
db.addPlayer(player3);
// list all players
List<Player> players = db.allPlayers();
if (players != null) {
String[] itemsNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
itemsNames[i] = players.get(i).toString();
}
// display like string instances
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, itemsNames));
}
}
}
Execution result can be seen here :
SQLite implementation in Android is simple and really powerful. You can now use it in your Android application to persist data.
Don't hesitate to give it a try and give me your feedbacks about this tutorial.
Thanks.
Sylvain
Click to expand...
Click to collapse
Awesome guide @sylsau...
Also, do you know how to make a flashify type app but only for a specific zip?
When you want to work with a SQLite database in Android, you must extend SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
Click to expand...
Click to collapse
You don't actually need to use a subclass of SQLiteOpenHelper you can use the SQliteDatabase's open????? methods.
Furthermore, SQLiteOpenHelper provides 2 methods to get access to an SQLiteDatabase instance object respectively in read and in write modes :
Click to expand...
Click to collapse
Actually, in either case, except if the database cannot be opened, for write, both getReadableDatabase and getWritableDatabase will open a database that can be written to. As per :-
Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.
Click to expand...
Click to collapse
as per developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper#getReadableDatabase()​
On occasions people new to SQLite sometimes wonder why no database exists after they have instantiated the subclass of SQLiteOpenHelper (aka the DatabaseHelper). This is because the database is only created when either getWritableDatabase or getReadableDatabase is called. With a single line added to the constructor, the constructor will create the database (and thus invoke the onCreate method) e.g.
Code:
public SQLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.getWritableDatabse();
}
AUTOINCREMENT is perhaps the most commonly misused keyword (perhaps wrongly named). It does not make the column automatically generate a unique ID. It is INTEGER PRIMARY KEY that does this, as it make the column an alias of the **rowid**.
Rather AUTOINCREMENT compliments INTEGER PRIMARY KEY adding a constraint that the generated ID must be larger that any ID that exists or have existed. However, this is a moot point as it's only when the largest possible ID has been assigned (9223372036854775807) that it comes into play (other than without AUTOINCREMENT a deleted highest ID will be resused). At this point a table with AUTOINCREMENT will then fail with an SQLITE_FULL exception (without AUTOINCREMENT will attempt to assign a free lower ID rather than fail). However, AUTOINCREMENT has overheads (using a limited test I came up with an 8-12% degradation in performance when inserting). This is due to a changed algorithm being used that utilises another table sqlite_sequence that stores the highest allocated ID.
The SQLite documentation states :-
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
Click to expand...
Click to collapse
sqlite.org/autoinc.html
There are a few issues with the code, such as :-
You should always close Cursors when finished with them (not doing so may result in too many databases /database objects open exception ).
Checking a Cursor for null after a Cursor is returned from a call to an SQLiteDatabase method that returns a Cursor serves no purpose. A valid Cursor will always be returned. If there is no data then using a Cursor moveTo????? method will return false is the move cannot be made, alternately the getCount() method will return the number of rows in the Cursor.
If there were now rows in the Players table, the the code would fail with an error when an attempt is made to retrieve data at
Code:
player.setId(Integer.parseInt(cursor.getString(0)));
Issues regarding mis-calculated column offsets can be reduced by taking advantage of the Cursor's **getColumnIndex** method.
As such, as an example, the getPlayer method would be improved if changed to :-
Code:
public Player getPlayer(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
Player player = new Player(); //<<<<<<<<<< Always have a Player to return (should check for default player to indicated )
if (cursor.moveToFirst()) {
player.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
player.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
player.setPosition(cursor.getString(cursor.getColumnIndex(KEY_POSITION)));
player.setHeight(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_HEIGHT))));
}
cursor.close(); //<<<<<<<<<< Important to close a Cursor
return player;
}

Categories

Resources