problem with ListActivity - android

The following is my code for SettingsActivity.java. The main activity starts this activity by calling onScreenSettings(this)
public class SettingsActivity extends ListActivity{
static String[] main_settings = {"mode",
"timeout"
};
static String[] mode = { "Audio",
"Video",
"Audio/Video"
};
static String[] timeout = {
"1 min",
"5 min",
"10 min"
};
static String result;
static String[] display;
boolean settings_selected = false;
static String TAG = "****ALIST****";
public static void onScreenSettings(Activity c){
display = main_settings;
Log.d(TAG,"inside onScreenSettings");
Intent intent = new Intent(c.getApplication(),SettingsActivity.class);
try{
c.startActivityForResult(intent,1);
Log.d(TAG,"after starting activity in onScreenSettings");
}catch(Exception e){
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"inside onCreate-before setting listview");
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, display));
getListView().setTextFilterEnabled(true);
Log.d(TAG,"inside oncreate-after setting listview");
}
public void onListItemClick(ListView l, View v, int position, long id){
result = (String) l.getItemAtPosition(position);
if(!settings_selected){
if(result.equals("mode")){
display = mode;
}
else if(result.equals("timeout")){
display = timeout;
}
settings_selected = true;
Log.d(TAG,"if !setting_selected");
}
else{/*accepting the sub options*/
display = main_settings;//next the main settings must be displayed
if(result.equals("Audio")){
}
else if(result.equals("Video")){
Log.d(AndroidRecorder.TAG,"inside sub option Video");
}
else if(result.equals("Audio/Video")){
}
settings_selected = false;
Log.d(TAG,"if setting_selected");
}
Intent intent = new Intent(this.getApplication(),SettingsActivity.class);
try{
startActivityForResult(intent,1);
Log.d(TAG,"after starting activity in ListItemClick");
}
catch(Exception e){
}
}
public void onActivityResult(int requestCode, int resultCode,Intent data) {
//nothing to do with the intent here
Log.d(TAG,"inside onActivityResult");
setResult(RESULT_OK, data);
finish();
Log.d(TAG,"inside onActivityResult-after finish()");
}
/*public void onBackPressed(){
Log.d(TAG,"inside onBackPressed");
finish();
Log.d(TAG,"inside onBackPressed-after finish()");
}*/
}//end of ListActivity
Problem is control is not entering the else /*accepting the sub options*/ and I can't figure out why. As a result, the mode or timeout list is getting displayed again and again and the main_settings is not displayed.
Please help.

When you call startActivityForResult in onListItemClick you get a whole new instance of the SettingsActivity. Does logcat show "inside oncreate" right after it shows "if !setting_selected"?
If it does and you don't want to go through major refactoring, you can stuff the value of setting_selected into an extra on the intent and pull it out in onCreate.

Related

Multiple Activities, launching and passing data

I am attempting to create a list of users in an android app. The list is on the MainActivity, with a button which redirects to AddMember. AddMember will take input for one member. I am trying to pass the information back to MainActivity, however it fails before I even get to the AddMemberActivity, when testing. It stops after the button click on the MainActivity.
Trie implementation
The error message is:
java.lang.NullPointerException: Attempt to invoke virtual method 'char java.lang.String.charAt(int)' on a null object reference
at attendance.Trie.get(Trie.java:117)
at attendance.Trie.get(Trie.java:113)
at attendance.MainActivity$1.onClick(MainActivity.java:49)
line 49 is
if (trie.get(name) != null) {
public class MainActivity extends AppCompatActivity {
private Button button;
private ListView list;
private Trie trie;
private ArrayAdapter<String> adapter;
private int count = 0;
private static final int REQUEST_CODE = 100;
private String name;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if(resultCode == RESULT_OK) {
name = data.getStringExtra("name");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.addBtn);
list = (ListView) findViewById(R.id.memberList);
trie = new Trie();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddMember.class);
startActivityForResult(intent, REQUEST_CODE);
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.content_list_items,R.id.list_content, trie.traverse());
list.setAdapter(adapter);
//check that member was added
if (trie.get(name) != null) {
// <- look for item!
//made an alert to show member already exists
} else {
trie.put(name.toLowerCase(), count++);
adapter.add(name);
}
adapter.notifyDataSetChanged();
}
});
}
}
public class AddMember extends AppCompatActivity {
//Array of options --> ArrayAdapter --> ListView
//ListView :{views, items.xml}
private static final int REQUEST_CODE = 100;
private Button button;
private EditText name;
private EditText phone;
private EditText email;
private ArrayAdapter<Member> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_member);
button = (Button) findViewById(R.id.uploadMember);
name = (EditText) findViewById(R.id.edit_name);
//add member button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("name", name.getText());
setResult(RESULT_OK, intent);
finish();
}
});
}
}
It is clear from crash log that you are attempting to get character from null string .
java.lang.String.charAt(int)' on a null object reference at attendance.Trie.get(Trie.java:117)
Reason : You are passing null value in get method. You never assign the name string and by default it is assigned with null. And you pass it with trie.get(name).
Check your get method of Trie class and put a check of null. If name is not null then get the character from string otherwise return null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if(resultCode == RESULT_OK) {
name = data.getStringExtra("name");
if(adapter == null){
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.content_list_items,R.id.list_content, trie.traverse());
list.setAdapter(adapter);
}
//check that member was added
if (trie.get(name) != null) {
// <- look for item!
//made an alert to show member already exists
} else {
trie.put(name.toLowerCase(), count++);
adapter.add(name);
}
adapter.notifyDataSetChanged();
}
}
}
Remove adapter code from onClick method
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddMember.class);
startActivityForResult(intent, REQUEST_CODE);
});

How to use FB FriendPickerFragment to show you list of all your friends in order to invite them to use your app

EDIT-----: So I did manage to make it show me users and be able to select some, and to send me back the selected users to my app but there is a slight problem. "Uri.parse("picker://friend");" doesn't give me the list of my friends, but only a list of the friends that I have and have my app installed.
I followed this example: https://developers.facebook.com/docs/android/scrumptious/show-friends but I am trying to modify it, so basically I took out the selectionActivity and Fragment. So I have from my activity a button that calls the PickerActivity which contains FriendPickerFragment. I can select my friends from there, but back in my activities onActivityResult i get back "data" as null.
I have an Application class in my app, where i save the FB session, and also have the login function in there.
In my MainActivity onCreate I have this:
MyApp.getInstance().facebookLogin(PSAddFriendsActivity.this, new CrudStateCallback() {
#Override
public void onResponse(final String string) {
Log.i("", "session : session is opened? : " + MyApp.getInstance().fbSession.getAccessToken());
}
});
After having logged in, I instantiate a list with the current friends I have in my app, and the first position of this list is a FB button:
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
if(position == 0){
startPickerActivity(PSPickerActivity.FRIEND_PICKER, 0);
}else if(position ==1){
//TODO: OPEN CONTACTS PAGE TO ADD FRIENDS
}
}
This is my onACtivityResult and the "startPickerActivity" from this class:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Log.i("","--------------data is : " + data);
Log.i("","--------------resultCode is : " + resultCode);
Log.i("","--------------requestCode is : " + requestCode);
}
public void startPickerActivity(Uri data, int requestCode) {
Intent intent = new Intent();
intent.setData(data);
intent.setClass(PSAddFriendsActivity.this, PickerActivity.class);
startActivityForResult(intent, requestCode);
}
This is the PickerActivity, how I took it from FB:
public class PickerActivity extends FragmentActivity{
private FriendPickerFragment friendPickerFragment;
public static final Uri FRIEND_PICKER = Uri.parse("picker://friend");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pickers);
Bundle args = getIntent().getExtras();
FragmentManager manager = getSupportFragmentManager();
Fragment fragmentToShow = null;
Uri intentUri = getIntent().getData();
if (FRIEND_PICKER.equals(intentUri)) {
if (savedInstanceState == null) {
friendPickerFragment = new FriendPickerFragment(args);
} else {
friendPickerFragment =
(FriendPickerFragment) manager.findFragmentById(R.id.picker_fragment);
}
// Set the listener to handle errors
friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> fragment,
FacebookException error) {
PSPickerActivity.this.onError(error);
}
});
// Set the listener to handle button clicks
friendPickerFragment.setOnDoneButtonClickedListener(
new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
finishActivity();
}
});
fragmentToShow = friendPickerFragment;
} else {
// Nothing to do, finish
setResult(RESULT_CANCELED);
finish();
return;
}
manager.beginTransaction()
.replace(R.id.picker_fragment, fragmentToShow)
.commit();
}
private void onError(Exception error) {
onError(error.getLocalizedMessage(), false);
}
private void onError(String error, final boolean finishActivity) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.error_dialog_title).
setMessage(error).
setPositiveButton(R.string.error_dialog_button_text,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (finishActivity) {
finishActivity();
}
}
});
builder.show();
}
private void finishActivity() {
setResult(RESULT_OK, null);
finish();
}
#Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
friendPickerFragment.loadData(false);
} catch (Exception ex) {
onError(ex);
}
}
}
#Override
protected void onResume() {
Log.i("", "location test onResume");
super.onResume();
MyApp.getInstance().pref.setIsBackground(this, false);
MyApp.getInstance().startLocationClient();
}
#Override
protected void onPause() {
Log.i("", "location test onPause");
super.onPause();
MyApp.getInstance().pref.setIsBackground(this, true);
}
}
Now I looked over this fragment, do not know if I have to add something or save something from the fragment on "onDoneButtonClicked"? or what exactly, because my main activity does return null as data..
forgot to call this in the finishActivty:
if (FRIEND_PICKER.equals(getIntent().getData())) {
if (friendPickerFragment != null) {
MyApp.getInstance().setSelectedUsers(friendPickerFragment.getSelection());
}
}
Now I can get from my Application the list of selected users.
About my edit, after this i found out that with Graph2.0 you cannot get a list of your whole friendlist. You can only get back the info of friends that also liked the app. It is possible to invite friends to like an app but only if you set it as a Game from the FB developers page

onActivityResult not getting string out of Intent

I need some help with my android app. I have two activities, first starts the second one with startActivityForResult(). When the second one closes it sends the intent as it should, however when i want to access extra from onActivityResult() i get a null instead of what I put in.
I also tried using bundle with
Bundle b = getIntent().getExtras();
b.getString(AddTable.EXTRA_NAME);
but it resulted in RuntimeException and failure delivering result.
Here's my code:
public class RunnerApp extends Activity {
private ListView listView;
private static ArrayList<String> values = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private Intent newTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_app);
listView = (ListView) findViewById(R.id.mylist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
public void addTable(View v){
newTable = new Intent(this, AddTable.class);
startActivityForResult(newTable, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null){
data = getIntent();
Log.d("add", "got intent");
String newName = data.getStringExtra(AddTable.EXTRA_NAME);
Log.d("add", "string " + newName); //always prints string null
values.add(newName);
Log.d("add", "added to list");
}
}
#Override
public void onResume(){
super.onResume();
setContentView(R.layout.activity_runner_app);
adapter.notifyDataSetChanged();
}
}
Second activity started by startActivityForResult()
public class AddTable extends Activity {
public final static String EXTRA_NAME = "com.example.runnerapp.NAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_table);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_add_table, menu);
return true;
}
public void addThisTable(View v) {
Intent addTable = new Intent(this, RunnerApp.class);
EditText editText = (EditText) findViewById(R.id.addTableField);
String name = editText.getText().toString();
addTable.putExtra(EXTRA_NAME, name);
Log.d("intenyt", name);
setResult(Activity.RESULT_OK, addTable);
this.finish();
}
}
In your first activity your code reads
data = getIntent();
But the actual data you want is in
data.getData()
use this in the onActivityResult function..
data.getStringExtra(EXTRA_NAME)

Passing ArrayList between activities

I have an activity where I am adding objects into an ArrayList which implements the Parcelable interface. I then pass this list to another activity via a bundle however I get the following error when I try to print the size of the list in the new activity:
java.lang.RuntimeException: Unable to resume activity {com.example.test/com.example.test.SectionsActivity}: java.lang.NullPointerException
Here is the first activity where I add to list:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), l.getItemAtPosition(position).toString() + " added to order", Toast.LENGTH_SHORT).show();
// add clicked item to orderData....
MenuItem m = (MenuItem) l.getItemAtPosition(position);
// create new item
orderData.add(m);
subTotal += m.getPrice();
calc();
}
This is first activity where I send the data via intent:
confirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b.putParcelable("order", orderData);
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data",b);
startActivity(i);
}
});
and this is second activity where I try to retrieve the bundle and display size:
#Override
protected void onResume() {
super.onResume();
getIntentData();
}
public void getIntentData(){
Intent i = getIntent();
if(i != null & i.hasExtra("data")){
Toast.makeText(this.getApplicationContext(), "recieved", Toast.LENGTH_LONG).show();
b = i.getExtras();
orderData = b.getParcelable("order");
int size = orderData.size();
Toast.makeText(this.getApplicationContext(), String.valueOf(size), Toast.LENGTH_LONG).show();
}
}
Any ideas why I am getting the null pointer?? It's driving me mad!
orderData is a MenuItemList object:
public class MenuItemList extends ArrayList <MenuItem> implements Parcelable{
/**
*
*/
private static final long serialVersionUID = 2998684930374219271L;
public MenuItemList(){
}
public static final Parcelable.Creator<MenuItemList> CREATOR = new Parcelable.Creator<MenuItemList>() {
#Override
public MenuItemList createFromParcel(Parcel source) {
return new MenuItemList(source);
}
#Override
public MenuItemList[] newArray(int size) {
return new MenuItemList[size];
}
};
public MenuItemList(Parcel source) {
readFromParcel(source);
}
private void readFromParcel(Parcel source) {
this.clear();
//read the size of the list
int size = source.readInt();
//Remember order of items written into the Parcel. Important here.
for(int i = 0; i < size; i ++){
MenuItem item = new MenuItem();
item.setName(source.readString());
item.setPrice(source.readDouble());
this.add(item);
}
}
#Override
public void writeToParcel(Parcel dest, int flags) {
int size = this.size();
dest.writeInt(size);
for(int i = 0; i < size; i ++){
MenuItem item = this.get(i);
dest.writeString(item.getName());
dest.writeDouble(item.getPrice());
}
}
#Override
public int describeContents() {
return 0;
}
}
CHANGES TO CODE THAT SOLVED PROBLEM:
CHANGED onClick(View v):
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data", (ArrayList<MenuItem>)orderData);
startActivity(i);
}
CHANGED getIntent():
public void getIntentData(){
Intent i = getIntent();
if(i != null && i.hasExtra("data")){
Toast.makeText(this.getApplicationContext(), "recieved", Toast.LENGTH_LONG).show();
orderData = i.getParcelableExtra("data");
int size = orderData.size();
Toast.makeText(this.getApplicationContext(), String.valueOf(size), Toast.LENGTH_LONG).show();
}
}
Rewrite
The problem is that you have an extra Bundle. Currently in getIntentData() you have to call:
getIntent() // Fetch the Intent,
.getExtras() // Fetch the Bundle of extras,
.getBundle("data") // Fetch the Bundle "data",
.getParcelable("order"); // Then get your parcelable...
Let's cut out the unnecessary Bundle.
public void onClick(View v) {
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data", orderData);
startActivity(i);
}
Now update getIntentData():
Intent i = getIntent();
if(i != null && i.hasExtra("data")){
orderData = i.getParcelableExtra("data");
...
}
Unless I missed something, you are using the bitwise & instead of the logical && in your getIntentData() function

keeping a variable value across all android activities

I have a database with one row of data that will be used across a number of activities. I need to be able to keep the row id available in all activites so I can read and write data across different activites with my DB adapter. I have successfully used putExtra (Overthelimit.java) via an intent to pass a row id to the next activity. mRowId variable is then given the row id using getExtra (Profile.java). The problem I now have is making mRowId available to other activities i.e. MyUsual and DrinksList so I can update data as I go.
You can see I have tried putExtras, putSerializable but can't get it to work. I think I am missing some understanding.
So for my profile menu option in the activity below I can send the value of the cursor row id to Profile class:
public class Overthelimit extends ListActivity {
private OverLimitDbAdapter dbHelper;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getListView();
dbHelper = new OverLimitDbAdapter(this);
dbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void fillData() {
cursor = dbHelper.fetchAllUserDrinks();
startManagingCursor(cursor);
//cursor.getCount();
String[] from = new String[] { OverLimitDbAdapter.KEY_USERNAME };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.user_row, cursor, from, to);
setListAdapter(notes);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
Intent myIntent1 = new Intent(this, Profile.class);
if(cursor.getCount() != 0) {
//Toast.makeText(getApplicationContext(), "no profile",Toast.LENGTH_SHORT).show();
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
}
startActivityForResult(myIntent1, 0);
return true;
case R.id.myusual:
Intent myIntent2 = new Intent(this, MyUsual.class);
startActivityForResult(myIntent2, 0);
return true;
case R.id.trackme:
Intent myIntent3 = new Intent(this, TrackMe.class);
startActivityForResult(myIntent3, 0);
return true;
case R.id.moreinfo:
Intent myIntent4 = new Intent(this, MoreInfo.class);
startActivityForResult(myIntent4, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then make it available as mRowId in my Profile activity below:
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
I then need to make this mRowId available to another activity called DrinkList from MyUsual. so I have MyUsual below with a drink1 button onClickListener to try and send the row id to DrinksList:
public class MyUsual extends Activity {
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
private Cursor cursor;
private TextView mDrink1Label;
private TextView mDrink1Units;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.my_usual);
mDrink1Label = (TextView) findViewById(R.id.drink1Label);
mDrink1Units = (TextView) findViewById(R.id.drink1Units);
Button drink1 = (Button) findViewById(R.id.drink1Button);
// get intent data i.e. which drink button pressed and mRowId
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
//populateFields();
drink1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
//finish();
Intent myIntent1 = new Intent(view.getContext(), DrinksList.class);
myIntent1.putExtra("drinkButton", "drink1");
if(cursor.getCount() != 0) {
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
}
startActivityForResult(myIntent1, 0);
}
});
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
}
From DrinksList I select a drink and I need to use the mRowId write the data to the database via the onListItemclick:
public class DrinksList extends ListActivity {
private ProgressDialog m_ProgressDialog = null;
private ArrayList<CreateDrinkOption> m_drinks = null;
private DrinkAdapter m_adapter;
private Runnable viewDrinks;
private String drinkButton;
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
private String databaseRow;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.drinks_list);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
m_drinks = new ArrayList<CreateDrinkOption>();
this.m_adapter = new DrinkAdapter(this, R.layout.drink_row, m_drinks);
setListAdapter(this.m_adapter);
viewDrinks = new Runnable(){
#Override
public void run() {
getDrinks();
}
};
Thread thread = new Thread(null, viewDrinks, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(DrinksList.this,
"Please wait...", "Retrieving data ...", true);
// get intent data i.e. which drink button pressed and mRowId
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
drinkButton = extras.getString(drinkButton);
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_drinks != null && m_drinks.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_drinks.size();i++)
m_adapter.add(m_drinks.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
try
{
super.onListItemClick(l, v, position, id);
CreateDrinkOption bkg = (CreateDrinkOption)l.getItemAtPosition(position);
String drink1type = bkg.getDrinkType().toString();
float drink1units = (bkg.getPercentageByVolume() * bkg.getVolume());
//Toast.makeText(this, mRowId.toString(), Toast.LENGTH_LONG).show();
mDbHelper.updateDrink(mRowId, drink1type, drink1units);
finish();
}
catch(Exception ex)
{
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
}
private void getDrinks(){
try{
m_drinks = new ArrayList<CreateDrinkOption>();
CreateDrinkOption o1 = new CreateDrinkOption();
o1.setDrinkType("Beer - 1 pint");
o1.setPercentageByVolume((float) 4.5);
o1.setVolume((float) 0.5);
m_drinks.add(o1);
CreateDrinkOption o2 = new CreateDrinkOption();
o2.setDrinkType("Wine - small glass");
o2.setPercentageByVolume((float) 12);
o2.setVolume((float) 0.125);
m_drinks.add(o2);
CreateDrinkOption o3 = new CreateDrinkOption();
o3.setDrinkType("Spirit - single");
o3.setPercentageByVolume((float) 40);
o3.setVolume((float) 0.25);
m_drinks.add(o3);
CreateDrinkOption o4 = new CreateDrinkOption();
o4.setDrinkType("Alcopop - bottle");
o4.setPercentageByVolume((float) 5);
o4.setVolume((float) 0.275);
m_drinks.add(o4);
Thread.sleep(1000);
Log.i("ARRAY", ""+ m_drinks.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class DrinkAdapter extends ArrayAdapter<CreateDrinkOption> {
private ArrayList<CreateDrinkOption> items;
public DrinkAdapter(Context context, int textViewResourceId, ArrayList<CreateDrinkOption> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.drink_row, null);
}
CreateDrinkOption o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.drinkdetail);
TextView bt = (TextView) v.findViewById(R.id.drinkunits);
if (tt != null) {
tt.setText("Type: "+o.getDrinkType());
}
if(bt != null){
bt.setText("Units: "+ String.valueOf(o.getPercentageByVolume() * o.getVolume()));
}
}
return v;
}
}
}
Sorry for the long post, but all I need to do is make this value for mRowId available to all activites so I can read/write data at any point. The data also needs to be there if the app is paused or interupted by say an incoming call, so I use onSaveInstanceState.
ok, thanks. So reply to great answers and I have done this, but it crashes trying to get the data. I have this as my Application class:
public class OverthelimitApplication extends Application {
private Long rowId;
public Long getRowId() {
return rowId;
}
public void setRowId(Long value) {
rowId = value;
}
}
then set value with this:
OverthelimitApplication app1 = (OverthelimitApplication)getApplicationContext();
app1.setRowId((long) cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID));
then try to get value with this and it crashes:
mRowId = ((OverthelimitApplication) getApplicationContext()).getRowId();
I have fixed it! using this the set and get:
app1.setRowId(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID))));
mRowId = (long)((OverthelimitApplication)getApplicationContext()).getRowId();
I still had to specify long when setting and getting. Thanks for all your input.
Another way is to create a application class which is available for all activities.
To do that, you have to extend you Manifest with
<application
..
android:name=".MyApplication" >
and create a new Class
public class MyApplication extends Application {
public int rowId = 0;
}
inside the activities, you can access the rowId by
int mRowId = ((MyApplication) getApplicationContext()).rowId;
There are two options that I think are fit for your purpose:
SharedPreferences: the added benefit is that your variables will kept and available next time you start the application. You can store primitive types easily in shared preferences, like your rowId.
Application: you can subclass the application class, something like MyApplication extends Application, declare in your manifest that you're using this class instead of the default application, and access it using getApplication from all your activities. The added benefit is you can store anything, even a complex data structure in the application, you define the member and access methods in your MyApplication class. For example you could store the whole row of data in your application, not just the rowId)
Personally, I use SharedPreferences to remember settings that I want to be saved for the user, and not having to set them again each time the application is started is nice. And I use application for all the temporary data that I want to live across all activities as long as the application is open.
I'll describe 2 ways.
1) Use a static variable in any one of the Activities. This is the quick, dirty and lazy way. You've been warned.
2) Create your Application class.
Create a Simple class MyApplication that extends Application
In the Android Manifest, there should be a field for Application, make sure you choose your Class.
Typical example.
public class MyApp extends Application
{
private Object myGloballyAccessibleObject; //make getter and setter
private static MyApp singleInstance = null;
public static MyApp getInstance()
{
return singleInstance;
}
#Override
public void onCreate() {
super.onCreate();
singleInstance = this;
}
}
In your activities,
Call this
MyApp myApp = MyApp.getInstance();
myApp.getMyAwesomeObject(); //Booyaah!
You can use the ApplicationContext too. In your Manifest, you should have something like this :
<application
...
android:name="xx.xx.MyApp"
...>
Now, you can access to the Application from any Activity thanks to :
MyApp application = (MyApp)this.getApplicationContext();
You can put your attributes in this class, it'll be accessible anywhere in your app. MyApp must extends Application. See Manifest and
Application
Here you want to get mRowId values from all activity and it is primitive types, So
Either use Shared Preferences for store data or make your member field as a static globally, Then you can use this data in your whole application life cycle..
EDIT: Also you can use Application class as a singleton for your application and create field mRowId in this class and also make getter setter method for this field..

Categories

Resources