Jackherer Jackherer - 1 month ago 12
Android Question

Duplicate onCreate(Bundle) in android project

I am a java noob (but learning fast), and i have been trying to introduce code snippets into my MainActivity in an android project.

My problem is that i have two onCreate(bundle) lines that are conflicting, other answers say to just delete one! when i comment out the top one most of my code throws errors, when i comment out the second one it causes an error on the snippet i was using i.e it stops the setOnClickListener which i assume is a listener on the button i will using to select an image.

The error:


Error:(273, 24) error: method onCreate(Bundle) is already defined in class MainActivity


Here is my MainActivity.java:

public class MainActivity extends AppCompatActivity {

private EditText inputStrain, inputNumOfZs, EditText, inputShortDesc;
private TextInputLayout inputLayoutStrain, inputLayoutNumOfZs, inputLayoutPricePerOz, inputLayoutShortDesc;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), "Please enter all the details requested.", Toast.LENGTH_SHORT).show();


Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

inputLayoutStrain = (TextInputLayout) findViewById(R.id.input_layout_strain);
inputLayoutNumOfZs = (TextInputLayout) findViewById(R.id.input_layout_num_of_zs);
inputLayoutShortDesc = (TextInputLayout) findViewById(R.id.input_layout_short_desc);
inputLayoutPricePerOz = (TextInputLayout) findViewById(R.id.input_layout_price_per_oz);
inputStrain = (EditText) findViewById(R.id.input_strain);
inputNumOfZs = (EditText) findViewById(R.id.input_num_of_zs);
EditText inputPricePerOz = (EditText) findViewById(R.id.input_price_per_oz);
inputShortDesc = (EditText) findViewById(R.id.input_short_desc);
Button btnAdd = (Button) findViewById(R.id.btn_add);

inputStrain.addTextChangedListener(new MyTextWatcher(inputStrain));
inputNumOfZs.addTextChangedListener(new MyTextWatcher(inputNumOfZs));
inputShortDesc.addTextChangedListener(new MyTextWatcher(inputShortDesc));
inputPricePerOz.addTextChangedListener(new NumberTextWatcher(inputPricePerOz, "#,###"));


btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submitForm();
}
});
}

/**
* Validating form
*/
private void submitForm() {
if (!validateStrain()) {
return;
}

if (!validateNumOfZs()) {
return;
}

if (!validateShortDesc()) {
return;
}

Toast.makeText(getApplicationContext(), "@string/add_new_oz_toast", Toast.LENGTH_SHORT).show();
}

// validate proper correctness of user input
// could make this to toast? if user doesnt enter correct/required field
private boolean validateStrain() {
if (inputStrain.getText().toString().trim().isEmpty()) {
inputLayoutStrain.setError(getString(R.string.err_msg_strain));
requestFocus(inputStrain);
return false;
} else {
inputLayoutStrain.setErrorEnabled(false);
}

return true;
}

private boolean validateNumOfZs() {
if (inputNumOfZs.getText().toString().trim().isEmpty()) {
inputLayoutNumOfZs.setError(getString(R.string.err_msg_num_of_zs));
requestFocus(inputNumOfZs);
return false;
} else {
inputLayoutNumOfZs.setErrorEnabled(false);
}

return true;
}

private boolean validatePricePerOz() {
if (EditText.getText().toString().trim().isEmpty()) {
inputLayoutPricePerOz.setError(getString(R.string.err_msg_price_per_oz));
requestFocus(EditText);
return false;
} else {
inputLayoutNumOfZs.setErrorEnabled(false);
}

return true;
}

private boolean validateShortDesc() {
if (inputShortDesc.getText().toString().trim().isEmpty()) {
inputLayoutShortDesc.setError(getString(R.string.err_msg_short_desc));
requestFocus(inputShortDesc);
return false;
} else {
inputLayoutShortDesc.setErrorEnabled(false);
}

return true;
}


private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}

// a text watcher to ensure the text is input as it should be
private class MyTextWatcher implements TextWatcher {

private View view;

private MyTextWatcher(View view) {
this.view = view;
}

public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}

public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}

public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_strain:
validateStrain();
break;
case R.id.input_num_of_zs:
validateNumOfZs();
break;
case R.id.input_price_per_oz:
validatePricePerOz();
break;
case R.id.input_short_desc:
validateShortDesc();
break;
}
}
}

//my number text watcher for making price of oz a currency
public class NumberTextWatcher implements TextWatcher {

private final DecimalFormat df;
private final DecimalFormat dfnd;
private final EditText et;
private boolean hasFractionalPart;
private int trailingZeroCount;

NumberTextWatcher(EditText inputPricePerOz, String pattern) {
df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.00");
this.et = inputPricePerOz;
hasFractionalPart = false;
}

@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);

if (s != null && !s.toString().isEmpty()) {
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
StringBuilder trailingZeros = new StringBuilder();
while (trailingZeroCount-- > 0)
trailingZeros.append('0');
et.setText(df.format(n) + trailingZeros.toString());
} else {
et.setText(dfnd.format(n));
}
et.setText("@string/currency_symbol".concat(et.getText().toString()));
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel < et.getText().length()) {
et.setSelection(sel);
} else if (trailingZeroCount > -1) {
et.setSelection(et.getText().length() - 3);
} else {
et.setSelection(et.getText().length());
}
} catch (NumberFormatException | ParseException e) {
e.printStackTrace();
}
}

et.addTextChangedListener(this);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int index = s.toString().indexOf(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
trailingZeroCount = 0;
if (index > -1) {
for (index++; index < s.length(); index++) {
if (s.charAt(index) == '0')
trailingZeroCount++;
else {
trailingZeroCount = 0;
}
}
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}




ImageView viewImage;
Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.btnSelectPhoto);
//viewImage = (ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
}

private void selectImage() {

final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);

}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);

viewImage.setImageBitmap(bitmap);

String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "iDealer" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {

Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path from gallery = ", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}


}

Answer

I think you can cut:

b = (Button)findViewById(R.id.btnSelectPhoto);
//viewImage = (ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        selectImage();
    }
});

code and go to the first onCreate. I think that's no problem. If you have 2 onCreate, your android studio will be confused. Your android studio can't detect which method will be compiled.