I want to store values in sharedpreferences and getting values from sharedpreferences finally display the values in listview. Next I want to remove values from list when click on longpress on specific value .After removing values status updated in sharedpreferences. i done this one but problem is when close application and open again i have to display sharedpreferences vales in listview. but it display NullPointerExeption,
actually my requirement is 1)storing values in sharedpreferences and display values in listview for every click .allowed only five values.And that list values are available in onresume() method also.
2) when long press on specific value of listview it have to remove and and updated values are stored in sharedpreferences also.
my code
public class ListViewDemo1 extends Activity {
/**
* Called when the activity is first created.
*/
Button btn;
static int count;
private ListView list;
public static ArrayList<String> values = new ArrayList<String>();
ArrayList countList = new ArrayList();
private ArrayAdapter adapter;
SharedPreferences shared;
Editor editor;
private static ArrayList<String> sharedList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(R.id.list);
btn = (Button) findViewById(R.id.btn);
shared = this.getSharedPreferences("Myprefernces", Context.MODE_WORLD_WRITEABLE);
editor = shared.edit();
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
sharedList = new ArrayList();
count++;
if (count == 1) {
values.add("one");
countList.add(count);
}
if (count == 2) {
values.add("two");
countList.add(count);
}
if (count == 3) {
values.add("three");
countList.add(count);
}
if (count == 4) {
values.add("four");
countList.add(count);
}
if (count == 5) {
values.add("five");
countList.add(count);
}
if (count > 5) {
--count;
Toast.makeText(getApplicationContext(), "" + count, 100).show();
}
//put values to sharedpreferences
editor.putInt("SIZE", values.size());
for (int i = 0; i < values.size(); i++) {
editor.putString("addr" + i, values.get(i));
}
editor.commit();
// getting values from sharedpreference
int size = shared.getInt("SIZE", 0);
for (int k = 0; k < size; k++) {
sharedList.add(shared.getString("addr" + k, ""));
}
adapter = new
ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
list.setAdapter(adapter);
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
--count;
values.remove(arg2);
sharedList.remove(arg2);
editor.clear();
editor.commit();
editor.putInt("SIZE", sharedList.size());
for (int i = 0; i < sharedList.size(); i++) {
editor.putString("addr" + i, sharedList.get(i));
}
editor.commit();
adapter.notifyDataSetChanged();
return true;
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (sharedList.size() > 0) {
adapter = new
ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
list.setAdapter(adapter);
}
}
}
Logcat
04-21 09:56:02.142: E/AndroidRuntime(1160): FATAL EXCEPTION: main
04-21 09:56:02.142: E/AndroidRuntime(1160): java.lang.RuntimeException: Unable to resume activity {com.views/com.views.ListViewDemo1}: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.os.Looper.loop(Looper.java:137)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-21 09:56:02.142: E/AndroidRuntime(1160): at java.lang.reflect.Method.invokeNative(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160): at java.lang.reflect.Method.invoke(Method.java:511)
04-21 09:56:02.142: E/AndroidRuntime(1160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-21 09:56:02.142: E/AndroidRuntime(1160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-21 09:56:02.142: E/AndroidRuntime(1160): at dalvik.system.NativeStart.main(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160): Caused by: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160): at com.views.ListViewDemo1.onResume(ListViewDemo1.java:114)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)
You instantiate sharedList only in onClick() method of a button. This method is not called when your activity is resumed and sharedList is null.
You need to check if it's not null:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(sharedList != null && sharedList.size()>0){
adapter=new ArrayAdapter(ListViewDemo1.this,android.R.layout.simple_list_item_1,sharedList);
list.setAdapter(adapter);
}
}
The problem i think is with initialization(or rather not doing that),
static int count;
public static ArrayList<String> values = new ArrayList<String>();
private static ArrayList<String> sharedList;
Now for eg, not initialized count to a value before:
count++;
if(count==1){
Same needs to be done for sharedList, like new ArrayList...
And yes, the reason being onCreate() is not called before onResume() every time, for more on the refer Android Activity Life Cycle
Check Figure 1. The activity lifecycle. on that link.
It will give you a better idea for your implementation/requirement and how to initialize or work with sharedPref and other components for your activity.
read this I hope help you http://developer.android.com/guide/topics/data/data-storage.html
You can use SharedPreferences:
To save data:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
To retrieve data:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
Related
I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)
Building on a theme from yesterday...I'm getting an NPE accessing a method in a singleton Application class from within an AlertDialog.
Activity SavedMealsActivity sets OnLongClickListenerSavedMeals as the listener for a series of TextViews in a ScrollView. OnLongClickListenerSavedMeals is defined as a separate class.
OnLongClickListenerSavedMeals displays an AlertDialog which gives the option of going to a different Activity, but it first needs to fire the methods of an Application class which is defined as a singleton (MealTimerApplication). This is the first line of the onClick method (line 25 in the first code sample below), and it throws the NPE because the activity is null at the time.
I've tried passing in the activity from the calling Activity (SavedMealsActivity) but for some reason it's not working as I'd hoped. Any ideas?
OnLongClick listener class - OnLongClickListenerSavedMeals:
public class OnLongClickListenerSavedMeals implements OnLongClickListener {
Context context;
String id;
private Activity activity;
public OnLongClickListenerSavedMeals(Activity activity) {
this.activity = activity;
this.context = activity;
}
#Override
public boolean onLongClick(View view){
// TODO Auto-generated method stub
this.context = context;
id = view.getTag().toString();
final CharSequence[] items = { "Edit", "Delete" };
//Set activity to allow context to be used in the OnClickListener/onClick method below
this.activity = activity;
new AlertDialog.Builder(context).setTitle("Meal Item")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
//Set the global meal_id variable and invoke the MealActivity
((MealTimerApplication) activity.getApplication()).setMealId(Long.getLong(id));
Intent myIntent = new Intent(activity.getBaseContext(),MealActivity.class);
activity.startActivityForResult(myIntent, 0);
}
else if (item == 1) {
boolean deleteSuccessful = new TableControllerMeal(context).delete(id);
if (deleteSuccessful){
Toast.makeText(context, "Record was deleted.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to delete record.", Toast.LENGTH_SHORT).show();
}
((SavedMealsActivity) context).readRecords();
}
dialog.dismiss();
}
}).show();
return false;
}
Calling Activity - SavedMealsActivity:
public class SavedMealsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_meals);
//Read saved meal records from the database and display them
readRecords();
}
public void readRecords() {
LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<meal> meal = new TableControllerMeal(this).read();
if (meal.size() > 0) {
for (meal obj : meal) {
long id = obj.id;
String MealDesc = obj.meal_desc;
int MealMinutes = obj.meal_ready_time;
String textViewContents = MealDesc + " - ready at "
+ Utilities.formatTime(MealMinutes);
TextView textViewItem = new TextView(this);
textViewItem.setPadding(0, 10, 0, 10);
textViewItem.setText(textViewContents);
textViewItem.setTag(Long.toString(id));
textViewItem.setOnLongClickListener(new OnLongClickListenerSavedMeals(this));
linearLayoutRecords.addView(textViewItem);
}
}
else {
TextView Item = new TextView(this);
Item.setPadding(8, 8, 8, 8);
Item.setText("No records yet.");
linearLayoutRecords.addView(Item);
}
}
Application class:
public class MealTimerApplication extends Application {
private static MealTimerApplication singleton;
private long mealId = 0;
// Returns the application instance
public static MealTimerApplication getInstance() {
return singleton;
}
public final void onCreate() {
super.onCreate();
singleton = this;
}
public void setMealId(long mealId) {
this.mealId = mealId;
}
public long getMealId() {
return this.mealId;
}
}
Logcat:
05-28 16:48:03.637: E/AndroidRuntime(4241): java.lang.NullPointerException
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.ian.mealtimer.OnLongClickListenerSavedMeals$1.onClick(OnLongClickListenerSavedMeals.java:39)
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView$3.run(AbsListView.java:3638)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Handler.handleCallback(Handler.java:733)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Handler.dispatchMessage(Handler.java:95)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Looper.loop(Looper.java:136)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-28 16:48:03.637: E/AndroidRuntime(4241): at java.lang.reflect.Method.invokeNative(Native Method)
05-28 16:48:03.637: E/AndroidRuntime(4241): at java.lang.reflect.Method.invoke(Method.java:515)
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-28 16:48:03.637: E/AndroidRuntime(4241): at dalvik.system.NativeStart.main(Native Method)
You get NPE because of autoboxing. Long.getLong(String) is not what you actually you need, check its description:
Returns the Long value of the system property identified by string.
It definitely returns null in your case. Moreover it returns null reference to Long object, but your MealTimerApplication.setMealId expects argument with primitive type long. Here is the point where auto-boxing implicitly trying to cast your Long object returned by getLong method to the long primitive. But as value was null auto-boxing fails and you get NPE.
You should just use Long.valueOf(String) instead of Long.getLong(String).
I am very new to android. I have a counter on some SomeActivity, but when I get to the page corresponding to SomeActivity, my app crashes :
final TextView counter = (TextView) findViewById(R.id.laws_counter);
ImageView handDown = (ImageView) findViewById(R.id.handViewDown);
counter.setText("" + 0);
I want that on click of the handown, the counter is idented by -1. Here's
handDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewsActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
setDown();
}
private void setDown() {
String count = counter.getText().toString();
int now_count = Integer.parseInt(count) +1;
counter.setText(String.valueOf(now_count));
}
});
Is this code correct ?
Update : here's the logcat
10-22 00:18:05.579: ERROR/AndroidRuntime(378): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donnfelker.android.bootstrap/com.donnfelker.android.bootstrap.ui.NewsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donnfelker.android.bootstrap.ui.NewsActivity.onCreate(NewsActivity.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
There are many ways that you can implement that functionality but think this would be an easy solution.
Make a helper method:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
Then simply call the putInt method to save the counter in any Activity and getInt to get it again in any other Activity. As long as you use the same key both places.
am new to android ,I juz wanna know how to make like when i click button1, then button2 the text view will show 1 2,,, but if I clicked button2 then button1 it will show 2 1
this is my codes but now when I click button1 then button2, or if i clicked button2 then button1 it shows the same,,
plz help me
thanx.
now I did it using the getText & setText its working as I wanted but the condition if its correct or not is not working plz help !! what is wrong with it and is my method correct?
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.wordgame2);
bu1 = (Button) findViewById(R.id.bu1);
bu2 = (Button) findViewById(R.id.bu2);
bu3 = (Button) findViewById(R.id.bu3);
bu4 = (Button) findViewById(R.id.bu4);
bu5 = (Button) findViewById(R.id.bu5);
t1 = (TextView) findViewById(R.id.t1);
i1 = (ImageView) findViewById(R.id.i1);
i2 = (ImageView) findViewById(R.id.i2);
bu1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu1.getText());
}
});
bu2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu2.getText());
}
});
bu3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu3.getText());
}
});
bu4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu4.getText());
}
});
bu5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(t1.getText().toString().equals("a b c d")) //this is not working
{
i1.setVisibility(View.VISIBLE);
i2.setVisibility(View.INVISIBLE);
}
else {
i2.setVisibility(View.VISIBLE);
i1.setVisibility(View.INVISIBLE);
}
}
});
}
04-21 07:00:48.690: E/AndroidRuntime(23874): FATAL EXCEPTION: main
04-21 07:00:48.690: E/AndroidRuntime(23874): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arabicalphabets.reham/com.arabicalphabets.reham.Wordgame2}: java.lang.NullPointerException
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.access$600(ActivityThread.java:127)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.os.Looper.loop(Looper.java:137)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.main(ActivityThread.java:4512)
04-21 07:00:48.690: E/AndroidRuntime(23874): at java.lang.reflect.Method.invokeNative(Native Method)
04-21 07:00:48.690: E/AndroidRuntime(23874): at java.lang.reflect.Method.invoke(Method.java:511)
04-21 07:00:48.690: E/AndroidRuntime(23874): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
04-21 07:00:48.690: E/AndroidRuntime(23874): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
04-21 07:00:48.690: E/AndroidRuntime(23874): at dalvik.system.NativeStart.main(Native Method)
04-21 07:00:48.690: E/AndroidRuntime(23874): Caused by: java.lang.NullPointerException
04-21 07:00:48.690: E/AndroidRuntime(23874): at com.arabicalphabets.reham.Wordgame2.onCreate(Wordgame2.java:36)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.Activity.performCreate(Activity.java:4465)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
04-21 07:00:48.690: E/AndroidRuntime(23874): ... 11 more
first instead of declaring each button individually use looping to declare them...
Button[] buttons;
for(int i=0; i<5; i++) { //for your 5 buttons
{
String buttonID = "bu" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
}
-using switch() find the clicked button...
-and as cases implement the onclick() as below
public void onClick(View v) {
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
}
hope it works
I cant see what is wrong with it and why its crashing and why the if else statement isn't working...??
public class Wordgame2 extends Activity implements OnClickListener {
Button[] buttons;
TextView t1;
ImageView i1, i2;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.wordgame2);
for(int i=0; i<5; i++) {
{
String buttonID = "bu" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
buttons[i].setOnClickListener(this);
}
}
t1 = (TextView) findViewById(R.id.t1);
i1 = (ImageView) findViewById(R.id.i1);
i2 = (ImageView) findViewById(R.id.i2);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bu1:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
case R.id.bu2:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
case R.id.bu3:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
case R.id.bu4:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
//when they click bu5 if t1 is correct as "a b c d" it will show picture
case R.id.bu5:
if(t1.getText().toString().equals("a b c d")) //this is not working
{
i1.setVisibility(View.VISIBLE);
i2.setVisibility(View.INVISIBLE);
}
else {
i2.setVisibility(View.VISIBLE);
i1.setVisibility(View.INVISIBLE);
}
break;
}
}
}