Please, I am having problem sending an ArrayList data to Activity.
The data is an URL saved in ArrayList but after using bundle extras, I am getting null pointer exception. I also try to catch the exception but still the data i get using get extra string is null
// below is the code i used to pass the data
Bundle extras = new Bundle();
extras.putString("VidUrl",VideoLecturesUrl.get(position));
extras.putString("bookUrl",bookUrl.get(position));
extras.putString("VidTitle",titleList.get(position));
Intent intent = new Intent(getActivity(),DetailsView.class);
intent.putExtras(extras);
startActivity(intent);
// below is the receiving activity
Intent intent = getIntent();
extras =intent.getExtras();
if (extras!=null){
try {
Video_Url = extras.getString("VidUrl");
BookUrl = extras.getString("bookUrl");
Title = extras.getString("VidTitle");
Toast.makeText(this,Video_Url,Toast.LENGTH_SHORT).show();
Toast.makeText(this,BookUrl,Toast.LENGTH_SHORT).show();
Toast.makeText(this,Title,Toast.LENGTH_SHORT).show();
videotexTitle.setText(Title);
setTitle(Title);
setVideo(Video_Url.toString());
}catch (Exception e){
e.printStackTrace();
}
} else {
Toast.makeText(this, "the extrass is empty", Toast.LENGTH_SHORT).show();
}
in the fragment
public interface NoticeFragmentListener {
public void onFragmentSendArray(ArrayType yourArray);
}
NoticeFragmentListener listener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeFragmentListener so we can send events to the host
listener = (NoticeFragmentListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
}
}
//metod to send array
public void SendArray(ArrayType yourArray){listener.onFragmentSendArray(yourArray);}
in de activity
public class yourActivity extends AppCompatActivity implements YourFragment.NoticeFragmentListener
and recive the array
#Override
public onFragmentSendArray(ArrayType yourArray) {
}
For simplicity use the SharedPreferences for this purpose
Related
My code has two activities.
public class OnCallingActivity extends Activity implement TextToSpeech.OnInitListener{}
public class TextReceiverActivity extends BroadcastReceiver{}
i want first activity to extend sencond activity
OnCallingActivity extends TextReceiverActivity {}
so I did this,
public class OnCallingActivity extends Activity implements TextToSpeech.OnInitListener {
private TextReceiverActivity TextReceiverActivityClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.on_calling_layout);
TextReceiverActivityClass= new TextReceiverActivity();
speaker= new TextToSpeech(this, this);
callerIdText=(TextView)findViewById(R.id.callerIdtextview);
callerText=(TextView)findViewById(R.id.callermsgtextview);
translatedText=(TextView)findViewById(R.id.translatedTextview);
speakButton=(ImageButton)findViewById(R.id.btnSpeak);
sendButton=(Button)findViewById(R.id.buttonsend);
endCallButton=(ImageButton)findViewById(R.id.buttonendCall);
}
my second activity is as follow,
public class TextReceiverActivity extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
number ="";
message="";
final Bundle bundle = intent.getExtras();
try {
if(bundle != null) {
final Object[] pduObjects = (Object[]) bundle.get("pdus");
for(int i = 0; i < pduObjects.length; ++i) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pduObjects[i]);
number = currentMessage.getDisplayOriginatingAddress();
message = currentMessage.getDisplayMessageBody();
Toast.makeText(context, "SENDER NUMBER: " + number + "; MESSAGE: " + message, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
in first activity i called the method of second activity like this
public void onReceive(Context context, Intent intent) {
TextReceiverActivityClass.onReceive(context, intent);
}
onReceive gives values for number and message..so how can i get them to my first activity to display them in TextViews.
onReceive is an inbuilt method so i can't change the return type.
If TextReceiverActivity extends BroadcastReceiver, then TextReceiverActivity isnt an Activity and I would refrain from calling it an Activity.
The onReceive method of a BroadcastReceiver is meant to be called from the Android sytem, not you.
To send a message from an Activity to a BroadcastReceiver you would send a Broadcast. See the docs.
If you want to send a message from your BroadcastReceiver to your Activity, there's a couple of questions about that.
I am trying to fetch some for Location Address using IntentService but ended up with error leading to app crash. Please help me.
Here is the Stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.ResultReceiver.send(int, android.os.Bundle)' on a null object reference
at com.example.ajender.sample2.FetchAddressIntentService.deliverResultToReceiver(FetchAddressIntentService.java:91)
at com.example.ajender.sample2.FetchAddressIntentService.onHandleIntent(FetchAddressIntentService.java:81)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
Here is FetchAddressIntentService:
public class FetchAddressIntentService extends IntentService {
private static String TAG="Fetch-address-Service";
protected ResultReceiver mReceiver;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public FetchAddressIntentService(String name) {
super(name);
}
public FetchAddressIntentService(){
super("FetchAddressIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
String errorMessage = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
Location location = intent.getParcelableExtra(
Constants.LOCATION_DATA_EXTRA);
mReceiver=intent.getParcelableExtra(Constants.RECEIVER);
Log.e(TAG,"1-----");
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
// In this sample, get just a single address.
1);
} catch (IOException ioException) {
// Catch network or other I/O problems.
errorMessage = "service_not_available";
Log.e(TAG, errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid_lat_long_used";
Log.e(TAG, errorMessage + ". " +
"Latitude = " + location.getLatitude() +
", Longitude = " +
location.getLongitude(), illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = "no_address_found";
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
Log.i(TAG, "address_found");
deliverResultToReceiver(Constants.SUCCESS_RESULT,
TextUtils.join(System.getProperty("line.separator"),
addressFragments));
}
}
private void deliverResultToReceiver(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
Log.e(TAG, "2-----");
mReceiver.send(resultCode, bundle);
Log.e(TAG, "3-----");
}
This service should have to send back bundle with Result Receiver and result code but not happening....
The error can be resolved following the steps below
In the MainActivity
Add public AddressResultReceiver mResultReceiver;
mResultReceiver = new AddressResultReceiver(null)- This will automatically assign a id for the main activity class.
In the FetchAddressIntentService
Add mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
Check whether mReceiver is null by logging it.
Send the data using your current code.
It should work. Thats how I got Around it.If you have any problem comment.
Probably you haven't initialize the mResultReceiver from your activity correctly, which you are supposed to pass to the FetchAddressIntentService intent:
mResultReceiver = new AddressResultReceiver(new android.os.Handler());
..
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
..
startService(intent);
What happens in case of IntentService is that you have three components that are playing role: MainActivity (that will call the intent service), IntentService (which is responsible for handling the intent) and the last ResultReceiver which receives the result after the intent has been handled (or operated).
As evident from the Log you have not initialized or assigned any value to ResultReceiver mReceiver
You should initialize mResultReceiver by declaring a class let us call it AddressResultReceiver which extends ResultReceiver and has a parameterized constructor that accepts a single parameter as Handler object and overrides the onReceiveResult() method like the following:
AddressResultReceiver(Handler handler) {
super(handler);
}
//Result from intent service
#Override
public void onReceiveResult(int resultCode, Bundle bundle) {
...
}
Now you have successfully obtained two of three components: MainActivity for starting an intent request and ResultReceiver for receiving the result. Let us now make our IntentService by defining a class in the project hierarchy and extending it with IntentService and overriding its method onHandleIntent(Intent intent)():
public class FetchAddressIntentService extends IntentService {
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {...}
}
So we are now good to go to get the things up and working. Now write the following code in your MainActivity:
//Initializing the reference with AddressResultReceiver object
mResultReceiver = new AddressResultReceiver(new Handler());
...
//Setting the IntentService to FetchAddressIntentService
Intent intent = new Intent(this, FetchAddressIntentService.class);
/*passing the receiver object to the service so as to let it know where to
publish results*/
intent.putExtra(Constants.RECEIVER, mResultReceiver);
...
//starting the service
startService(intent);
Now your deliverResult(int, String) would no longer throw NullPointerException. For more information visit IntentService and ResultReceiver. Hope it helps! :)
Add the below code in your protected void onHandleIntent (#Nullable Intent intent){} before Geocoder
if (intent != null){
String errorMessage ="";
resultReceiver = intent.getParcelableExtra(Constants.RECEIVER);
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
if (location == null) {
return;
}
i'm doing a project where i have to call a browser via my android app, but when i call it, the app stops.
the code can be found here: https://github.com/coppetti/android-pulsometer
but for fast view, i have a "Pulsometro" class where
public void onPreviewFrame(byte[] data, Camera cam) {
...
Browser browser = new Browser();
browser.callBrowser(beats);
return;
...
}
and a Browser class where:
public class Browser extends Activity{
public void callBrowser(int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return;
}
}
There's a way to call a browser and my app doesn't breaks?
Try this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onOpenWebBrowser(View v)
{
Intent webPageIntent = new Intent(Intent.ACTION_VIEW);
webPageIntent.setData(Uri.parse("https://www.google.co.in/"));
try {
startActivity(webPageIntent);
} catch (ActivityNotFoundException ex) {
}
}
Do not just randomly choose superclasses. Do not just create some subclass of Activity and expect it to work.
Move your callBrowser() method into some real Activity implementation, and get rid of Browser entirely.
Or, remove the superclass from Browser, have callBrowser() take a Context as a parameter, and call startActivity() on that Context.
Try this class. Call the callBrowser method and give it and Activity for the context parameter.
public class Browser{
public void callBrowser(Context context, int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
}
}
I'm new to android and I have a problem with this code. I'm trying to get a JSON String and start another activity to display it as a ListView.
I'm not able to start the activity. It says that the The constructor Intent(RequestJsonString, Class) is undefined and The constructor Intent(RequestJsonString, Class) is undefined .
Here:
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
and Here:
RequestJsonString.this.startActivity(intent);
I have read many posts on this on stackoverflow and tried with activity, context and this. But still I'm not getting it right. I think I should be missing something. Any help is appreciated.
public class RequestJsonString extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
// Code HTTP Get Request and get JSONObject
return jsonObject;
}
protected void onPostExecute(JSONObject jsonObj){
try {
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
RequestJsonString.this.startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("Json_OutPut","Done");
}
}
To start the activity from AsyncTask.
Intent intent = new Intent(YourActivityName.this,DisplayResults.class);
or you can do same like below.
Declare the context instance variable and initialize it in onCreate method.
private Context context;
public void onCreate(Bundle bundle) {
............
context = this;
........
}
Start the activity like this.
Intent intent = new Intent(context,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
startActivity(intent);
In your case you are referring to asynctask class context
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
Use a Activity Context
Intent intent = new Intent(ActivityName.this,DisplayResults.class);
Check the link to know when to use getApplicationContext() and when to use Activity Context
When to call activity context OR application context?
Edit:
Pass the Activity context to the asynctask constructor
new RequestJsonString(ActivityName.this).execute(params..);
In your asynctask constructor
Context c;
public RequestJsonString( Context context)
{
c= context;
}
Then
Intent intent = new Intent(c,DisplayResults.class);
startActivity(intent);
private Button.OnClickListener goFirstPage = new Button.OnClickListener() {
public void onClick(View v)
{
try
{
Intent i = new Intent(v.getContext(), quizMath.class);
startActivityForResult(i, 0);
} catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
}
};
hi, this is my code, but the problem is that i want to call a function from class quizmath.So is it possible or not?. can we pass integer or string from startActivityForResult?
Yes it's possible. You'll find documentation for Intent here http://developer.android.com/reference/android/content/Intent.html
Before you start the activity you can use the putExtra function on your intent.
i.putExtra( "yourapp.function_to_call", "subtract" );
This is going to be passed to your activity and you can get out the information with the Intent.getStringExtra function. In your activity you can then do something like this.
Intent i = this.getIntent();
String fname = i.getStringExtra( "yourapp.function_to_call" );
if( fname.equals("add") )
// ...