Trying to pass data from a service to an activity - java

I have a string that I'm trying to pass to my main activity that is bound to this service. The data doesn't seem to be making it through to the other side and I've tried a plethora of techniques. Any help would be appreciated
Here's the service
public int onStartCommand(Intent intent, int flags, int startId) {
String thename=intent.getStringExtra("stockName");
String TAG="hello";
Intent putIntent=new Intent(LocalService.this,Binding.class);
if(thename.equals("AMZN"))
{
//Toast.makeText(this, "The price is $1,755.25", Toast.LENGTH_LONG).show();
putIntent.putExtra("theName","WORKED");
}
and here is the activity itself
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binding);
final Button priceButton=findViewById(R.id.priceButton);
final EditText stockPrice=findViewById(R.id.stockText);
final Intent theIntent=new Intent(Binding.this,LocalService.class);
priceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stockText=stockPrice.getText().toString();
theIntent.putExtra("stockName",stockText);
startService(theIntent);
Intent getit=getIntent();
String name=getit.getParcelableExtra("theName");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
}
});
}

I tried adding a BroadcastReceiver to your code (it's not that pretty), I commented the lines I added. It's possible that I've missed something or made an error. Feel free to ask if your get any errors or read https://developer.android.com/reference/android/content/BroadcastReceiver
Good luck!
Your service
public int onStartCommand(Intent intent, int flags, int startId) {
//String for the BroadcastReceiver to listen for.
public static final String BROADCAST_STRING = "your.package.or.whatever.you.want.sending";
String thename=intent.getStringExtra("stockName");
String TAG="hello";
Intent putIntent=new Intent(BROADCAST_STRING);
if(thename.equals("AMZN"))
{
//Toast.makeText(this, "The price is $1,755.25", Toast.LENGTH_LONG).show();
putIntent.putExtra("theName","WORKED");
}
//Broadcast sent and picked up in Activity.
sendBroadcast(putIntent);
Your Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binding);
final Button priceButton=findViewById(R.id.priceButton);
final EditText stockPrice=findViewById(R.id.stockText);
private BroadcastReceiver broadcastReceiver;
final Intent theIntent=new Intent(Binding.this,LocalService.class);
//Adds a filter to the broadcastReceiver, what it should listen for
IntentFilter filter = new IntentFilter();
filter.addAction("your.package.or.whatever.you.want.sending");
//Triggered when a broadcast is picked up
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Get intent and do what you want
};
// Register the broadcastReceiver and filter
this.registerReceiver(broadcastReceiver, filter);
priceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stockText=stockPrice.getText().toString();
theIntent.putExtra("stockName",stockText);
startService(theIntent);
Intent getit=getIntent();
String name=getit.getParcelableExtra("theName");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
}
});
}

Related

Not able to receive broadcast in other app

I was learning broadcast receiver concept, so I tried making demo apps for sending broadcast and receiving custom private broadcast
This is my Broadcast Sender App code :
public class MainActivity extends AppCompatActivity {
TextView senderTextView;
Button sendButton;
private int counter;
//This is our anonymous class which will receive broadcast when sent from send button and set our text view
private final BroadcastReceiver innerReceiverAnonymousClass = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//if our (com.example.PRIVATE_BROADCAST) broadcast equals to the intent received here from intent filter
if("com.example.PRIVATE_BROADCAST".equals(intent.getAction())){
//counter variable for tracking no. of times broadcast is sent
counter++;
//then this means broadcast has been sent in mobile
//set text
senderTextView.setText("Broadcast Sent " + counter + " times");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
senderTextView = findViewById(R.id.senderTextView);
sendButton = findViewById(R.id.sendButton);
//Setting onClick Listener on sendButton
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Calling Broadcast Method
Broadcast();
}
});
}
//Broadcast Method
private void Broadcast(){
//Creating private broadcast event
Intent intent = new Intent("com.example.PRIVATE_BROADCAST");
//Adding String to our intent
intent.putExtra("BROADCAST_EXTRA_DATA","This is Private Broadcast");
//Sending our private broadcast to our android mobile
sendBroadcast(intent);
}
#Override
protected void onStart() {
super.onStart();
//Intent filter will filter out intent from all the broadcasts happening in mobile
// on basis of action and pass it to innerReceiverAnonymousClass
IntentFilter intentFilter = new IntentFilter("com.example.PRIVATE_BROADCAST");
registerReceiver(innerReceiverAnonymousClass,intentFilter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(innerReceiverAnonymousClass);
}
This is my Broadcast Receiver app :
public class MainActivity extends AppCompatActivity {
TextView receiverTextView;
//Our anonymous private broadcast receiver class
//We can also make a separate class java class that will extend BroadcastReceiver class
//But we are using an anonymous so that we can get control of text view i.e. UI
private final BroadcastReceiver privateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if("com.example.PRIVATE_BROADCAST".equals(intent.getAction())){
Log.d("APP_LOGS", "Broadcast Received");
Toast.makeText(context, "Private Broadcast Received", Toast.LENGTH_SHORT).show();
String broadcastString = intent.getStringExtra("BROADCAST_EXTRA_DATA");
receiverTextView.setText("Broadcast Received : " + broadcastString);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiverTextView = findViewById(R.id.receiverTextView);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter("com.example.PRIVATE_BROADCAST");
registerReceiver(privateBroadcastReceiver,intentFilter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(privateBroadcastReceiver);
}
When I press send Broadcast button textview inside sender activity sets to "Broadcast sent 1 times which means our intent is getting broadcasted but toast from my receiver app doesn't show which means I am not able to get broadcast there.
Can someone help me with this.
Thanks in advance.

Transferring data from the third activity to the first

From the first activity I would like to go to the second, then from the second to the third. In the third activity I would like to enter the name in EditText, then after pressing the button, go to the first activity and at the same time send the information entered in the third activity.
Unfortunately, after pressing the button in the third activity, instead of returning to the first activity, I return to the second activity. Was the first activity killed? What could I do to ensure that the information is correct for the first activity? This is my code:
First:
public class MainActivity extends AppCompatActivity {
TextView textViewInformation;
Button button_GoToSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewInformation = findViewById(R.id.textView);
button_GoToSecond = findViewById(R.id.button);
button_GoToSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Second.class);
startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
String name = i.getStringExtra("name");
textViewInformation.setText(name);
}
}
}
Second:
public class Second extends AppCompatActivity {
Button button_GoToThird;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
button_GoToThird = findViewById(R.id.button2);
button_GoToThird.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Second.this, Third.class);
startActivity(i);
}
});
}
}
Third:
public class Third extends AppCompatActivity {
EditText editText_Data;
Button button_SendData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
editText_Data = findViewById(R.id.editText);
button_SendData = findViewById(R.id.button3);
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
just remove finish(); thats it
The reason that it goes to the second activity is because of this:
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish(); //This kills the current activity.
}
You should do:
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", name);
startActivityForResult(i, RESULT_OK, bundle);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
Bundle bundle = i.getExtras();
String name = bundle.getString("name");
textViewInformation.setText(name);
}
}
When you call finish, it just kills the current activity. If you want to go back to the first activity, just start a new activity for the first activity and pass the data in a Bundle.
If you want to have more of a stack concept, you can use Fragments.

Intent is hijacking in app billing

I was able to implement an in app billing processor, and it tests fine without my intent to go to a new activity.
However, after a customer pays for the paid content I want a new intent to be
run automatically whereby a new activity is launched (the activity with the paid content).
However, when I do this the intent overtakes the billing processor, and switches to the paid
activity without any billing or payment. I understand how to use a button with an intent to launch the new activity. However, another button won't work because this too would
be an easy way to go around the in app billing.
Any suggestions to get around this sticky wicket? Thanks much. Yes, this is my first android app. I’m sure you can tell…
BillingProcessor bp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
bp = new BillingProcessor(this, "null", this);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bp.purchase(MainActivity.this, "android.test.purchased");
//THE PROBLEM IS WHAT FOLLOWS: It overtakes .bp
startActivity(new Intent(MainActivity.this, paidstuff.class));
}
});
}
#Override
public void onProductPurchased(#NonNull String productId, #Nullable TransactionDetails details) {
Toast.makeText(this, "You just bought something great!", Toast.LENGTH_SHORT).show();
}
#Override
public void onPurchaseHistoryRestored() {
}
#Override
public void onBillingError(int errorCode, #Nullable Throwable error) {
}
#Override
public void onBillingInitialized() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onDestroy() {
if (bp != null) {
bp.release();
}
super.onDestroy();
}
}
cant you just put
startActivity(new Intent(MainActivity.this, paidstuff.class));
inside
#Override
public void onProductPurchased(#NonNull String productId, #Nullable TransactionDetails details) {
Toast.makeText(this, "You just bought something great!", Toast.LENGTH_SHORT).show();
}

Android Intent.getParcelableArrayListExtra return null

A Activity execute below code.
Call Test Activity passing arraylist "bus_list".
But Test Activity new_bus_list_array = I.getParcelableArrayListExtra("bus_list") returns null.
new_bus_list_array Class "Parcelable" has been implemented.
I don't know why.
please help.
Intent intent;
intent = new Intent(_context, Test.class);
intent.putParcelableArrayListExtra("bus_list", (ArrayList<? extends Parcelable>) new_bus_list_array);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
[Test.java]
public class Test extends AppCompatActivity {
List<Bus_List> new_bus_list_array = new ArrayList<Bus_List>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Intent I = getIntent();
new_bus_list_array = I.getParcelableArrayListExtra("bus_list");
}
}
You can also do this way (using BrodCastManager)
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your intent action
Intent intent = new Intent(value.equals("AccountFragment") ? "sendMeData" : "analysisMe");
tempList.clear();
intent.putExtra("analysisData", (Parcelable) balanceMap.get(keylist.get(position)));
tempList.addAll(myRecord); // for backup because we are removing other data so it affect on parent
// send like this
intent.putParcelableArrayListExtra("RecordData", (ArrayList<? extends Parcelable>) tempList);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
In your Another Activity where you Received Data
(After register to BroadcastManger)
BroadcastReceiver analysisRecevier = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
AccountAnalysisModel currentAccountBalModel = intent.getParcelableExtra("analysisData");
recordData = intent.getParcelableArrayListExtra("RecordData");
}
};

Multiple startActivityForResult()

I need to call this function twice in my application pointing to two different activities. I have a unique request code for each call, however my app seems to crash everytime it launches the second activity.
Here is my code (only relevant parts):
MainActivity:
//Request Info vars
static final int GET_DETAILS = 1;
static final int EDIT_DETAILS = 2;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
lat = latLng.latitude;
lon = latLng.longitude;
startActivityForResult(new Intent(MapsActivity.this,NewMarkerActivity.class), GET_DETAILS);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
current_marker = marker;
startActivityForResult(new Intent(MapsActivity.this,EditMarkerActivity.class), EDIT_DETAILS);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == GET_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
addMarker(lat, lon, marker_title, marker_snippet);
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lon)));
}
} if (requestCode == EDIT_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
current_marker.setTitle(marker_title);
current_marker.setSnippet(marker_snippet);
}
}
}
EditMarkerActivity:
public class EditMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
NewMarkerActivity:
public class NewMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
Any obvious issues? Help or insight to this problem will be greatly appreciated :)
Here is my output from Logcat:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.geekybrackets.virtualtourguide/com.geekybrackets.virtualtourguide.EditMarkerActivity}; have you declared this activity in your AndroidManifest.xml?
Turns out the issue was that I hadn't defined the activity in the manifest file.
Dear old me, now i know to check my errors !
Thanks again guys, case closed.

Categories