encounter null point exception when using Shared Preference - android

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.

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.

Pass Values to ListView by Clicking a Button

I want to pass values to list view by clicking a button. Problem is I want to make a list by gaining values from different activities with several buttons.
For Example :
In EnglandActivity if I click Button Visit I want to pass "England" to ListView in MainActivity,
In MalaysiaActivity pass "Malaysia" to ListView in MainActivity.
I dont know how to do that, Can you help me??
First Of All, You should write this on your onCreate() method of MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String data;/*For Storing Country Name*/
ListView listview = (ListView)findViewById(R.id.listView); /*Finding ListView From Layout*/
ArrayList<String> list = new ArrayList<String>(); /*ArrayList To Store All The Data Of ListView*/
ArrayAdapter adapter= new ArrayAdapter<String>(this,R.layout.android.R.layout.simple_list_item_1,list);/*Defining ArrayAdapter For ListView*/
listview.setAdapter(adapter); /*Setting Adapter To ListView*/
Bundle intentExtras = getIntent().getExtras(); /*Getting The Intent Extras Sent By The Activity Which You Had Navigated From*/
if(intentExtras != null) {/*Checking For Null*/
data= intentExtras.getString("countryName");/*Extracting The Data From The Intent Extras*/
list.add(0,data);/*You Can Replace 0 With The Position Of Your Wish*/
} else {
data=null;
}
}
Now Write This In The OnClickListener() Method Of Button On Each CountryNameActivity.java
btn.setOnClickListener(new OnClickListener() {/*Setting The Click Listener*/
#Override
public void onClick(View v) {
Intent intent = new Intent(this,MainActivity.this)/*Defining The Intent*/
intent.putExtra("countryName","CountryName");/*Putting The Data To Pass To The Next Activity*/
startActivity(intent);/*Starting The Activity*/
}
});
Make an object shared by all of your activity, put your data there and read them when you must put data into your ListView's adapter
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Intent listIntent = new Intent(getApplicationContext(), YourActivity.class);
listIntent.putExtra("country", yourList.get(position));
startActivity(listIntent);
}
});
in next activity onCreate:
String country;
Bundle extras = getIntent().getExtras();
if(extras == null) {
country= null;
} else {
country= extras.getString("country");
}

Trying to Implement shared preferences with a listview

can someone tell me what I am doing wrong here? I'm getting a null pointer exception for my listview... I am trying to use shared preferences to keep the values in my listview when I come back to it
Apologies if its a silly question but from my view everything is initialised and nothing is empty that shouldnt be, so it would be great if someone else could spot the issue :{)
public class MainActivity3 extends MainActivity{
EditText display;
ListView lv;
ArrayAdapter<String> adapter;
Button addButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (EditText) findViewById(R.id.editText5);
lv = (ListView) findViewById(R.id.listView2);
addButton = (Button) findViewById(R.id.button21);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
LoadPreferences();
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (display.getText().toString().equals("")) {
}
else {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", task);
}
}
});
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
}
Apologies if its a silly question but from my view everything is initialised and nothing is empty that shouldnt be, so it would be great if someone else could spot the issue :{)
<ListView
android:layout_width="wrap_content"
android:layout_height="359dp"
android:id="#+id/listView2"
android:layout_alignParentTop="true"
android:layout_toStartOf="#+id/button21"
android:layout_alignRight="#+id/editText6"
android:layout_alignEnd="#+id/editText6" />
Could you put here your layout code?? Because the name of your components are not so good, So, maybe, you can be calling to another listView in another layout.
Could you try to delete your import line when you have android.R ? and then, import the correct.
If this doesn't work, up the code of layout, please :)
I am thinking about another solution. Go to listView and give it this id:
android:id="#android:id/list"
then, Go to MainActivity and write this:
public class YourClass extends ListActivity
So, to access to listView, you just have to use the next method:
getListView();
if you want to know more, see the oficial doc here
I hope It work

Android, refresh listview after click on list item

I have one small problem, after i click on list item, checkbox on item dont change state. Update works perfectly, setChecked maybe, but change will appear after exiting and re-running activity. I read lot of about notifyDataSetChange(), it may work, but not. How can i fix it, like after click on item chechbox value will change.
public class SviatokPridajActivity extends Activity
{
private DatabaseOp mDbHelper;
ListView listview;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sviatok_pridaj);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
listview = (ListView) findViewById(R.id.listSviatok);
showUserSettings();
mDbHelper = new DatabaseOp(this);
mDbHelper.open();
Cursor sviatokCursor = mDbHelper.fetchAllSviatokNastav(username, 3);
if (sviatokCursor.getCount()==0)
{
mDbHelper.naplnSviatky(username);
sviatokCursor = mDbHelper.fetchAllSviatokNastav(username, 3);
}
final SviatokCursorAdapter adapter = new SviatokCursorAdapter(this, sviatokCursor);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int stlpec, long arg3)
{
// TODO Auto-generated method stub
Cursor cur = (Cursor) adapter.getItem(stlpec);
String odosli = cur.getString(cur.getColumnIndex("_id"));
String zobraz = cur.getString(cur.getColumnIndex("dlzka"));
CheckBox check = (CheckBox)findViewById(R.id.checkBox);
if (Integer.parseInt(zobraz)==0)
{
mDbHelper.updateSviatok(odosli, username, 1);
} else {
mDbHelper.updateSviatok(odosli, username, 0);
}
check.setChecked(!check.isChecked());
adapter.notifyDataSetChanged();
}
});
}
#Override
public void onPause()
{
super.onPause();
mDbHelper.close();
}
private void showUserSettings()
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
username = sharedPrefs.getString("prefUsername", "NULL");
}
}
you have checked your CheckBox in itemclick but it's not reflected to your itemList so before calling adapter.notifyDataSetChanged(); you should have to refresh listItems with new changes.
I ve answered this question in this : https://stackoverflow.com/a/22954806/1332870
can you check it? if it does not solve your problem please let me know
Reload your Cursor and instead of adapter.notifyDataSetChanged(); use adapter.changeCursor(reloadedCursor);
Not sure if this is a strain on the main thread but you could just set the adapter again in the on click method.

Passing data in a ordered way to another activity

I have a list of college careers, choosing one of the options takes me to a LinearLayout with multiple spinners, which contain class schedules. What is selected in the spinner, is sent to a "textview1" in the same activity.
My question is what would be the best way to put in another activity, in an ordered way, the information within the "textview1"? And of course be saved there.
I have some example code , using a clickable button that only sends the data, there is another button that allows me to start the another activity when you want to see it, but the problem is to organize the information in the second activity, do I really have to do so many strings? I hope you can help me to find a better way. I also want to say that this application is directed to the 2.1 api, if that matters.
Activity1=Administracion.java
public class Administracion extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.administracion);
final TextView lblMensaje = (TextView)findViewById(R.id.LblMensaje);
final Spinner cmbOpciones = (Spinner)findViewById(R.id.CmbOpciones);
final String[] datos =
new String[]{"0031711 Lab Biologia","Lun-Mar 9:30am prof. Marcarian","Elem3","Elem4","Elem5"};
ArrayAdapter<String> elefante =
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, datos);
elefante.setDropDownViewResource(
R.layout.multiline_spinner_dropdown_item);
cmbOpciones.setAdapter(elefante);
cmbOpciones.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
android.view.View v, int position, long id) {
lblMensaje.setText("Seleccionado: " + datos[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
lblMensaje.setText("");
}
});
final TextView lblMensaje1 = (TextView)findViewById(R.id.LblMensaje1);
final Spinner cmbOpciones1 = (Spinner)findViewById(R.id.CmbOpciones1);
final String cuervo[] =
new String[] {"00311712 Biología I","Mar-Jue 7:00am Prof.Briceño","Elem3","Elem4","Elem5"};
ArrayAdapter<String> adaptador1 =
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cuervo);
adaptador1.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
cmbOpciones1.setAdapter(adaptador1);
cmbOpciones1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
android.view.View v, int position, long id) {
lblMensaje1.setText(cuervo[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
lblMensaje1.setText("");
}
});
Button BotonPasar1;
BotonPasar1 = (Button)findViewById(R.id.VB1);
BotonPasar1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String Aguila;
String Canario;
Aguila = lblMensaje.getText().toString();
Canario = lblMensaje1.getText().toString();
SharedPreferences mypreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mypreferences.edit();
editor.putString("Canario", Aguila);
editor.commit();
SharedPreferences mypreferences1 = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = mypreferences1.edit();
editor1.putString("Canario", Aguila);
editor1.commit();
}
});
Button BotonPasar2;
BotonPasar2 = (Button)findViewById(R.id.VB2);
BotonPasar2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Intent pasarahorario = new Intent("com.reversiblelabs.unisvenecas.udobeta.HORARIO");
startActivity(pasarahorario);
}
});
}
}
Activity 2 = Horario.java
public class Horario extends Activity{
TextView llegada, llegada2, llegada3, llegada4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.horario);
llegada = (TextView) findViewById(R.id.tv1);
llegada2 = (TextView) findViewById(R.id.tv2);
SharedPreferences mypreferences = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences mypreferences1 = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
String teamnamestring = mypreferences.getString("canario", "no_name");
String hola = mypreferences1.getString("Canario","no_name");
llegada.setText(teamnamestring);
llegada2.setText(hola);
Here is the first activity, the last botton send the data on the textwiews to the second activity, and the first button start the second activity.
1st Activity
Whatever you choose on your spinner, would be seen on its own textview.
Now here is the second activity, I want the data to get organized vertically by hours
7:00 9:00 math
9:00 11:00 chemestry
11:00 1:00 extra
2nd Activity
What I can do to acomplish this?
Here is the first activity, the last botton send the data on the
textwiews to the second activity, and the first button start the
second activity.
No need to do this. Only last button can send all the data and as well start the second activity.
Bundle bundle = new Bundle();
bundle.putString("some constant1", value1);
bundle.putString("some constant2", value2);
Intent intent = new Intent (this, newActvity.class);
intent.putExtra(bundle);
startActivity(intent);
Now here is the second activity, I want the data to get organized
vertically by hours
Use RelativeLayout, laydown view one below another and receive bundle in second activity and show them to user.

Categories

Resources