how to use utility class to start intent android - java

I am updating code for a company app and there are about 20 activity classes that all download a PDF and then display it using this code:
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
the code is working, however it has been replicated in all 20 classes (seems very bad to me) and I would like to put it into a single class which each activity class imports, however when I try to do this, things like getPackageManager() and startActivity(intent) no longer work.
How can I structure my class to make this happen? or am I going about this the wrong way.

How can I structure my class to make this happen?
Step #1: Make this a static method on a utility class.
Step #2: Add Context ctxt as a parameter to the method.
Step #3: For methods like getPackageManager() and startActivity(), which are implemented on Context, call them on the passed-in ctxt parameter.
Step #4: Smack your wrist with a ruler for using string concatenation for creating a file path, and do it the right way.
Step #5: Get rid of the queryIntentActivities() code that you aren't using.
public static void showPdf(Context ctxt)
{
File file = new File(Environment.getExternalStorageDirectory(), "/pdf/Read.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
startActivity(intent);
}
Step #6: Have the places that are presently calling showPdf() call YourUtilityClass.showPdf(this).

public class PDFUtlity{
public static void showPdf(Context context)
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
PackageManager packageManager = context.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
((Activity)context).startActivity(intent);
}
}
public class MyActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
///.....
PDFUtlity.showPdf(this);
}
}

Related

Android Studio: How to send, and recieve a Class in diferent Activities

Im making a quiz game with questions on diferent topics
For Example i have activities for these topics: Flags, Capitals, Population, Economy, Continent, etc.
And i have one single ResultActivity to obtain the Score of the quiz.
The ResultActivity has a PLAY AGAIN button.
On the FlagsActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "FlagsActivity");
startActivity(intent);
On the CapitalActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "CapitalActivity");
startActivity(intent);
etc.....
On the ResultActivity i have this code:
activity = getIntent().getStringExtra("NAME_ACTIVITY");
public void playAgain(View view){
if(activity.equals("FlagsActivity")){
Intent intent = new Intent(getApplicationContext(), FlagsActivity.class);
startActivity(intent);
}
if(activity.equals("CapitalActivity")){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
if(activity.equals("PopulationActivity")){
Intent intent = new Intent(getApplicationContext(), PopulationActivity.class);
startActivity(intent);
}
if(activity.equals("EconomyActivity")){
Intent intent = new Intent(getApplicationContext(), EconomyActivity.class);
startActivity(intent);
}
if(activity.equals("ContinentActivity")){
Intent intent = new Intent(getApplicationContext(), ContinentActivity.class);
startActivity(intent);
}
}
Basically im sending an Intent with a String containing the name of the activity, then on the Result Activity evaluating with "if" the String = That activity name, start the activity.
What i want to do is someting like this:
On the Flags Activity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(FlagsActivity.class);
startActivity(intent);
On the CapitalActivity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(CapitalActivity.class);
startActivity(intent);
On the Result Activity:
activity = getIntent();
public void playAgain(View view){
Intent intent = new Intent(getApplicationContext(), activity);
startActivity(intent);
}
So that i can create as many quiz activities without having to create an "if" statement on the ResultActivity for it to work.
You can pass the class name as a string and use reflection to look up a class object for that type. Something like this:
Class classToLoad = Class.forName(getIntent().getStringExtra("NAME_ACTIVITY"));
Intent intent = new Intent(getApplicationContext(), classToLoad);
startActivity(intent);
I would pass the fully qualified class name to avoid errors.
You could pass the String of activity name to the Result activity, and get its corresponding class name using reflection:
String strActivity = "com.package.FlagsActivity";
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("activity_name", strActivity );
startActivity(intent);
String activityName = getIntent().getStringExtra("activity_name");
Class<?> myClass = Class.forName(activityName );
Intent myIntent = new Intent(getApplicationContext(), myClass);
Something like this.
In the Results Activity
public static void toActivity(Context context, final Class ActivityToOpen){
//whatever awesome code you would like to perform
Intent intent = new Intent(context, ActivityToOpen);
startActivity(intent);
}
In the originating Activity (Flags Activity for example)
ResultsActivity.toActivity(FlagsActivity.this, FlagActivity.class);
Check for typos... I kinda winged this :)
You should be able to call from any originating Activity without if statement.
When you receive the data
String activity;
Bundle bundle = getIntent().getExtras();
if (bundle != null){
activity = bundle.getString("NAME_ACTIVITY");
}

App crashes when starting a activity

I have a webview app and wanted to updated app from inside when a certain text is present in the url.
I am calling these in shouldOverrideUrlLoading function of webview:
Intent intent = new Intent(getApplicationContext(), Update.class);
startActivity(intent);
return true;
And here is the Update.class
public class Update extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "app-file.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
File file = new File(destination);
if (file.exists())
file.delete();
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(getIntent().getStringExtra("http://example.com/app-file.apk")));
request.setDestinationUri(uri);
dm.enqueue(request);
final String finalDestination = destination;
final BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(ctxt, BuildConfig.APPLICATION_ID + ".provider", new File(finalDestination));
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
openFileIntent.setData(contentUri);
startActivity(openFileIntent);
unregisterReceiver(this);
finish();
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(install);
unregisterReceiver(this);
finish();
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
When I go to the certain url to start the activity, the app crashes. I would love to see any solution. Thanks!!
I SOLVED IT, it was permission error.
I would suggest you to look into ADB Logcat, which will help you to fix the issue.
Otherwise, check into crash log or make sure that you have declared your Update Activity in manifest.xml
Make sure you declare the new activity in your Android Manifest.xml
try changing this
Intent intent = new Intent(getApplicationContext(), Update.class);
startActivity(intent);
return true;
to this
Intent intent = new Intent(getApplicationContext(), Update.class);
startActivity(intent);
finish();
return true;
Let me know how that went.

Launch intent with some sound file

I am making an Android application containing more than 60 buttons. Each button responds to an Activity. Each Activity contains a sound file sourced from a raw file, a TextView and an image. Is there any way that I can use Intent parameters for each button?
For example:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("soundfile", "FirstKeyValue");
myIntent.putExtra("image", "SecondKeyValue");
myIntent.putExtra("text", "ThirdKeyValue");
startActivity(myIntent);
//Make method let suppose
public void sendMysong(String songname,String imgUrl,String text)
{
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("soundfile",songname);
myIntent.putExtra("image",imgUrl);
myIntent.putExtra("text",text);
}
// Now in receiving Activity receive intent data
Bundle extras = getIntent().getExtras();
if (extras != null) {
String fname=extras.get("soundfile");
int resID=getResources().getIdentifier(fname, "raw", getApplicationContext().getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
mediaPlayer.start();
}
Sixty button in single layout is not a good design pattern, you must use either grid or List view.
Using List View
http://developer.android.com/design/building-blocks/lists.html
Using Grid View
http://developer.android.com/guide/topics/ui/layout/gridview.html
As far as the current problem is concerned
You can create a generalized Function as given below
public boolean startActivityFoo(String value1,String value2,String value3)
{
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("soundfile",value1);
myIntent.putExtra("image",value2);
myIntent.putExtra("text",value3);
startActivity(myIntent);
}

Copy intent / change source activity and destination class

I want to change to a new Activity over an Intent, but in my current Intent there are all my ExtraStrings as parameters. So decided to copy it with
Intent next = getIntent();
but how to change the source activity and the destiantion class now ?
Probably the better solution would be create your own Intent with your destination class and use Intent.putExtras(Intent src) to put extra data of original intent to new one.
And of course you can use Intent.setClass or setClassName() just to replace destination class.
You can also pass your data in bundle..
FirstActivity:
Intent mIntent = new Intent(this, activity1.class);
Bundle mBundle = new Bundle();
mBundle.putString("key", "value");
mIntent.putExtra("keyBundle", mBundle);
SecondActivity:
Intent mIntent = new Intent(this, activity2.class);
mIntent.putExtras(getIntent().getExtras().getBundle("keyBundle"));

Adding a list of scan results from Wifi to an intent and retrieving from a broadcast receiver?

I want to add a list as a parameter to pass into an intent and then receive it from a broadcast listener, but I'm having some trouble. I cannot figure out how to put this List into the Intent as an extra, or retrieving the list from it. I can get into the broadcast receiver.
//In my Main File: Everthing is registered and working.
IntentFilter startUsingScanResults = new IntentFilter("StartUsingScanResults");
c.registerReceiver(serviceConsume.ScanResultReceiver, startUsingScanResults);
List<ScanResult> scanResults = Some values;
Intent intent = new Intent();
intent.setAction("StartUsingScanResults");
// Then Need to put the List<ScanResults> into the intent.
// ie: intent.putExtra("MyResults", scanResults);
Context.sendBroadcast(intent);
// My broadcast receiver that should have the list inside it.
public BroadcastReceiver ScanResultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
// Need something here to get the list
// ie: List<ScanResult> scanResults = extras.getBundle("MyResults");
}
};
Hopefully I am clear with this question. I just need to put the list into and get the List from the bundle (or intent).
A ScanResult is in the format of ["","","","","","",""] if that helps. So I guess it might be similar to a multidimensional array.
Any help is appreciated! Thanks
I've figured it out. I like simple solutions, and this is pretty much as simple as it gets.
intent.putParcelableArrayListExtra("ScanResults", (ArrayList) scanResults);
And Add this to the Broadcast receiver
ArrayList scanResults = extras.getParcelableArrayList("ScanResults");
So the end result is:
//In my Main File:
IntentFilter startUsingScanResults = new IntentFilter("StartUsingScanResults");
c.registerReceiver(serviceConsume.ScanResultReceiver, startUsingScanResults);
List<ScanResult> scanResults = Some values;
Intent intent = new Intent();
intent.setAction("StartUsingScanResults");
intent.putParcelableArrayListExtra("ScanResults", (ArrayList<? extends Parcelable>) scanResults);
Context.sendBroadcast(intent);
// And my broadcast receiver
public BroadcastReceiver ScanResultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
ArrayList<ScanResult> scanResults = extras.getParcelableArrayList("ScanResults");
}
};
Hopefully this helps out someone in a similar situation.

Categories

Resources