Call and set Global variable - android

I'm trying to create a global variable that I can referece anywhere. I need to be able to set the variable depending on the selection the user makes from the ListAdapter onclick. I just can't figure out how to code this. I also need to use that variable for if statements. Sorry I am new to this :)
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_flavor);
String[] select_flavor_list = {"Kansas City", "Memphis", "Texas", "North Carolina", "South Carolina","Alabama"};
ListAdapter FlavorListAdapter = new ArrayAdapter<String>(this, R.layout.row_layout_flavor, R.id.flavor_text_view,
select_flavor_list);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(FlavorListAdapter);
//For list view selection, begin here...
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
GlobalClass flavorPref = ((GlobalClass)getApplicationContext());
flavorPref.setFlavorPreference(String a) = String.valueOf(adapterView.getItemAtPosition(position));
if (flavorPref.equals("Kansas City")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "test " + flavorPref,
Toast.LENGTH_LONG).show();
}
else if (flavorPicked.equals("Memphis")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "test " + flavorPref,
Toast.LENGTH_LONG).show();
}
}
});
}
This is the Global class I created:
public class GlobalClass extends Application {
public String flavorPreference;
public String getFlavorPreference(){
return flavorPreference;
}
public void setFlavorPreference(String a){
flavorPreference = a;
}
}

You can use android shared preference to this kind of usage
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
Insert or Update Value
editor.putString("key_name", "string value");
Get Value
pref.getString("key_name", null);

Related

List can't be saved or loaded

I tried making a dynamic list where the user can add elements by writing a text and pushing a button. The user also should be able to delete elements by clicking on them for a longer time.
All of that is working fine, however everytime I close the App the created list is gone. I'm not sure what exactly is failing, either the loading or the saving.
Here is my code:
public class MainActivity extends AppCompatActivity {
private ArrayList<String> ModuleList;
private ArrayAdapter<String> MyAdapter;
private ListView listView;
private Button addButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
addButton=findViewById(R.id.btnPlus);
MyAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView=findViewById(R.id.listView);
listView.setAdapter(MyAdapter);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addModule(view);
saveData();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
deleteItem(view, position);
saveData();
return true;
}
});
}
private void addModule(View view) {
EditText input =findViewById(R.id.textInput);
String itemText=input.getText().toString();
if(!(itemText.equals("")))
{
ModuleList.add(itemText);
MyAdapter.add(itemText);
MyAdapter.notifyDataSetChanged();
input.setText("");
}
else
{
Toast.makeText(getApplicationContext(),"Please insert Module...",Toast.LENGTH_LONG).show();
}
}
private void deleteItem(View view,int i)
{
Context context = getApplicationContext();
MyAdapter.remove(ModuleList.get(i));
ModuleList.remove(i);
MyAdapter.notifyDataSetChanged();
Toast.makeText(context, "Item Removed", Toast.LENGTH_LONG).show();
}
private void saveData()
{
SharedPreferences sharedPreferences=getSharedPreferences("Shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
Gson gson=new Gson();
String json=gson.toJson(ModuleList);
editor.putString("Task List",json);
editor.apply();
}
private void loadData()
{
SharedPreferences sharedPreferences=getSharedPreferences("Shared preferences",MODE_PRIVATE);
Gson gson=new Gson();
String json=sharedPreferences.getString("Task List",null);
Type type= new TypeToken<ArrayList<String>>() {}.getType();
ModuleList=gson.fromJson(json,type);
if(ModuleList==null){
ModuleList=new ArrayList<>();
}
}
}
I can't see my mistake, but I'm new to all of this. So there might be something obvious missing.
Thank you very much.
i once encountered the same problem and the solution was
instead of
SharedPreferences sharedPreferences=getSharedPreferences("Shared preferences",MODE_PRIVATE);
write (remove the space from the name)
SharedPreferences sharedPreferences=getSharedPreferences("Sharedpreferences",MODE_PRIVATE);
similarly with your variable name
editor.putString("TaskList",json);
String json=sharedPreferences.getString("TaskList",null);
i don't know if this is your case or why this happens since the variable is a string and the space shouldn't matter but for me it never allows me to save anything in sharedPrefs if the name has spaces
then check this line
MyAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
update it with this
MyAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,ModuleList);
for the issue in saving the item twice the problem is here
if(!(itemText.equals("")))
{
ModuleList.add(itemText);
// MyAdapter.add(itemText); remove this line the itemText is already added to the moduleList
MyAdapter.notifyDataSetChanged();
input.setText("");
}
First: create a static final variable to store "Task List", then add some Log.d("TEST", variable) to show in 'Logcat' the interested variables and then update the question please.

How the spinner items not be kept selected as it is while rerunning the app

Hello I want to Know that how can i keep the spinner items selected throughout the activity so that if i come back form other activity to the activity that is consisting of spinner its still remain selected as it is.
The above statement that i have used that has been solved after this there is an another issue that whenever i restart my app its the selected portion remains as it is i want to know what i can do so that the spinner does not show what i have selected before
I have a code of spinner which i want to keep it selected throughout all the activities ,
daySelection = (Spinner)findViewById(R.id.daypreferance);
//String[] dayName = new String[]{
// "sunday", "monday", "tuesday"
//};
MyClass[] dayName ={
new MyClass("sunday", ""),
new MyClass("monday", "2"),
new MyClass("tuesday", "3")
};
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this , R.layout.spinner_items ,R.id.spinneritem,dayName);
adapter.setDropDownViewResource(R.layout.spinner_items);
hotelSelection.setAdapter(adapter);
daySelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
preferDay= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
public void onPause() {
super.onPause();
daySelection = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
prefs.edit().putInt("spinner_indx", daySelection.getSelectedItemPosition()).apply();
}
public void onResume() {
super.onResume();
daySelection = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
int spinnerIndx = prefs.getInt("spinner_indx", 0);
daySelection.setSelection(spinnerIndx);
}
I need to add the code that whenever I restart my app its the selected portion remains as it is I want to know what I can do so that the spinner does not show what I have selected before
try dis and let me know if any error....
daySelection = (Spinner)findViewById(R.id.daypreferance);
//String[] dayName = new String[]{
// "sunday", "monday", "tuesday"
//};
MyClass[] dayName ={
new MyClass("sunday", ""),
new MyClass("monday", "2"),
new MyClass("tuesday", "3")
};
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this , R.layout.spinner_items ,R.id.spinneritem,dayName);
adapter.setDropDownViewResource(R.layout.spinner_items);
hotelSelection.setAdapter(adapter);
daySelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check if preferDay has some valur rhen set on spinner
if(preferDay!=null)
{
daySelection.setSelection(Integer.parseInt(preferDay));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
you can save state of activity and then set those values after came back
check this stack over flow question and this one
Save the state of the spinner in the onPause() method.
#Override
public void onPause() {
super.onPause();
Spinner spinner = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
prefs.edit().putInt("spinner_indx", spinner.getSelectedItemPosition()).apply();
}
Restore the state of the spinner in the onResume() method.
#Override
public void onResume() {
super.onResume();
Spinner spinner = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
int spinnerIndx = prefs.getInt("spinner_indx", 0);
spinner.setSelection(spinnerIndx);
}

Passing values to Activities with putExtra()

I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");

encounter null point exception when using Shared Preference

I have an activity which is working without operating the shared preference. After adding it, got null pointer error after clicking the button.
I think the way I am using shared preference is not correct. Anyone can help point out what is the issue? Should I new() it before using?
public class BanknameActivity extends Activity {
String [] bank_name;
String selected_bank_config;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bankname);
// Show the Up button in the action bar.
// setupActionBar();
bank_name = getResources().getStringArray(R.array.bankname);
ListView lv1 = (ListView) findViewById(R.id.bankname_listview);
lv1.setChoiceMode(1); // CHOICE_MODE_SINGLE
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, bank_name);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
//selected_bank_config = "Citi";
prefs.edit().putString(selected_bank_config, "citi").commit();
return_to_config(view);
}
});
}
Below is part of my code:
public void return_to_config(View view){
Intent intent = new Intent(this, ConfigActivity.class);
startActivity(intent);
this.finish();
}
**you need to initialize your shared Preferences. Without initialization it will always be null.**
yo need to do following stuff:
// mPrefs=getSharedPreferences("Preferences Name",mode);
mPrefs=getSharedPreferences("FBPref",0);
Editor edit=mPrefs.edit();
edit.putString("UserName", "");
edit.putString("UserId","");
edit.putString("EmailId","");
edit.commit();
This code is working fine.
I hope you will appreciate it.

android putextra without start activity

i need help please.
I have two activities and a db. All i want to do is when i press a button in activity A, i send the string in my editText to the activity B. In the activity B i try to insert that string in my db and display it in a listview. All works if i start the activity B in the activity A but i wont display the activity B.
Here my code:
Activity A:
public class Example extends Activity {
public final static String ID_EXTRA2="com.example.activities";
public EditText MyInputText = null;
ImageView MyButton;
TextView MyOutputText, MyInputtext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diccionary);
MyInputText = (EditText)findViewById(R.id.InputText);
MyOutputText = (TextView)findViewById(R.id.OutputText);
MyButton = (ImageView)findViewById(R.id.botonaceptar);
MyButton.setOnClickListener(MyButtonOnClickListener);
public ImageView.OnClickListener MyTranslateButtonOnClickListener = new ImageView.OnClickListener(){
public void onClick(View v) {
String InputString;
InputString = MyInputText.getText().toString();
try{
Intent d = new Intent(Example.this, Secondactivity.class);
d.putExtra(ID_EXTRA2, InputString);
//startActivity(d); <----- If i start the secondactivity, that works...
}catch (Exception e){
}
}
};
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater awesome = getMenuInflater();
awesome.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu1:
startActivity(new Intent("com.example.activities.SECONDACTIVITY"));
return true;
case R.id.menu2:
//something to do
return true;
}
return false;
}
};
Activity B:
public class Secondactivity extends Activity {
NoteAdapter2 adapter = null;
NoteHelper2 helper2 = null;
Cursor dataset_cursor2 = null;
String entriId = null;
public ListView list2;
String passedword = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
try{
list2 = (ListView)findViewById(R.id.list2);
helper2 = new NoteHelper2(this);
---->passedword = getIntent().getStringExtra(Example.ID_EXTRA2);
---->helper2.insert(passedword); //here i insert the string in my db
startManagingCursor(dataset_cursor2);
dataset_cursor2 = helper2.getAll();
adapter = new NoteAdapter2(dataset_cursor2);
list2.setAdapter(adapter);
dataset_cursor2.requery();
adapter.notifyDataSetChanged();
//this is how we know to do when a list item is clicked
list2.setOnItemClickListener(onListClick);
}
catch (Exception e){
// this is the line of code that sends a real error message to the log
Log.e("ERROR", "ERROR IN CODE" + e.toString());
//this is the line that prints out the location in the code where the error ocurred
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
helper2.close();
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
entriId = String.valueOf(id);
}
};
class NoteAdapter2 extends CursorAdapter {
NoteAdapter2(Cursor c){
super(Zhistorytranslate.this, c);
}
public void bindView(View row2, Context ctxt, Cursor c) {
NoteHolder2 holder2 = (NoteHolder2)row2.getTag();
holder2.populateFrom2(c, helper2);
}
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row2 = inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder2 = new NoteHolder2(row2);
row2.setTag(holder2);
return (row2);
}
}
static class NoteHolder2 {
private TextView entriText = null;
NoteHolder2(View row2){
entriText = (TextView)row2.findViewById(R.id.entri);
}
void populateFrom2(Cursor c, NoteHelper2 helper2) {
entriText.setText(helper2.getEntri(c));
}
}
If I understood you correctly, you want to send data from A to B without launching B. In this case, you need to forget about Intents and consider a way to store data in your app. My suggestion is to use SharedPreferences.
Here is how you can use it:
In your Activity A, store the String:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("string_id", InputString); //InputString: from the EditText
editor.commit();
In your Activity B, you can get the value by:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String data = prefs.getString("string_id", "no id"); //no id: default value
Your question is very difficult to understand, but you seem to want to be able to add the EditText's contents into your database without starting another Activity. Simply do this in your Image's OnClickListener:
public void onClick(View v) {
NoteHelper2 helper2 = new NoteHelper2(this);
helper2.insert(MyInputText.getText().toString());
}
You should also read about Java naming convention.

Categories

Resources