restoring the edittext field on clicking back button - android

public class MainActivity extends Activity implements SurfaceHolder.Callback {
EditText , PatientInfo,PatientAge,PatientId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
Button buttonCapturePreview = (Button) findViewById(R.id.Capturecamerapreview);
rgGender = (RadioGroup) findViewById(R.id.rgGender);
rdbMale = (RadioButton) findViewById(R.id.rdbMale);
rdbFemale = (RadioButton) findViewById(R.id.rdbFemale);
PatientInfo = (EditText) findViewById(R.id.PatientName);
PatientInfo.setHint("enter patient name");
PatientAge = (EditText) findViewById(R.id.Age);
PatientAge.setHint("Age");
PatientId = (EditText) findViewById(R.id.PatientId);
PatientId.setHint("PatientId");
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this)
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
loadInput();
int imageNum = 0;
String Name = PatientInfo.getText().toString();
String Age = PatientAge.getText().toString();
String Id = PatientId.getText().toString();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
Rname = s.toString() +".jpg";
File imagesFolders = new File(Environment.getExternalStorageDirectory().toString() + "/" + Name + Age + gender + Id);
imagesFolders.mkdirs();
File output = new File(imagesFolders, Rname);
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(MainActivity.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
{
........
}
buttonCapturePreview.setOnClickListener(new OnClickListener()
{...}
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
......}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.rdbMale:
if (checked)
gender= "M";
gender1="M";
rdbFemale.setChecked(false);
break;
case R.id.rdbFemale:
if (checked)
gender = "F";
gender1="F";
rdbMale.setChecked(false);
break;
}
}
Button backButton = (Button) findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
saveInput();
startActivity(intent);
}
});
}
protected void saveInput()
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().putString("Name",PatientInfo.getText().toString()).commit();
preferences.edit().putString("Age", PatientAge.getText().toString()).commit();
preferences.edit().putString("Id",PatientId.getText().toString()).commit();
}
private void loadInput(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedTextN = preferences.getString("Name", null);
String savedTextA = preferences.getString("Age", null);
String savedTextI = preferences.getString("Id", null);
PatientInfo.setText(savedTextN);
PatientAge.setText(savedTextA);
PatientId.setText(savedTextI);
System.out.println(savedTextN);
System.out.println(savedTextA);
System.out.println(savedTextI);
}
i am trying to load the same data that i entered in my first activity. On button click the data is lodt. So i used shared preferences. But am using it first time so there is something wrong in my code. I just tried to load one of the edittext. Anyone can point out whats the mistake

You are doing it wrong. the wrong things are
to just restoring a data you are trying to restart the whole activity.
you are calling the onResume method by yourself..
Dont do these . you can do it easily by following.
create a method which will do the initial data setting tasks for your.
in onResume of you method (or in oncreate ) call that method
whenever you want to reset data (i.e after back button pressed) call that method.

You are wrongly getting the data from your preferences with the Wrong key.
As you are storing the value in preferences with the key Name in your onResume method and in your loadInput method you are trying to fetch it with the PatientInfo key which is not available in your preferences.
Change your loadInput method as below:
private void loadInput(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedText = preferences.getString("Name");
PatientInfo.setText(savedText);
}
As the onResume method always gets called before the onCreate so you need to initialize your PatientInfo view in your onResume method and then try to store its value into the Preferences.

Related

How to open a file in android app?

I am trying to make an app that can open a file from the phone's directory. I will be opening .ddd files but would like to be able to open any file type. I know intents can be used. I have tried this but at the moment it just opens goes into the file selection but doesn't open the file.
import java.io.File;
import java.io.Serializable;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import ar.com.daidalos.afiledialog.*;
public class AFileDialogTestingActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Assign behaviors to the buttons.
Button buttonActivity1 = (Button)this.findViewById(R.id.activity_simple_open);
buttonActivity1.setOnClickListener(btnActivitySimpleOpen);
Button buttonActivity2 = (Button)this.findViewById(R.id.activity_open_downloads);
buttonActivity2.setOnClickListener(btnActivityOpenDownloads);
Button buttonActivity3 = (Button)this.findViewById(R.id.activity_select_folders);
buttonActivity3.setOnClickListener(btnActivitySelectFolders);
Button buttonActivity4 = (Button)this.findViewById(R.id.activity_create_files);
buttonActivity4.setOnClickListener(btnActivityCreateFiles);
Button buttonActivity5 = (Button)this.findViewById(R.id.activity_select_images);
buttonActivity5.setOnClickListener(btnActivitySelectImages);
Button buttonActivity6 = (Button)this.findViewById(R.id.activity_ask_confirmation);
buttonActivity6.setOnClickListener(btnActivityAskConfirmation);
Button buttonActivity7 = (Button)this.findViewById(R.id.activity_custom_labels);
buttonActivity7.setOnClickListener(btnActivityCustomLabels);
Button buttonDialog1 = (Button)this.findViewById(R.id.dialog_simple_open);
buttonDialog1.setOnClickListener(btnDialogSimpleOpen);
Button buttonDialog2 = (Button)this.findViewById(R.id.dialog_open_downloads);
buttonDialog2.setOnClickListener(btnDialogOpenDownloads);
Button buttonDialog3 = (Button)this.findViewById(R.id.dialog_select_folders);
buttonDialog3.setOnClickListener(btnDialogSelectFolders);
Button buttonDialog4 = (Button)this.findViewById(R.id.dialog_create_files);
buttonDialog4.setOnClickListener(btnDialogCreateFiles);
Button buttonDialog5 = (Button)this.findViewById(R.id.dialog_select_images);
buttonDialog5.setOnClickListener(btnDialogSelectImages);
Button buttonDialog6 = (Button)this.findViewById(R.id.dialog_ask_confirmation);
buttonDialog6.setOnClickListener(btnDialogAskConfirmation);
Button buttonDialog7 = (Button)this.findViewById(R.id.dialog_custom_labels);
buttonDialog7.setOnClickListener(btnDialogCustomLabels);
}
// ----- Buttons for open a dialog ----- //
private OnClickListener btnDialogSimpleOpen = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogOpenDownloads = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Define start folder.
dialog.loadFolder(Environment.getExternalStorageDirectory() + "/Download/");
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogSelectFolders = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the folder mode.
dialog.setFolderMode(true);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogCreateFiles = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the button for create files.
dialog.setCanCreateFiles(true);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogSelectImages = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Define the filter for select images.
dialog.setFilter(".*jpg|.*png|.*gif|.*JPG|.*PNG|.*GIF");
dialog.setShowOnlySelectable(false);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogAskConfirmation = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the button for create files.
dialog.setCanCreateFiles(true);
// Activate the confirmation dialogs.
dialog.setShowConfirmation(true, true);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogCustomLabels = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the folder mode.
dialog.setFolderMode(true);
// Activate the button for create files.
dialog.setCanCreateFiles(true);
// Activate the confirmation dialogs.
dialog.setShowConfirmation(true, true);
// Define the labels.
FileChooserLabels labels = new FileChooserLabels();
labels.createFileDialogAcceptButton = "AcceptButton";
labels.createFileDialogCancelButton = "CancelButton";
labels.createFileDialogMessage = "DialogMessage";
labels.createFileDialogTitle = "DialogTitle";
labels.labelAddButton = "AddButton";
labels.labelSelectButton = "SelectButton";
labels.messageConfirmCreation = "messageConfirmCreation";
labels.messageConfirmSelection = "messageConfirmSelection";
labels.labelConfirmYesButton = "yesButton";
labels.labelConfirmNoButton = "noButton";
dialog.setLabels(labels);
// Show the dialog.
dialog.show();
}
};
// ---- Buttons for open an activity ----- //
private OnClickListener btnActivitySimpleOpen = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityOpenDownloads = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Define start folder.
intent.putExtra(FileChooserActivity.INPUT_START_FOLDER, Environment.getExternalStorageDirectory() + "/Download/");
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivitySelectFolders = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the folder mode.
intent.putExtra(FileChooserActivity.INPUT_FOLDER_MODE, true);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityCreateFiles = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the button for create files.
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivitySelectImages = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Define the filter for select images.
intent.putExtra(FileChooserActivity.INPUT_REGEX_FILTER, ".*jpg|.*png|.*gif|.*JPG|.*PNG|.*GIF");
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityAskConfirmation = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the button for create files.
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
// Activate the confirmation dialogs.
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_CREATE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_SELECT, true);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityCustomLabels = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the folder mode.
intent.putExtra(FileChooserActivity.INPUT_FOLDER_MODE, true);
// Activate the button for create files.
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
// Activate the confirmation dialogs.
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_CREATE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_SELECT, true);
// Define the labels.
FileChooserLabels labels = new FileChooserLabels();
labels.createFileDialogAcceptButton = "AcceptButton";
labels.createFileDialogCancelButton = "CancelButton";
labels.createFileDialogMessage = "DialogMessage";
labels.createFileDialogTitle = "DialogTitle";
labels.labelAddButton = "AddButton";
labels.labelSelectButton = "SelectButton";
labels.messageConfirmCreation = "messageConfirmCreation";
labels.messageConfirmSelection = "messageConfirmSelection";
labels.labelConfirmYesButton = "yesButton";
labels.labelConfirmNoButton = "noButton";
intent.putExtra(FileChooserActivity.INPUT_LABELS, (Serializable) labels);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener clickButtonOpenActivity = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
intent.putExtra(FileChooserActivity.INPUT_REGEX_FILTER, ".*pdf|.*jpg|.*png|.*mp3|.*mp4|.*avi");
intent.putExtra(FileChooserActivity.INPUT_SHOW_ONLY_SELECTABLE, true);
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
intent.putExtra(FileChooserActivity.INPUT_FOLDER_MODE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_CREATE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_SELECT, true);
// Define labels.
FileChooserLabels labels = new FileChooserLabels();
labels.createFileDialogAcceptButton = "AcceptButton";
labels.createFileDialogCancelButton = "CancelButton";
labels.createFileDialogMessage = "DialogMessage";
labels.createFileDialogTitle = "DialogTitle";
labels.labelAddButton = "AddButton";
labels.labelSelectButton = "SelectButton";
labels.messageConfirmCreation = "messageConfirmCreation";
labels.messageConfirmSelection = "messageConfirmSelection";
labels.labelConfirmYesButton = "yesButton";
labels.labelConfirmNoButton = "noButton";
intent.putExtra(FileChooserActivity.INPUT_LABELS, (Serializable) labels);
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
// ---- Methods for display the results ----- //
private FileChooserDialog.OnFileSelectedListener onFileSelectedListener = new FileChooserDialog.OnFileSelectedListener() {
public void onFileSelected(Dialog source, File file) {
source.hide();
Toast toast = Toast.makeText(AFileDialogTestingActivity.this, "File selected: " + file.getName(), Toast.LENGTH_LONG);
toast.show();
}
public void onFileSelected(Dialog source, File folder, String name) {
source.hide();
Toast toast = Toast.makeText(AFileDialogTestingActivity.this, "File created: " + folder.getName() + "/" + name, Toast.LENGTH_LONG);
toast.show();
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
boolean fileCreated = false;
String filePath = "";
Bundle bundle = data.getExtras();
if(bundle != null)
{
if(bundle.containsKey(FileChooserActivity.OUTPUT_NEW_FILE_NAME)) {
fileCreated = true;
File folder = (File) bundle.get(FileChooserActivity.OUTPUT_FILE_OBJECT);
String name = bundle.getString(FileChooserActivity.OUTPUT_NEW_FILE_NAME);
filePath = folder.getAbsolutePath() + "/" + name;
} else {
fileCreated = false;
File file = (File) bundle.get(FileChooserActivity.OUTPUT_FILE_OBJECT);
filePath = file.getAbsolutePath();
}
}
String message = fileCreated? "File created" : "File opened";
message += ": " + filePath;
Toast toast = Toast.makeText(AFileDialogTestingActivity.this, message, Toast.LENGTH_LONG);
toast.show();
}
}
}
This is how I would do it. You also should be sure to include <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in the AndroidManifest
xml file
Button
android:id="#+id/FileButtonOrWhatever"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="GetFiles"
java file
public void GetFiles(View view) {
// get the files directory
File lister = this.getFilesDir();
FileInputStream inputStream = null;
byte[] bytes = new byte[500];
int fileIdx = -1;
for (String list : lister.list()){
fileIdx++;
if(list.endsWith("ddd")){
File file = lister.listFiles()[fileIdx];
try {
inputStream = new FileInputStream(file);
bytes = new byte[inputStream.available()];
inputStream.read(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();}
finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}

Issues With login/regstration

*UPDATED*still haveing issues please if you see any errors please let me know, i would like to put my logcat in but i cant access it due to the errors .......I'm having issues with my login and registration mechanism. I'm probably doing something wrong, but when i try to test out the login my app crashes with the message "...has suddenly stopped." msg. Also, my textview that goes to my registration class isnt responding. Can some please help me?
I know there is probably a lot of errors, but be kind I'm new to this :)
If anyone is generous or just bored and wanted to personally help me out with issues please leave your email
Below is the code for my login class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), SignUp.class);
startActivity(i);
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn = (Button) findViewById(R.id.btnLogin);
}
// Methods to handleClick Event of Sign In Button
public void signIn(View V) {
try{
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
Button btnSignIn = (Button) dialog.findViewById(R.id.btnLogin);
}catch(Exception e){
Log.e("tag", e.getMessage());
}
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = loginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
dialog.show();
}
}
#Override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("tag", e.getMessage());
}
}
#Override
protected void onDestroy() {
try{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
MY registration class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
// get Instance of Database Adapter
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get References of Views
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
// check if any of the fields are vacant
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}}
The best way to know your code errors it's, put all your code in a block try-catch in all functions..
try{
//your code here
}catch(Exception e){
Log.e("tag", e.getMessage());
}
in Logcat will be apears in red color the errors of your code, "tag" it's a way to differentiate the erros like:
#Override
protected void onDestroy() {
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
I hope this helps...

how to save toggle button state to database and if user edits then edited state should be saved to database in android

how to save toggle button state to database and if user edits then edited state should be saved to database in android.the following is my code it is working fine.but the problem is that when user edits to on it is in on state and green light displays on toggle button. and then user performs the required actions.when user again comes back to edit again it displays on only but no green light is visible.so it looks bad so please help me and following is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
db.close();
}
#Override
public void onBackPressed(){
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
slight=light.getText().toString();
salarm=alarm.getText().toString();
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
intent.putExtra("Daddress",pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}
}
You can use SharedPrefernce for saving the state of toggle button.
sharedpreferences = context.getSharedPreferences("Toggle_pref", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("button_state", "state");
editor.commit();
This is code for Toogle Button with saved state..
private SharedPreferences spref;
private ToggleButton tb;
private boolean on;
spref = getSharedPreferences("APP", MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.toogleButton);
on = spref.getBoolean("On", true); //default is true
if (on)
{
tb.setChecked(true);
} else
{
tb.setChecked(false);
}
tb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (tb.isChecked()) {
//Toast.makeText(MainActivity.this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
} else {
// Toast.makeText(MainActivity.this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor =spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
}
}
});
in the following way i done and my problem solved.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
Log.v("___EDIT CLASS____________", "__LIGHT TEXT_____________"+slight);
Log.v("_____EDIT CLASS_____________", "___ALARM TEXT____________"+salarm);
Log.v("___EDIT CLASS____________", "__LIGHT boolean_____________"+blight);
Log.v("_____EDIT CLASS_____________", "___ALARM boolean____________"+balarm);
// edittext.setText(val);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
Log.v("___________edittext", "_______________"+edittext.getText());
Log.v("__________address", "_______________"+pos);
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
if(slight.equalsIgnoreCase("on"))
{
light.setChecked(true);
}
else
{
light.setChecked(false);
}
if(salarm.equalsIgnoreCase("on"))
{
alarm.setChecked(true);
}
else
{
alarm.setChecked(false);
}
db.close();
}
#Override
public void onBackPressed(){
//saveData();
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
// slight=light.setClickable(true);
//salarm= String.valueOf(balarm);
Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______pos", "______UUID___________"+pos);
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
Log.v("___QUERY ", "_________________"+db.select(strSQL));
slight=light.getText().toString();
salarm=alarm.getText().toString();
Log.v("___EDIT CLASS____________", "__SLIGHT ___AFTER__________"+slight);
Log.v("_____EDIT CLASS_____________", "___SALARM ___AFTER_________"+salarm);
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
/*Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______cccccc", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
/* Log.v("______device_____text", "_______________"+c.getString(c.getColumnIndex("devicename")));
Log.v("___________edittext", "_______________"+edittext.getText().toString());
Log.v("_____ADDRESS______edittext", "_______________"+pos);
*/ Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
Log.v("_____edittext in intent________", "__________"+edittext.getText().toString());
intent.putExtra("Daddress",pos);
Log.v("_____edittext in intent________", "__________"+pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
/* Log.v("_______EDIT IN DB", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}

Image is not displayed in the imageview on giving the path of that image

I am trying to display image on ImageView. I have the image in /storage/sdcard/DCIM/Camera/SAMPLE IMAGES/xxx.png I have used the following code to display image on the ImageView.
public class MainActivity extends Activity
{ Button button,hi,addpic;
final adapter info = new adapter(this);
Runnable m_handlertask = null ;
String path,birth;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
hi = (Button) findViewById(R.id.button3);
final adapter info = new adapter(this);
/* for(int i =1;i<=info.getrowcount();i++)
{
java.lang.String[] images_paths = {};
images_paths[i-1]=info.fetchsingles(i);
Toast.makeText(getApplicationContext(), images_paths[i-1], Toast.LENGTH_LONG).show();
}*/
hi.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,newlist.class);
startActivity(i);
}
});
addpic = (Button) findViewById(R.id.button2);
addpic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,adpic.class);
startActivity(i);
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,padd.class);
startActivity(i);
}
});
Date date = new Date(0);
java.text.DateFormat dateFormat =
android.text.format.DateFormat.getDateFormat(getApplicationContext());
dateFormat.format(date);
final ImageView jpgView;
jpgView = (ImageView) findViewById(R.id.imageView1);
//adapter mDbAdapter;
// path = info.getpath(y);
path = info.getPath();
final Handler mHandler = new Handler();
m_handlertask = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
mHandler.postDelayed(m_handlertask,3000);
condition();
}
int i=3;
private void condition() {
// TODO Auto-generated method stub
if((i % 3 )== 0) //running 1 time
{
birthday();
i++;
}
else //running 2 times
{
images();
i++;
}
}
private void birthday() {
// TODO Auto-generated method stub
try
{
birth = info.getBirth();
Toast.makeText(getApplicationContext(), "This is b'day pic : "+birth, Toast.LENGTH_LONG).show();
//Drawable d = Drawable.createFromPath(birth);
//jpgView.setImageDrawable(d);
File sdCardPath = Environment.getExternalStorageDirectory();
Bitmap bitmap = BitmapFactory.decodeFile(sdCardPath+"/DCIM/Camera/SAMPLE IMAGES/"+path);
jpgView.setImageBitmap(bitmap);
// Bitmap bitmap = BitmapFactory.decodeFile(birth);
// jpgView.setImageBitmap(bitmap);
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
private void images() {
// TODO Auto-generated method stub
try
{
path = info.getPath();
Toast.makeText(getApplicationContext(), "This is reg pic : "+path, Toast.LENGTH_LONG).show();
// Drawable d = Drawable.createFromPath(path);
// jpgView.setImageDrawable(d);
File sdCardPath = Environment.getExternalStorageDirectory();
Bitmap bitmap = BitmapFactory.decodeFile(sdCardPath+"/DCIM/Camera/SAMPLE IMAGES/"+path);
jpgView.setImageBitmap(bitmap);
// Bitmap bitmap = BitmapFactory.decodeFile(path);
// jpgView.setImageBitmap(bitmap);
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
};
m_handlertask.run();
}
#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;
} }
I have read other questions and tutorials, but I found same method of displaying, as I did in the code above. No image is displayed here. I did not find any error message in logcat. Please suggest me, any improvements in the code.
Thanks in advance.
You have a space between "/storage/ sdcard/". You should print the stacktrace to see the Exception using er.printStackTrace(). Also, you shouldn't hardcode the string path; use the Environment Class to reference file locations in a consistent way.
1) Make sure you have given permission to read external storage in your android manifest file.
2)
instead of hard coding the path to external storage use this.
File sdCardPath = Environment.getExternalStorageDirectory();
then add your folder and file name..
Bitmap bitmap = BitmapFactory.decodeFile(sdCardPath+"/DCIM/Camera/img_folder/xxx.png");
jpgView.setImageBitmap(bitmap);

Android App only working One time, then crashes

Okay so I am having a problem getting my app to work. Basically I have an game that needs to get a few pictures and Strings from the user. I have an opening screen (OpeningScreen) that acts as a splash screen that opens up the menu (MenuScreen). From there the user can pick to go to the game or go to the activity that shows the current pictures (PickScreen). The user can go to that activity and from there open up another activity that gives a larger version of the picture they currently have picked or a default picture (PicOne). Here the user has the option to take a new picture and change the current Strings. For the most part all of it works great. My problem occurs when:
After the user picks a picture and backs out of the app. The next time they open it, it will force close either when I go back to PickScreen or after I press done after taking a new picture and sometimes when I go to PicOne activity. It does not do the same thing everytime, it just crashes at one of those points.
The other issue happens when I change the 3 String names. After pressing save and going back to PickScreen, the app crashes when going back to PicOne or if I back out of the app crashes when going from MenuScreen to PickScreen.
I know this is a lot of code to look at, but I have spent a lot of time looking around and getting code from different places for this app and I am at a point that I cannot figure out. I figure there are many people with more knowledge than me out there, so I am asking for your help. I know that you cannot just ask a question without showing you have been doing any work, so here it is.
Why does may app work perfectly once and then crash in various spots the second time in? By the way it does work fine after the force close, again only once. And why does it force close when I change the Strings?
Thanks everyone!!
The PicOne Class
public class PicOne extends Activity implements OnClickListener {
ImageView iv;
EditText c1, c2, c3;
Button cam, save;
Bitmap bit, bmp,other;
Intent i;
Uri uriSavedImage;
String imageFilePath10 = "", name1="", name2="", name3="";
final static int cameraData = 0;
boolean CAMERA;
int camORgal10 = 0;
SharedPreferences gameData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.picone);
CAMERA = false;
iv = (ImageView)findViewById(R.id.picIV);
cam = (Button)findViewById(R.id.camButton);
save = (Button)findViewById(R.id.savebut);
e1 = (EditText)findViewById(R.id.Enter1);
e2 = (EditText)findViewById(R.id.Enter2);
e3 = (EditText)findViewById(R.id.Enter3);
cam.setOnClickListener(this);
save.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
//camera
case R.id.camButton:
camORgal10 = 1;
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MySpot");
imagesFolder.mkdirs(); // <----
String fileName = "image_1.PNG";
File output = new File(imagesFolder, fileName);
uriSavedImage = Uri.fromFile(output);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(i, cameraData);
break;
case R.id.savebut:
CAMERA = true;
name1 = e1.getText().toString();
name2 = e2.getText().toString();
name3 = e3.getText().toString();
SharedPreferences.Editor editor = gameData.edit();
editor.putInt("NUM10CAMGAL", camORgal10);
editor.putString("NUM10NAME1", name1);
editor.putString("NUM10NAME2", name2);
editor.putString("NUM10NAME3", name3);
editor.commit();
Intent goPT = new Intent(this, PickScreen.class);
goPT.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
goPT.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
startActivity(goPT);
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
CAMERA = true;
name1 = e1.getText().toString();
name2 = e2.getText().toString();
name3 = e3.getText().toString();
SharedPreferences.Editor editor = gameData.edit();
editor.putInt("NUM10CAMGAL", camORgal10);
editor.putString("NUM10NAME1", name1);
editor.putString("NUM10NAME2", name2);
editor.putString("NUM10NAME3", name3);
editor.commit();
Intent goPT = new Intent(this, PickScreen.class);
goPT.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
goPT.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
startActivity(goPT);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == cameraData)
{
if(resultCode == RESULT_OK && data.hasExtra("data"))
{
bmp = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bmp);
}
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled",Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if(OpeningScreen.isEXIT)
{
finish();
}
gameData = getSharedPreferences(MenuScreen.MYFOLDER, 0);
name1 = slotData.getString("NUM10NAME1", "one");
name2 = slotData.getString("NUM10NAME2", "two");
name3 = slotData.getString("NUM10NAME3", "three");
e1.setText(name1);
e2.setText(name2);
e3.setText(name3);
camORgal10 = gameData.getInt("NUM10CAMGAL", 0);
if(camORgal10 == 0)
{
bit = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
else if(camORgal10 == 1)
{
File imgFile = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_1.PNG");
if(imgFile.exists())
{
bit = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
else
{
bit = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
}
else
{
bit = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
iv.setImageBitmap(bit);
super.onResume();
}
}
OpeningScreen
public class OpeningScreen extends Activity {
/** Called when the activity is first created. */
public static boolean isEXIT = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
isEXIT = false;
Thread timer = new Thread(){
public void run(){
try{
sleep(2500);
} catch(InterruptedException e){
} finally{
Intent toMenu = new Intent(getApplicationContext(), MenuScreen.class);
toMenu.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//toMenu.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
finish();
startActivity(toMenu);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
finish();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if(isEXIT)
{
finish();
}
super.onResume();
}
}
MenuScreen
public class MenuScreen extends Activity implements OnClickListener {
float x,y;
int camORgal = 0;
ImageButton play, edit, more;
Intent i;
public static String MYFOLDER = "GAMEDATA";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
play = (ImageButton)findViewById(R.id.IBplay);
edit = (ImageButton)findViewById(R.id.IBedit);
more = (ImageButton)findViewById(R.id.IBmore);
play.setOnClickListener(this);
edit.setOnClickListener(this);
more.setOnClickListener(this);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
OpeningScreen.isEXIT = true;
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.IBplay:
i = new Intent(getApplicationContext(), TheGame.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
break;
case R.id.IBedit:
i = new Intent(this, PickScreen.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
break;
case R.id.IBmore:
break;
}
}
}
PickScreen
public class PickScreen extends Activity implements OnClickListener {
Button bPic1, bPic2, bPic3;
ImageView ivpic3,ivpic2, ivpic1;
TextView TVpic3a, TVpic3b, TVpic3c, TVpic2a, TVpic2b, TVpic2c, TVpic1a, TVpic1b, TVpic1c;
Intent pageMove;
SharedPreferences gameData;
int camORgal10 = 0;
String threeNamea = "", threeNameb = "", threeNamec = "", twoNamea = "", twoNameb = "", twoNamec = "", oneNamea = "", oneNameb = "", oneNamec = "";
Bitmap bmp1, bmp2,bmp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.paytable);
intitializeThings();
}
public void intitializeThings()
{
bPic1 = (Button)findViewById(R.id.pic1but);
bPic2 = (Button)findViewById(R.id.pic2but);
bPic3 = (Button)findViewById(R.id.pic3but);
ivpic3 = (ImageView)findViewById(R.id.ivpic3a);
ivpic2 = (ImageView)findViewById(R.id.ivpic2a);
ivpic1 = (ImageView)findViewById(R.id.ivpic1a);
TVpic3a = (TextView)findViewById(R.id.pic3TVa);
TVpic3b = (TextView)findViewById(R.id.pic3TVb);
TVpic3c = (TextView)findViewById(R.id.pic3TVc);
TVpic2a = (TextView)findViewById(R.id.pic2TVa);
TVpic2b = (TextView)findViewById(R.id.pic2TVb);
TVpic2c = (TextView)findViewById(R.id.pic2TVc);
TVpic1a = (TextView)findViewById(R.id.pic1TVa);
TVpic1b = (TextView)findViewById(R.id.pic1TVb);
TVpic1c = (TextView)findViewById(R.id.pic1TVc);
bPic1.setOnClickListener(this);
bPic2.setOnClickListener(this);
bPic3.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.pic1but:
pageMove = new Intent(getApplicationContext(), PicOne.class);
pageMove.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pageMove.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//pageMove.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
finish();
startActivity(pageMove);
break;
case R.id.pic2but:
pageMove = new Intent(getApplicationContext(), PicTwo.class);
pageMove.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//pageMove.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(pageMove);
finish();
break;
case R.id.pic3but:
pageMove = new Intent(getApplicationContext(), PicThree.class);
pageMove.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//pageMove.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(pageMove);
finish();
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
Intent goOP = new Intent(this, MenuScreen.class);
goOP.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
goOP.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
startActivity(goOP);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
gameData = getSharedPreferences(MenuScreen.MYFOLDER, 0);
oneNamea = gameData.getString("NUM10NAME1", "one");
oneNameb = gameData.getString("NUM10NAME2", "two");
oneNamec = gameData.getString("NUM10NAME3", "three");
camORgal10 = gameData.getInt("NUM10CAMGAL", 0);
if(camORgal10 == 1)
{
File pic1 = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_1.PNG");
if(pic1.exists())
{
bmp1 = BitmapFactory.decodeFile(pic1.getAbsolutePath());
}
else
{
bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
}
else if(camORgal10 == 0)
{
bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
else
{
bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.red);
}
File pic2 = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_2.PNG");
File pic3 = new File(Environment.getExternalStorageDirectory() + "/MySpot/image_3.PNG");
if(pic2.exists())
{
bmp2 = BitmapFactory.decodeFile(pic2.getAbsolutePath());
}
else
{
bmp2 = BitmapFactory.decodeResource(getResources(), R.drawable.purple);
}
if(pic3.exists())
{
bmp3 = BitmapFactory.decodeFile(pic3.getAbsolutePath());
}
else
{
bmp3 = BitmapFactory.decodeResource(getResources(), R.drawable.green);
}
ivpic3.setImageBitmap(bmp3);
ivpic2.setImageBitmap(bmp2);
ivpic1.setImageBitmap(bmp1);
TVpic1a.setText(oneNamea);
TVpic1b.setText(oneNameb);
TVpic1c.setText(oneNamec);
}
}
Logcat will give you a stack trace, and then use debug to pinpoint the place where it's crashing. Debugging a modern application by reading through code, especially OOP code, is nearly impossible.
This was probably caused by the fact the AOS does not closes apps really but you might think is does. So on the next start AOS doesn't start your app "from the scratch" but it raises your undead cached app. And since your logic wasn't expected that your app crashes. I'm pretty sure it starts OK once again right after the crash but the next start once again crashes -> the loop. So to avoid that use System.exit(0) (most advanced devs gonna say its a bad practice) to ensure your app wont became a zombie OR change the logic of your app so it wont crash on the next start cuz the main activity is still there.

Categories

Resources