I have problem with onActiviResult function. Code compiles and emulates but the data parameter returns null.
In function main:
private static String sActualLogin = "admin";
private static String sActualPassword = "qwerty";
(...)
public void setRegisterOnClick(View v)
{
Intent intentLOGIN = new Intent(this, Users.class);
intentLOGIN.putExtra("Type",1);
startActivityForResult(intentLOGIN, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data.getExtras().containsKey("Login")){
if(resultCode==RESULT_OK && requestCode==1){
String sContainer = data.getStringExtra("Login");
sActualLogin=sContainer;
RESULT1.setText(sActualLogin);
}
}
if(data.getExtras().containsKey("Password")){
if(resultCode==RESULT_OK && requestCode==1){
String sContainer=data.getStringExtra("Password");
sActualPassword=sContainer;
RESULT2.setText(sActualPassword);
}
}
}
And then code goes to Users:
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class Users extends Activity {
private EditText etNewLogin;
private EditText etNewPassword;
private TextView RESULT3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
etNewLogin = (EditText) findViewById(R.id.etChangePassword);
RESULT3 = (TextView) findViewById(R.id.RESULT3);
Intent Intent2=getIntent();
int number = Intent2.getIntExtra("Type", 0);
RESULT3.setText("" +number); //returns 1 well
}
public void giveResponse(View v)
{
Intent intent = getIntent();
int iOperation = intent.getIntExtra("Type", 0);
if (iOperation == 1){
String sNewLogin = etNewLogin.getText().toString();
intent.putExtra("Login", sNewLogin);
setResult(RESULT_OK, intent);
finish();
}
if (iOperation == 2){
String sNewPassword = etNewPassword.getText().toString();
intent.putExtra("Password", sNewPassword);
setResult(RESULT_OK, intent);
finish();
}
}
}
So I sActualLogin is being set to "" after onActivityResult. Please help me with this problem; something is wrong there and I can't see it.
assuming you start Users activity with startActivityForResult(intent, 1);, the only thing I see is that you set the same variable for both of the EditText views:
etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
etNewLogin = (EditText) findViewById(R.id.etChangePassword);
You can also add to the if statement on onActivityResult(...) a check to make sure its not empty:
if(data.getExtras().containsKey("Login") && !data.getStringExtra("Login").isEmpty())
Related
Basically i have two java activities where i have implemented textToSpeech in one activity but when i go to another activity using on click view and when i pressed back for returning to the mainactivity then it will again execute texttospeech method.
But i want to execute this method only once when the user starts the app after that it will stop.
Below is my code and i want to execute the code only once how it will done?
package com.example.software2.ocrhy;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private static int firstTime = 0;
private TextView mVoiceInputTv;
float x1, x2, y1, y2;
private TextView mSpeakBtn;
private static TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.US);
textToSpeech.setSpeechRate(1.1f);
if (firstTime == 0)
textToSpeech.setSpeechRate(1.1f);
textToSpeech.speak("Welcome to Blind App. Swipe left to listen the features of the app or swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
}
public boolean onTouchEvent(MotionEvent touchEvent) {
firstTime = 1;
switch (touchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
if (x1 < x2) {
textToSpeech.speak(" Say Read for reading, calculator for calculator, time and date, weather for weather, battery for battery. Swipe right and say what you want ", TextToSpeech.QUEUE_FLUSH, null);
} else if (x1 > x2) {
startVoiceInput();
}
break;
}
return false;
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
a.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SPEECH_INPUT) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
if (mVoiceInputTv.getText().toString().equals("read")) {
Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("yes")) {
textToSpeech.speak(" Say Read for reading, calculator for calculator, time and date, weather for weather, battery for battery. Do you want to listen again", TextToSpeech.QUEUE_FLUSH, null);
mVoiceInputTv.setText(null);
} else if ((mVoiceInputTv.getText().toString().equals("no"))) {
textToSpeech.speak("then tap on the screen and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
} else if (mVoiceInputTv.getText().toString().equals("exit")) {
finish();
}
}
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
textToSpeech.speak("You are already in the main menu", TextToSpeech.QUEUE_FLUSH, null);
}
return true;
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
Make Text to Speak variable in Global and at these code in your onStop / onPause method.
public static void releaseTts() {
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
}
Replace these code in your MainActivity.class
private static final int REQ_CODE_SPEECH_INPUT = 100;
private static int firstTime = 0;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
private static TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.US);
if (firstTime == 0)
textToSpeech.speak("Welcome to Blind App. Tap on the screen. Say Read for reading . Say calculator for calculator.say time and date. say weather for weather. say battery for battery.", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstTime = 1;
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
a.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SPEECH_INPUT) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().equals("read")) {
Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
}
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
This is where I import the image to(from gallery) and I want to save it to SQLite to hopefully display it in another activity, how would I go about doing so? I am kind of new to Android Studio so if there is some newbie kind of easy way that I would go about doing so would be very helpful.
(Update) So I have added this two lines marked by /* */ but now I can't get my app to work still have no idea how to do this.. any ideas?
Import image>Save to SQLite>Take Image to SQLite>Display in another activity
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DataInput extends AppCompatActivity {
private EditText inputName;
private EditText inputAge;
private Button buttonSave;
private Button buttonGetLocation;
private Button buttonImportImage;
private ImageView mImageView;
private static final int IMAGE_PICK_CODE = 1000;
private static final int PERMISSION_CODE = 1001;
private InputHelper helper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_input);
inputName = (EditText) findViewById(R.id.input_name);
inputAge = (EditText) findViewById(R.id.input_age);
address = (TextView) findViewById(R.id.address);
buttonSave = findViewById(R.id.button_save);
buttonSave.setOnClickListener(onSave);
buttonImportImage = findViewById(R.id.button_import_image);
mImageView = findViewById(R.id.image_view);
buttonImportImage.setOnClickListener(onImport);
helper = new InputHelper(this); }
private View.OnClickListener onSave = new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameStr = inputName.getText().toString();
String ageStr = inputAge.getText().toString();
String addressStr = address.getText().toString();
String combineStr = nameStr + "\n" + ageStr + "\n" + addressStr;
Toast.makeText(v.getContext(), combineStr, Toast.LENGTH_LONG).show();
/*BitmapDrawable drawable = (BitmapDrawable)mImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
byte[] image = getBitmapAsByteArray(bitmap);*/
Intent i = new Intent(DataInput.this,InformationDisplay.class);
startActivity(i);
helper.insert(nameStr,ageStr,addressStr,image);
finish();
}
/* public byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray(); */
}
};
private View.OnClickListener onImport = new View.OnClickListener() {
#Override
public void onClick(View v) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
//permission not granted, request it.
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_CODE);
} else {
//permission already granted
pickImageFromGallery();
}
} else {
//system os is less then marshmallow
pickImageFromGallery();
}
}
};
private void pickImageFromGallery() {
//intent to pick image
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
//handle result of runtime permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//permission was granted
pickImageFromGallery();
} else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_LONG).show();
}
}
}
}
//handle result of picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
//set image to image view
mImageView.setImageURI(data.getData());
}
}
You can save an Image in SQLite database in the form of blob. Another simple way to storing the image is in the form of base64 string. This is what I tried in my previous project and this works:
public class Profile_Class extends AppCompatActivity {
private Bitmap photo, OutImage;
private AppPreferences preferences;
private CircularImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile__class);
EditText name = findViewById(R.id.name);
preferences = new AppPreferences(this);
Toolbar toolbar = findViewById(R.id.toolbar_t);
EditText userName = findViewById(R.id.userName);
EditText passWord = findViewById(R.id.passWord);
imageView = findViewById(R.id.iv_profile_auditor);
ImageView take_pic1 = findViewById(R.id.take_pic1);
if (prefernces.getProfileImage().equals(" ")) {
Log.e("TAG", "NoProfilePic");
} else {
imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));
}
take_pic1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
OutImage = Bitmap.createScaledBitmap(photo, 300, 400, true);
prefernces.setProfileImage(encodeTobase64(OutImage));
Intent intent2 = new Intent("header_pic_update");
LocalBroadcastManager.getInstance(Profile_Class.this).sendBroadcast(intent2);
}
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return true;
}
If you see in OnActivityResult class, I'm converting the outImage into Base64 string. Here use the method encodeTobase64 and add the image string to your table.
Now in the other activity where you want to show the image, call the method decodeBase64 and decode the image. In the above code I'm decoding the string to image and setting it to imageview like this:
imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));
There are numerous ways to store and retrieve the image. This is one way I did. Mind here that I'm storing the image in bitmap so the quality will not be good. If you want image with full quality than you have to use URI to store the image in your mobile and then call the image in required quality.
i can not figure out how to pass the results from onActivityResult to resultBreakdown. I know there is a get/set and I've looked at a few tutorials, but I'm just not getting it. Or, Is there a better way? The program runs fine up if i comment out */ the resultBreakdown Class
Side note, I just started with java/android. I'm a better learner at doing then reading. I know my code is a little clumsy. Thanks for the help
Note: i edited code to reflect suggested changes
package com.example.spdwiz18.testproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import java.text.DateFormat;
import java.time.*;
import java.time.temporal.*;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
public class GrindLogActivity extends AppCompatActivity {
TextView barcodeResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gringlogactivity);
// this is how to set id's from the xml file with vNames. (julianDate)
TextView bcc = (Textview)findViewById(R.id.bccheck);
TextView pc = (Textview)findViewById(R.id.pcode);
TextView pd = (Textview)findViewById(R.id.pdate);
// TextView en = (Textview)findViewById(R.id.estnum);
TextView sn = (Textview)findViewById(R.id.seqnum);
TextView nw = (Textview)findViewById(R.id.nweight);
barcodeResult = (TextView) findViewById(R.id.barcode_result);
TextView julianDate = (TextView) findViewById(R.id.datecode);
TextView td1 = (TextView) findViewById(R.id.todaydate1);
// this is how you get a julian/original date for android
LocalDate now = LocalDate.now();
int julian = now.get(ChronoField.DAY_OF_YEAR);
// this how to set you current date for android
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
// this is how to set your vNames to your method variables
julianDate.setText(Integer.toString(julian));
td1.setText(stringDate);
}
/*add click event to the scan barcode button */
public void scanBarcode(View v) {
Intent intent = new Intent(this, ScanBarcodeActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(String result) {
if (result.length() == 44) {
pc.setText(result.CharSequence(2,10));
pd.setText(result.CharSequence(13,18));
sn.setText(result.CharSequence(21,27));
nw.setText(result.CharSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}
The code posted needs a lot of work - so this answer most likely is just partial
(1) TextView initialization in wrong place
The TextViews declared as class instance variables cannot also be initialized at that point. So leave the declarations there (where bardcodeResult is declared):
TextView barcodeResult;
TextView bcc;
TextView pc;
TextView pd;
TextView sn;
TextView nw;
but move the initialization to the onCreate method in the same manner barcodeResult.
// in onCreate
barcodeResult = (TextView) findViewById(R.id.barcode_result);
bcc = (TextView)findViewById(R.id.bccheck);
pc = (TextView)findViewById(R.id.pcode);
pd = (TextView)findViewById(R.id.pdate);
sn = (TextView)findViewById(R.id.seqnum);
nw = (TextView)findViewById(R.id.nweight);
(2) The syntax is of resultsBreakdown is invalid and the functionality is wrong (need to invoke setText)- try:
public void resultsBreakdown(String result) {
if (result.length() == 44) {
pc.setText(result.CharSequence(2,10));
pd.setText(result.CharSequence(13,18));
sn.setText(result.CharSequence(21,27));
nw.setText(result.CharSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}
(3) Actually invoke the resultsBreakdown method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
//-- THIS LINE WAS ADDED TO CALL METHOD
resultsBreakdown(barcode.displayValue.toString());
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
I think there should be resultCode instead of requestCode in requestCode == CommonStatusCodes.SUCCESS
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
resultsBreakdown(barcode.displayValue)
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(String barcodeData){
if (barcodeData.length == (44)) {
pc = (barcodeData.CharSequence(2,10);
pd = (barcodeData.CharSequence(13,18);
sn = (barcodeData.CharSequence(21,27);
nw = (barcodeData.CharSequence(13,18);
)else(
bcc = "invalid barcode";
}
)
}
resultBreakdown neither a class nor a method.İt isn't even compile. You change your resultBreakDown to Method:
public void resultsBreakdown(Barcode barcodeResult){
if (barcodeResult.length == (44)) {
pc = (barcodeResult.CharSequence(2,10);
pd = (barcodeResult.CharSequence(13,18);
sn = (barcodeResult.CharSequence(21,27);
nw = (barcodeResult.CharSequence(13,18);
} else{
bcc = "invalid barcode";
}
and later in onActivityResult call your method with Barcode parameters.
The code is incomplete as you have not placed ScanBarcodeActivity java file. Well... I am placing a small code in my project which will clear your concept and even you can use it.
Here suppose i am in Activity MyClassA.java where is a button and when it is clicked it will start another activity MyClassB.java, Remember it will start that activity along with layout.. from that activity you have to finish it on certain event and when it is finished your MyClassA.java will collect its result...
From Activity MyClassA.java on button click i want to start a activity
MyClassB.java for result:
ContactsBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
ContactsBtn.setEnabled(false);
Intent intent = new Intent(MyClassA.this, MyClassB.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
Where REQUEST_CODE should be declared in MyClassA class as public static final int REQUEST_CODE = 1;
Now From Activity MyClassB.java on particular event say on click of a button you want to close this activity and want to send result to previous activity :
SelectContactsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.putStringArrayListExtra("WhitelistNames", (ArrayList<String>) WhitelistNames);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
Here i am placing WhitelistNames array list as result to be sent to calling activity.
Now From Activity MyClassA.java again you have to collect the result with :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK)
{
ArrayList<String> WhitelistNames = data.getStringArrayListExtra("WhitelistNames");
Log.d("ContactsContracts", "\nPREVIOUS LIST : "+ContactsNumbers);
}
}
}
Remember onActivityResult method should be part of your MyClassA.java class and should not be in onCreate nor in some other existing standard methods of this class.
Hope it helps
Thank you for everyones help. This one worked as needed
package com.example.spdwiz18.testproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import java.text.DateFormat;
import java.time.*;
import java.time.temporal.*;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
public class GrindLogActivity extends AppCompatActivity {
TextView barcodeResult;
TextView bcc;
TextView pc;
TextView pd;
TextView sn;
TextView nw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gringlogactivity);
bcc = (TextView)findViewById(R.id.bccheck);
pc = (TextView)findViewById(R.id.pcode);
pd = (TextView)findViewById(R.id.pDate);
// TextView en = (TextView)findViewById(R.id.estnum);
sn = (TextView)findViewById(R.id.seqnum);
nw = (TextView)findViewById(R.id.nweight);
barcodeResult = (TextView) findViewById(R.id.barcode_result);
TextView julianDate = (TextView) findViewById(R.id.datecode);
TextView td1 = (TextView) findViewById(R.id.todaydate1);
// this is how to set id's from the xml file with vNames. (julianDate)
// this is how you get a julian/original date for android
LocalDate now = LocalDate.now();
int julian = now.get(ChronoField.DAY_OF_YEAR);
// this how to set you current date for android
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
// this is how to set your vNames to your method variables
julianDate.setText(Integer.toString(julian));
td1.setText(stringDate);
}
/*add click event to the scan barcode button */
public void scanBarcode(View v) {
Intent intent = new Intent(this, ScanBarcodeActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
resultsBreakdown(barcode.displayValue.toString());
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(CharSequence result) {
if (result.length() == 44) {
pc.setText(result.subSequence(2,10));
pd.setText(result.subSequence(13,18));
sn.setText(result.subSequence(21,27));
nw.setText(result.subSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}}
I am making bluetooth application in which I want to send data using bluetooth. That task I am able to do. But after that I want open any particular file from device. Then How can I do it? I have written the code below.
package com.example.blue;
import java.io.File;
import java.util.List;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int DISCOVER_DURATION=300;
private static final int REQUEST_BLU=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path="/storage/emulated/0/DCIM/Camera/20141018_152852.jpg";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=file.getName().substring(file.getName().indexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file),type);
startActivity(intent);
}
public void sendViaBluetooth(View v){
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null)
{
Toast.makeText(this,"Bluetooth not supported" , Toast.LENGTH_LONG).show();
}else
{
enableBluetooth();
}
}
public void enableBluetooth(){
Intent discoveryIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
File f = new File(Environment.getExternalStorageDirectory(),"md5sum.txt");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
PackageManager pm = getPackageManager();
List<ResolveInfo> appsList = pm.queryIntentActivities(intent, 0);
if(appsList.size()>0)
{
String packageName = null;
String className = null;
boolean found = false;
for(ResolveInfo info : appsList)
{
packageName = info.activityInfo.packageName;
if(packageName.equals("com.android.bluetooth"))
{
className = info.activityInfo.name;
found = true;
break;
}
}
if(!found){
Toast.makeText(this,"Bluetooth haven't been found" , Toast.LENGTH_LONG).show();
}else
{
intent.setClassName(packageName, className);
startActivity(intent);
}
}
}else{
Toast.makeText(this,"Bluetooth is cancelled" , Toast.LENGTH_LONG).show();
}
}
}
I have my main activity using the startActivityForResult method which calls an activity that i need to return two string values from. I have it working to return one, but even with all the tutorials and other questions on here i have read i cant seem to get it to return the two values. Below is my code.
here is where i start the second activity:
Button button = (Button) findViewById(R.id.add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
Here is the activity it starts, i need to return the text that is in the titleField(which works now) and the yearField
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.setData(Uri.parse(titleField.getText().toString()));
setResult(RESULT_OK, data);
//data.setData(Uri.parse(yearField.getText().toString()));
//setResult(RESULT_OK, data);
finish();
}
});
}
}
Here is the method in my main class that receives results
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getData().toString();
//tempYear = data.getStringExtra("movieYear");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
The code that is commented out was one attempt at making it receive multiple values, although they failed. Any help with this situation would be great. Thanks!
You should use something like:
Intent returnIntent = new Intent();
returnIntent.putExtra("title",titleField.getText().toString());
returnIntent.putExtra("year",yearField.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
And on your main activity, onActivityResult:
tempTitle = data.getStringExtra("title");
tempYear = data.getStringExtra("year");
use data.putExtra("keys", data); instead of data.setData(.....)
and get data like;
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}
You should be able be put extras on your intent and get that data through an associated tag. This is how I'm doing it from an Activity's onCreate.
Intent mIntent = new Intent(this, MainActivity.class);
mIntent.putExtra("your_tag", "the string you want to get");
startActivity(mIntent);
finish();
Then in the activity you want that data (the MainActivity or whatever you're calling it)....
Intent intent = getIntent();
String value = intent.getExtras().getString("your_tag");
It may also be worth noting that you can Override the onNewIntent in your MainActivity to handle new Intents coming in, mine currently looks like...
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
Try this
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("title_field", titleField.getText().toString);
data.putExtra("year_field", yearField.getText().toString);
setResult(RESULT_OK, data);
finish();
}
});
}
And this
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getStringExtra("title_field");
tempYear = data.getStringExtra("year_field");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
You can use a putExtra method on your Intent:
data.putExtra("title", movieTitle);
data.putExtra("year", movieYear);
Then in the Activity that opens, you can get this data as follows:
String title, year;
Intent data = getIntent();
if (data != null) {
title = data.getExtras().getString("title");
year = data.getExtras().getString("year");
}
You can create a new intent and then add your two variables
Intent i = new Intent(getApplicationContext(), asd8.as.hwapp.timemonday.class);
i.putExtra("username",username);
i.putExtra("password", password);
startActivity(i);
And then retrieving the information in your new activity as so;
public void getInformation(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
username = extras.getString("username");
password = extras.getString("password");
}
}