Calling two different activities on different devices (tablet and phone) - java

Here, I'm trying to start an activity on different devices (Android Tablet and Android Phone). Is there a way to use if statement to check which activity should to load based on the devices?
Here's my code:
Button buttonGo = (Button) findViewById(R.id.button_goToActivity);
buttonGo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (tablet device) {
startActivity(new Intent(MainActivity.this, TabletActivity.class));
} else {
startActivity(new Intent(MainActivity.this, AndroidPhoneActivity.class));
}
});
Thanks for your effort...

In order to achieve that you must use Fragment not an Activity. the Design Philosophy of Fragments is exactly what you want. you can take a look at Example to see how it is implemented. This is a master-detail app with two Fragments, when device in a portrait mode or it is not a tablet it just shows master, otherwise it also shows detail beside the master and when you select an item from the list you will see the details without going to other Activity.

Firstly as Android Best Practice it is adviced to use Fragments rather than Activity to achieve your requirement.
But if you are keen on using Activity, then below is the solution to find device type and load different activities.
1) Have 2 values folders: values -> strings.xml and values-sw600dp -> strings.xml
2) Create string value in both the xml
<string name="device_type">PHONE</string> in values -> strings.xml
<string name="device_type">TABLET</string> in values-sw600dp -> strings.xml
3) create a method to check if current device is Phone or not
public boolean isPhone() {
String deviceType = getResource().getString(R.string.device_type);
if (deviceType.equalsIgnoreCase("PHONE") {
return true;
} else {
return false;
}
}
4) Depending on the device load your activity as you have already done in your above code snippet
Let me know if this helps...

Most likely, you should not have two separate activities here. Instead, you should have two different layouts for the same activity. The layout for phones should be in the regular res/layout folder and the layout for tablets should be in the res/layout-large folder. Read Supporting Different Screens for more details.

If you are using same fuctionality for Tablet Activity and Phone activity then you do not need two activities for this purpose. You need to make two different Layout xml for Tablet as well as Phone.
Make a Layout folder named : layout-large and layout-xlarge.
Now copy the xml file from normal layout folder and paste in both new layout folders.
No need to change the name of xml file.
Now Adjust xml file of layout-large and layot-xlarge as you want to make design for tablet.
Now on running application Tablet and phone bot will pick xml according to there size and screen density.
Note : the functionality should be same.
And if: you want to show different screen with different functionality for phone and tablet then. use this code for check.
if ((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
}
Hope this wll help you.

Related

How do I change the main xml file from another activity?

I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.

Which is the best way to use media player?

Just to be clear, because my question can be not so clear.
I develop Music Player app. The thing is I have MainActivity and 4 Fragments in this activity(it's not all).
In each fragment I have list of songs retrieved from device using CustomCursorAdapter(for example: first fragment - all songs, second fragment albums e.t.c.)
I already tried to use MediaPlayerSingleton
public class singletonMediaPlayer{
MediaPlayer mediaPlayer;
private static singletonMediaPlayer in = null;
private singletonMediaPlayer() { }
public static singletonMediaPlayergetInstance() {
if (in == null) {
synchronized (singletonMediaPlayer.class) {
if (in == null) {
in = new singletonMediaPlayer();
}
}
}
return instance;
}
}
But here the problem was that all playback controls I have in MainActivity(not in fragments) and have no idea how to handle previouse, next buttons. It is not a problem if media player is in fragment or activity together with ListView of songs but like this... have no idea. Plus when I tried to select item(song) from another activity it just didn't play until I press play button. Playbacks I can see it through all fragments so it's looks like this(just in case):
Plus I have 2 seperate Activities to show songs from albums and from playlists. Sooooooooooo... Finaly the question is:
How do you think it is better to build Media Player for such app (just in case, I don't need code from you). Is it better to use Music Service(which I already started to build) or maybe Singletone is better(in that case I just don't know how to perform the task with singletone for now) or maybe there is another way??? Will be great if somebody response with hint, link or just show me the way in which better to go.
Thank you in advance!
P.S.
Yep, by the way there are 3 ListViews with songs(for now) - 2 of them reusable.

Passing a Layout and it's contents between Activities

So full admission, I am a bit self taught when it comes to Android Dev, so I maybe going about this all wrong. As such I am open to suggestions! I'm essentially trying to semi-automate a task I do every day currently.
Question: How to Pass a LinearLayout, it's contents intact, between Activities?
So I have this 2nd Activity, called reportGeneratorActivity In this activity there is a Linear Layout directly under the Report Preview.
The Linear Layout itself is defined in a separate XML file as previewplate.xml
Now this Activity functions, when you put text into the upper fields it updates the preview below. Which brings me to the brick wall I'm hitting. The Goal is to take that preview plate and add it to my main activity that I've named rootActivity in the white area which is a Linear Layout itself named rootWorkingLayout.
Now the Strings from the text are all stored temporarily in reportGeneratorActivity at which point I am doing this when the button is pressed:
public void beginReport (View view) {
//Bundle the Preview
Bundle previewBundle = new Bundle();//Create the Bundle
previewBundle.putString("date", dateHolder);
previewBundle.putString("client", clientNameHolder);
previewBundle.putString("machine", machineTypeHolder);
previewBundle.putString("serial#", serialNumberHolder);
previewBundle.putString("notes", notesHolder);
// Prepare The Intent
Intent previewPasser = new Intent(this, rootActivity.class);
previewPasser.putExtras(previewBundle); // Add the Bundle to Intent
//Send Preview to Root
startActivity(previewPasser);
//Send Preview to History
//Send User to Decision Tree
}
From what I understand, I've put all the strings in Bundle previewBundle, then attached the bundle to the previewPasser intent and sent the intent back to rootActivity.
In rootActivity, within the onCreate function I have placed this code:
Bundle previewReceiver = getIntent().getExtras();
//If There is a Bundle, Process it
if(previewReceiver != null) {
newPreview(previewReceiver);
}
The Goal here is to grab the Intent, and grab the bundle then pass it to my newPreview function (currently empty) that will duplicate finished preview from report_generator_activity and desplaying within the Linear Layout: rootWorkinglayout in an identical fashion.
It's this final step that I am hitting a brick wall on, I can only assume there is an easier way, perhaps a way to duplicate the Layout and it's contents and send it over? Or if I am doing this functionally, How do I unpack the data in an identical manner?
Please forgive the verbosity and lack of images as I am a new member of the community.
Edit #1:
In response to SoroushA's excellent answer that has put me on the correct path, I've adjusted my newPreview Method to be this:
public void newPreview (Bundle previewReceiver) {
//Extract Strings from Bundle
String date = previewReceiver.getString("date");
String client = previewReceiver.getString("client");
String machine =previewReceiver.getString("machine");
String serialNum = previewReceiver.getString("serial#");
//Create New Inflater
LayoutInflater previewInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View previewLayout = previewInflater.inflate(R.layout.previewplate, null);
//Add previewLayout to rootWorkingLayout
rootWorkingLayout.addView(previewLayout);
}
Currently, I am just trying to get the grey box of the preview plate layout to appear as it's background is defined in it's own XML file. However, nothing is occurring when I go through the process clearly due to my own error. I am unsure of what step I am missing.
Thanks in advance!
I hope that I understood your question clearly.
In your newPreview method, start by getting the Strings back from the Bundle:
public void newPreview(Bundle preview){
String dateHolder = preview.getString("date");
//similarly for other strings
}
Then inflate the LinearLayout and start setting its elements.
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.your_xml, null);
//call findviewbyid on the layout and set its children using the strings you extracted
How to Pass a LinearLayout, it's contents intact, between Activities?
You don't. Widgets and containers (i.e., subclasses of View) are owned by their activity.
I can only assume there is an easier way
Have only one activity, altering its UI as needed (e.g., use fragments and replace them as needed). These seem to be way too closely coupled to be two separate activities.
The Goal here is to grab the Intent, and grab the bundle then pass it to my newPreview function (currently empty) that will duplicate finished preview from report_generator_activity and desplaying within the Linear Layout: rootWorkinglayout in an identical fashion.
There is nothing intrinsically wrong with this approach. You act as though you are having problems implementing it ("How do I unpack the data in an identical manner"), but we do not have nearly enough information on which to provide you with much advice. In general, a Bundle has getter methods, to retrieve that values that you put into the Bundle via the setter methods.

How to show different page if user is first time user (Android)

I have a blank-ish Android Project and what I want to do is take the user to a different "page/screen" if it is their first time only.
I know the logic for this but since I'm new to Android, I'm unsure of how to code this.
Below are the steps I believe I need to take in order to accomplish this:
App loads. If Local storage contains setting "FirstTimeUser", then it is not their first time using the app. Show the MainActivity page. If FirstTimeUser setting does not exist, it is their first time using the app (or they have uninstalled and reinstalled it), so instead, show WelcomeActivity page.
After viewing Welcome activity page, create FirstTimeUser setting and set to False.
But how do I code this for an Android app?
Use shared preferences as shown:
//declare as global
SharedPreferences prefs = null;
//and in your onCreate method:
prefs = getSharedPreferences("packageNameHere", MODE_PRIVATE);
if (prefs.getBoolean("firstrun", true)) {
//do stuff here if first run
//make sure to flag the boolean as false
prefs.edit().putBoolean("firstrun", false).commit();
}
else{
//if not first run, do something else
}
There is something called "SharedPreferences" that i believe your looking for.
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

Button to start the Gallery on Android

I'm trying to make a button in my App open the built in gallery.
public void onClick(View v) {
Intent intentBrowseFiles = new Intent(Intent.ACTION_VIEW);
intentBrowseFiles.setType("image/*");
intentBrowseFiles.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentBrowseFiles);
}
This results in an error message "The application Camera (process com.android.gallery) has stopped unexpectedly."
If I set the Intent action to ACTION_GET_CONTENT it manages to open the gallery but then simply returns the image to my app when a picture is selected which is not what I want.
I'm trying to make a button in my App open the built in browser.
Your question subject says "Gallery". Your first sentence in the question says "browser". These are not the same thing.
If I set the Intent action to ACTION_GET_CONTENT it manages to open the gallery but then simply returns the image to my app when a picture is selected which is not what I want.
Of course, actually telling us "what [you] want" would just be too useful, so you are making us guess.
I am going to go out on a limb and guess that you are trying to open the Gallery application just as a normal application. Note that there is no Gallery application in the Android OS. There may or may not be a Gallery application on any given device, and it may or may not be one from the Android open source project.
However, for devices that have the Android Market on them, they should support an ACTION_VIEW Intent with a MIME type obtained from android.provider.MediaStore.Images.Media.CONTENT_TYPE.

Categories