The SharedPreferences code was no function to make button Visible - java

First time i had done coding without preferences the button can visible but when i put preferences code the button not visible
i have 3 class it is menu.class, levelone.class, leveltwo.class
this is the following code of menu.class like this
public class menu extends Activity {
Button f1, f2;
ImageView f2lock;
boolean levelTwoUnlocked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.famouslevel);
f1 =(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level1 = new Intent ();
level1.setClassName ("com.example.game", "com.example.game.levelone");
startActivityForResult (level1, 0);
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent level1) {
super.onActivityResult (requestCode, resultCode, level1);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
switch (resultCode) {
case 2: SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
}
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level2 = new Intent ();
level2.setClassName ("com.example.game", "com.example.game.leveltwo");
startActivityForResult (level2, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splashscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and in levelone.class i have put this code
public void onClick(View v){
setResult (2);
finish();
}
});
thats code is to make button visible in menu.class but when levelone.class finish(); is nothing happen with the button, it's still GONE
f2 button function is to open leveltwo.class and in leveltwo.class had same code to set f3 button visible
public void onClick(View v){
setResult (3);
finish();
}
});
and so on with the next level had a same code to make button visible
Did my code setResult is wrong or the preferences code make it not function?

Int the lines:
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
You just put always false to "f2", because levelTwoUnlocked is always false.

Assign a boolean value to leveTwoUnloacked
or
make changes in
editor.putBoolean("f2",true);
and check
if(prefernces.getBoolean("f2",false))
{
//your code
}

Related

How to show captured Image onto new Activity?

When I click a Button it opens the camera and when I save it, it saves into the gallery. I want to display that picture in a new activity as an ImageView.
This is the code I have for the camera button click
btn2 =(Button)findViewById(R.id.drawer_two);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent upload = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(upload);
}
}
Your Main Activity
public class MainActivity extends ActionBarActivity {
private final int requestCode = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",bitmap);
startActivity(in1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
on Your Activity2 write this code on onCreate method
Bundle ex = getIntent().getExtras();
Bitmap bmp2 = ex.getParceable("image");
ImageView result = (ImageView)findViewById(R.Id.imageView1);
result.setImageBitmap(bmp);
use startActivityForResult() for firing Image upload screen and use onActivityResult() to get the image data back and to display it in ImageView
Refer this

The code was not function if SharedPreferences put in there

Hy guys i have a problem with my code, if i put SharedPreferences my code not function
i will explain with my following code
this is menu.class
public class menu extends Activity {
Button f1, f2;
ImageView f2lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.famouslevel);
f1 =(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level1 = new Intent ();
level1.setClassName ("com.example.game", "com.example.game.levelone");
startActivityForResult (level1, 0);
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent level1){
super.onActivityResult (requestCode, resultCode, level1);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
switch (resultCode) {
case 2: f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level2 = new Intent ();
level2.setClassName ("com.example.game", "com.example.game.leveltwo");
startActivityForResult (level2, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splashscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
if i use this code
switch (resultCode) {
case 2: f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
The code was running perfect, the f2 button in menu.xml is show up to VISIBLE and f2lock GONE but of course without SharedPreferences it won't save.
So if I change the code and put SharedPreferences like this:
switch (resultCode) {
case 2:
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
}
The f2 button in menu.xml does not turn VISIBLE, it is still GONE. Yhe code does not function to make f2 button VISIBLE and f2lock GONE.
Can anyone help me with this code?
UPDATED
i have changed my code again
switch (resultCode) {
case 2:
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
//to make f2 VISIBLE and f2lock GONE
boolean levelTwoUnlocked = preferences.getBoolean("f2", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
}
still have the same problem, f2 won't setVisibility(View.VISIBLE)
Actually I don't understand well what you're trying to do, but mistake is you never toggle your boolean levelTwoUnlocked. So don't mind how many times you enter in the if, the route will be always the same (I bet levelTwoUnlocked=false because is default Java boolean value):
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
levelTwoUnlocked = false;
} else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
levelTwoUnlocked = true;
}

App crashing when saving to shared preferences

I am trying to save to shared preferences. I want to be able to load from shared preferences but when I save and or load at the moment my app crashes.
I also want to be able to have my handler/runnable resume when my app starts up. How can I do this?
Here is my code:
public class MainActivity extends ActionBarActivity {
public void save(){
Editor editor = pref.edit();
editor.putInt("countertest", counter);
editor.commit();
}//end of save
public void read(){
counter = pref.getInt("countertest", counter);
}//end of read
Handler testHandler = new Handler();
int counter;
TextView testView;
Button testButton;
Runnable Runnable0;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testView = (TextView) findViewById(R.id.testView);
testButton = (Button) this.findViewById(R.id.testButton);
// read();
testView.setText(Integer.toString(counter));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
//read();
final Runnable Runnable0 = new Runnable() {
#Override
public void run() {
counter += 1;
testView.setText(Integer.toString(counter));
testHandler.postDelayed(this, 1000);
// save();
}// end of if
};
/* button click */
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Start runnable */
testButton.setEnabled(false);
counter -= 5;
//save();
testView.setText(Integer.toString(counter));
testHandler.post(Runnable0);
}// end of onClick
});// end of blingButton onClickListener
super.onResume();
}//end of onResume
#Override
protected void onPause() {
//save();
testHandler.removeCallbacks(Runnable0);
super.onPause();
}//end of onPause
}
You haven't initialize your pref object. You have just declared it. So you need to do it on onCreate() by
pref = getSharedPreferences("MySP", 0);
OR
pref = PreferenceManager.getDefaultSharedPreferences(this);

Same activity getting stacked

I have an activity that is suppose to finish itself and close the application. Now, in certain cases, which are varying on how the user is navigating to the activity, the activity is getting stacked. When the activity is stacking up, then calling finish() or android.os.Process.killProcess(android.os.Process.myPid()); or both together is only showing up the same activity again.
The Manifest:
<activity
android:name="newActivities.HomeActivity"
android:label="#string/title_activity_home"
android:screenOrientation="portrait">
</activity>
The activity:
public class HomeActivity extends Activity {
private EditText studentNameEdittext;
private Button startYourStoryButton, loginButton, navCollegesButton, settingsButton, search_friends_button, browseStoriesButton;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// saveInPreference("loginStatus", "");
// }
// Set up the action bar
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#009945")));
bar.setTitle("Study Story");
bar.setIcon(R.drawable.statusbar_icon);
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.white_colour));
yourTextView.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// studentNameEdittext = (EditText)
// findViewById(R.id.studentNameEdittext);
startYourStoryButton = (Button) findViewById(R.id.startYourStoryButton);
// loginButton = (Button) findViewById(R.id.loginButton);
navCollegesButton = (Button) findViewById(R.id.navCollegesButton);
// settingsButton = (Button) findViewById(R.id.settingsButton);
// search_friends_button = (Button)
// findViewById(R.id.search_friends_button);
browseStoriesButton = (Button) findViewById(R.id.browseStoriesButton);
// textView1 = (TextView) findViewById(R.id.textView1);
// Set up font type
// studentNameEdittext.setTypeface(TypeFaceController.generalTextFace(HomeActivity.this));
startYourStoryButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// loginButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
navCollegesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// settingsButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// search_friends_button.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
browseStoriesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// textView1.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
startYourStoryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(HomeActivity.this, SignUp.class);
i.putExtra("signUpCaller", "Home");
startActivity(i);
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View arg0){
// Intent i = new Intent(HomeActivity.this, Login.class);
// startActivity(i);
// }
// });
// search_friends_button.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this,
// FindStudentBrowseStoryActivity.class);
// i.putExtra("Button", "search_friends_button");
// i.putExtra("searchString", studentNameEdittext.getText().toString());
// startActivity(i);
//
// }
// });
browseStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, FindStudentBrowseStoryActivity.class);
i.putExtra("Button", "browseStoriesButton");
startActivity(i);
}
});
navCollegesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, CollegeListActivity.class);
startActivity(i);
}
});
// settingsButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this, HomeSettingsActivity.class);
// i.putExtra("FromActivity", "HomeSettingsActivity");
// startActivity(i);
// finish();
//
// }
// });
}
// #Override
// protected void onStart(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onStart();
// }
//
// #Override
// protected void onResume(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onResume();
// }
// =========Login button action bar
#Override
public boolean onCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_menu, menu);
return true;
}
// =========Login button action bar
#Override
public boolean onOptionsItemSelected(MenuItem item){
// handle item selection
switch (item.getItemId()) {
case R.id.home_login_string:
Intent i = new Intent(HomeActivity.this, Login.class);
// finish();
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// logic to fix logout
#Override
public void onBackPressed(){
// Intent startMain = new Intent(Intent.ACTION_MAIN);
// startMain.addCategory(Intent.CATEGORY_HOME);
// startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);;
// startActivity(startMain);
//
// int pid = android.os.Process.myPid(); //
// android.os.Process.killProcess(pid); // return; }
android.os.Process.killProcess(android.os.Process.myPid());
finish();
}
// method to save variable in preference
public void saveInPreference(String name, String content){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(name, content);
editor.commit();
}
// getting content from preferences
public String getFromPreference(String variable_name){
String preference_return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preference_return = preferences.getString(variable_name, "");
return preference_return;
}
}
Please tell me where am I going wrong? Why is the activity stacking?
P.S: We cannot use single top etc as it causes some transition issues with the existing custom theme!
Take one application class which extends Application and take one arrayList and maintain the references of the activities in the arraylist.
When you click on back button in desired activity then finish the all the activities using arraylist.
Take one base activity. Which is super class of all the activities
public class BaseActviity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App application = (App) getApplication();
application.addActivity(this);
}
}
Take one application class
public class App extends Application {
public App() {
if (listActivty == null) {
listActivty = new ArrayList<BaseActviity>();
}
}
public ArrayList<BaseActviity> listActivty;
public void addActivity(BaseActviity actviity) {
if (!listActivty.contains(actviity)) {
listActivty.add(actviity);
}
}
}
take 4 samples activity classes like ......
1) public class FirstActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
2) public class SecondActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
}
3).........................
4) ............................
in 4 th activity class placed the following code
In desire activity that means final activity,override the onBackPressed
public void onBackPressed() {
super.onBackPressed();
App application = (App) getApplication();
ArrayList<BaseActviity> listActivty = application.listActivty;
for (BaseActviity actviity : listActivty) {
actviity.finish();
}
}
Wherever you are opening the activity which is getting stacked up, use this:
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Check if the Activity, that would be last activity when user clicks on the back button,is visible or not and if visible use
System.exit(0);
At last, the problem is solved. I has to do a little trick:
ParseUser.getCurrentUser();
ParseUser.logOut();
Intent i = new Intent(getActivity(), NewHomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().startActivity(i);
getActivity().finish();
This did not cause any transition issues as well.

eclipse android application syntax error

i just started to use eclipse, and im trying to do my first android application. But apparently something is wrong with my syntax error , and i dont know how can i fix it or where did i do wrongly. so i hope someone here can help me. Thanks :) pardon me for my bad english.
Those underlined in red are errors but i dont know how can i fix them.
starts below here
Here is my .java
public class Category extends Activity { <---(**this sign is underlined in red**)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
Button switchButton = (Button) findViewById(R.id.button1);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cake.class);
startActivity(intent);
Button switchButton = (Button) findViewById(R.id.button2);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cookie.class);
startActivity(intent);
};
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} ^
(**this sign is underlined in red**)
};
Unfortunately you're trying to initialize your button listener in another button listener. That's wrong.
Corrected:
Button switchButton = (Button) findViewById(R.id.button1);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cake.class);
startActivity(intent);
};
});
Button switchButton2 = (Button) findViewById(R.id.button2);
switchButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cookie.class);
startActivity(intent);
};
});

Categories

Resources