Shared Element transition from an Activity to a fragment in Another Activity - android

I’m working on a project in which I have to do a shared transition.
I want to perform a transition on an ImageView from my splash Activity [First Activity] to Login Activity [Second Activity] which has the ImageView in a Fragment. The Image in my 1st Activity and The Image in the fragment of my 2nd Activity are same and Shares The Same Transition Name. I’m unable to perform the transition.
My Splash Activity Code is This
public class Splash extends Activity implements View.OnClickListener{
private ImageView imageView;
private String SharedElementname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getWindow().setExitTransition(R.transition.shared_element_transition_a);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setSharedElementExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.shared_element_transition_a));
}
setContentView(R.layout.activity_splash);
imageView = (ImageView)findViewById(R.id.splashimage);
SharedElementname = getString(R.string.sharedname);
imageView.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_splash, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(this,v,SharedElementname);
Intent intent = new Intent(this, LoginActivity.class);
ActivityCompat.startActivity(this, intent, compat.toBundle());
}
My Login Activity Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(BuildConfig.MINT_API_ENABLED) {
Mint.initAndStartSession(LoginActivity.this, BuildConfig.MINT_API_KEY);
}
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.shared_element_transition_a));
}
setContentView(R.layout.activity_login);
}
Some More Codes….
*****************************************************************************
My Fragment Code Within Login Activty
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loginTab = new LoginTab();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setSharedElementReturnTransition(TransitionInflater.from(
getActivity()).inflateTransition(R.transition.shared_element_transition_a));
setExitTransition(TransitionInflater.from(
getActivity()).inflateTransition(android.R.transition.fade));
loginTab.setSharedElementEnterTransition(TransitionInflater.from(
getActivity()).inflateTransition(R.transition.shared_element_transition_a));
loginTab.setEnterTransition(TransitionInflater.from(
getActivity()).inflateTransition(android.R.transition.fade));
}
}
Some More Codes….
*************************************************************************************
My Splash Activity XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_new"
android:orientation="vertical"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:id="#+id/SplashLayout"
>
<ImageView
android:id="#+id/splashimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#drawable/eventifyd_logo"
android:transitionName="#string/sharedname"
/>
</RelativeLayout>
</LinearLayout>
My Transition XML File [Shared_element_transition]
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android" android:duration="5000">
<changeTransform />
<changeBounds />
<!—
I also tied ChangeImageTranform But Nothing Happened
-->
</transitionSet>
My Fragment XML File
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
>
<ImageView
android:id="#+id/profile_pic_login"
android:layout_above="#+id/login_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#drawable/eventifyd_logo"
android:transitionName="#string/sharedname"
/>
<TextView
android:layout_marginTop="30dp"
android:id="#+id/login_text"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/login_text"
style="#style/thin.white.large"/>
</RelativeLayout>
</LinearLayout>

I couldn't do it the way i was try. I changed the Fragments to Activity and it worked as a charm. I think Making transition from Activity to a Fragment of another activity is not Possible. Anyway, My this approach worked.

Related

Save and list contents in android

So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:onClick="save"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:onClick="list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
This is the XML for the second Activity which will be opened when the list button is clicked:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/show"
android:scrollbars="horizontal|vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="63dp" />
<TextView
android:text="#string/list_of_saved_url_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:id="#+id/textView"
android:textColor="#color/colorAccent"
android:textSize="24sp" />
</RelativeLayout>
This is my main class:
public class MainActivity extends AppCompatActivity {
private EditText url;
private Button save;
ArrayList<String> addArray = new ArrayList<String>();
private Button list;
private ListView show1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
list = (Button)findViewById(R.id.btn_list);
show1 = (ListView)findViewById(R.id.show);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = url.getText().toString();
if(addArray.contains(getInput))
{
Toast.makeText(getBaseContext(), "URL already added to the list!", Toast.LENGTH_LONG).show();
}
else if(getInput == null || getInput.trim().equals(""))
{
Toast.makeText(getBaseContext(), "Input field is empty!", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
((EditText)findViewById(R.id.txtbox_website)).setText("");
}
}
});
}
public void list(View view) {
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent screen = new Intent(MainActivity.this, Activity2.class);
startActivity(screen);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}http://www.stackoverflow.com
return super.onOptionsItemSelected(item);
}
}
My save button and list button is not able to save and list the URLs entered by the user.
What should I add?
Thanks
1) Not Saving:
Currently you are storing data statically inside your addArray object. Which gets cleared when you close app.
I think better to use persist data storage. So you can retrieve already stored websites when app re-launched. (Like browser manages history). Available storage options
2) Not showing list:
You need to pass your current list of urls (i.e. addArray variable) in bundle when starting Activity2 And read that list inside Activity2 onCreate. Find here.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
You don't need this list adapter inside your main activity, You need to create it inside Activity2 and set this adapter in your listview.
I hope it will help you fix your issues.

Best practices in the interaction between Activities

I am developing an application only to validate the interaction between activities through intents.
I created 5 ImageButton with an image for each. Each button is a movie and if you click any of them, is directed to a new activity with the synopsis of the film. The activity with the synopsis, there is an "up navigation" that returns the MainActivity (home).
The way I developed left very extensive project since created six activities (main activity and 5 activities, one for each film) and 6 layouts. Also, my apk is to 1.5mb.
Could someone help me with suggestions for best practices for I minimize my code or how developed is correct and could be developed in a real application?
I appreciate!!!
My MainActivity
package luizugliano.com.br.appfilmes;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void onClickBtVideo01(View view){
Intent intent = new Intent(getContext(),ActivityVideo01.class);
startActivity(intent);
}
public void onClickBtVideo02(View view){
Intent intent = new Intent(getContext(),ActivityVideo02.class);
startActivity(intent);
}
public void onClickBtVideo03(View view){
Intent intent = new Intent(getContext(),ActivityVideo03.class);
startActivity(intent);
}
public void onClickBtVideo04(View view){
Intent intent = new Intent(getContext(),ActivityVideo04.class);
startActivity(intent);
}
public void onClickBtVideo05(View view){
Intent intent = new Intent(getContext(),ActivityVideo05.class);
startActivity(intent);
}
private Context getContext(){
return this;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My ActivityVideo01 (other activities have the same code so I only put this as an example)
package luizugliano.com.br.appfilmes;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class ActivityVideo01 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_video01);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
//O método finish encerrará essa activity
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
My content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView android:text="Sinopse - Filmes" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="22dp"/>
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/layout_marginTop">
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton01"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:background="#drawable/btn_img_01"
android:onClick="onClickBtVideo01"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton02"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_02"
android:onClick="onClickBtVideo02"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton03"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_03"
android:onClick="onClickBtVideo03"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton04"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_04"
android:onClick="onClickBtVideo04"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton05"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_05"
android:onClick="onClickBtVideo05"/>
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
My content_activity_video01.xml (other layout have the same code so I only put this as an example)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_activity_video01"
tools:context="luizugliano.com.br.appfilmes.ActivityVideo01">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Title Synopsis"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Synopsis"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_marginTop="51dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I suggest, that you have two activities, and both these activities will act as container activity for their respective fragments.
In your first activity's fragment have your buttons. In your second activity's fragment, play your movie.
Now when you click on the button, go from first activity's fragment to second activity's fragment. Use interfaces to communicate between your fragments.
This is the way i thought about it, if you have a better way please do share.
Instead Of taking five different activity just take single activity and replace textview's value dynamically on the click of your button.
Just marge the two xml file like that in content_main.xml create another relative layout(which is initially gone view) with height width match parent under the image button linear layout. When one image button is pressed then just gone the view of linear layout of image buttons and visible the textview relative layout and visible the back button of the up navigation. When user pressed the up navigation just gone the textview relative layout, gone the up navigation and visible the linear layout of image button.
you need not to create multiple activities to show synopsis from different films.
you need to create your synopsis activity like a template and pass information about selected film in intent.
now you can change the content of your activity depending upon the information you received from intent.
Basically, whenever you are copying the code you need to ask yourself do you really need to copy the code? almost all the time answer is NO and what you actually need to do is, think of ways you can reuse the code you are copying.
Implement onclicklisstener and use switch case to detect which button has been clicked, Use only one activity to display synopsis instead of four and use bundle along with Intent to send which synopsis has to be shown. Here is the code.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
case R.id.imageButton01:
//handle click for imgbutton1;
Intent intent = new Intent(getContext(),ActivityVideo.class);
//send which video should be played along with the intent. use bundle in ActivityVideo class to get this value.
intent.putExtra("Video name", "video1");
startActivity(intent);
case R.id.imageButton02:
//handle click for imgbutton2;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video2");
startActivity(intent);
case R.id.imageButton03:
//handle click for imgbutton3;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video3");
startActivity(intent);
case R.id.imageButton04:
//handle click for imgbutton4;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video4");
startActivity(intent);
}
}
Use ActivityVideo class instid of ActivityVideo01, 02 ......
ActivityVideo.java ->
public class ActivityVideo01 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_video01);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle extras = intent.getExtras();
String VideoName = extras.getString("Video Name");
// VideoName will be having the sent value.
if(VideoName == "video1"){
//code for what do you want to do when imagebutton1 is clicked
}elseif(VideoName == "video2"){
//code for what do you want to do when imagebutton2 is clicked
}elseif(VideoName == "video3"){
//code for what do you want to do when imagebutton3 is clicked
}elseif(VideoName == "video4"){
//code for what do you want to do when imagebutton4 is clicked
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
//O método finish encerrará essa activity
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hope it helps!

Android fragments xml crash

I keep getting a crash when I change my set content view to an xml layout and not sure whats wrong. The program is supposed to have two fragments, a list view on the left and a webview on the right when it is in landscape and just the list in portrait. Sorry for all the code, I just can not figure out what is going on.
Here is my main activity
public class MainActivity extends Activity {
static final String LOGTAG = MainActivity.class.getSimpleName() + "_TAG";
static Resources mRes = null;
static FragmentManager mFrgmntMngr = null;
static MainActivity mThisAct = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager.enableDebugLogging(true);
setContentView(R.layout.activity_main_1view);
mRes = getResources();
mFrgmntMngr = getFragmentManager();
mThisAct = this;
}
static boolean isInLandscapeOrientation() {
return mRes.getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void displayTwainText(int mCurPosition) {
// TODO Auto-generated method stub
if ( isInLandscapeOrientation() ) {
// Check what fragment is shown, replace if needed.
TwainTitleWebViewFragment tTxtFrgmnt = (TwainTitleWebViewFragment)
mFrgmntMngr.findFragmentById(R.id.twain_title_list);
if (tTxtFrgmnt == null || tTxtFrgmnt.getDisplayedTwainIndex() !=mCurPosition)
// Make new fragment to show this selection.
tTxtFrgmnt = TwainTitleWebViewFragment.newInstance(mCurPosition);
// Execute a transaction, replacing any existing
// fragment inside the frame with the new one.
Log.d(LOGTAG, "about to run FragmentTransaction...");
FragmentTransaction frag_trans
= mFrgmntMngr.beginTransaction();
frag_trans.setCustomAnimations(R.animator.bounce_in_down,
R.animator.fade_out);
frag_trans.setCustomAnimations(R.animator.bounce_in_down,
R.animator.slide_out_right);
frag_trans.replace(R.id.list, tTxtFrgmnt);
frag_trans.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(mThisAct, TwainTitleViewActivity.class);
intent.putExtra(mRes.getString(R.string.twain_index_key), mCurPosition);
this.startActivity(intent);
}
}
}
This is activity_main1view.xml in the lay out folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment class="com.example.hw_07_final_.TitleListFragment"
android:id="#+id/twain_title_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
this is the one in layout-land
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment class="com.example.hw_07_final_.TitleListFragment"
android:id="#+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="#00550033"/>
<FrameLayout
android:id="#+id/twain_text"
android:layout_weight="4"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
this is the log cat
You CANNOT have numbers or uppercase letters when naming your xml files.
activity_main1view.xml should be activity_mainview.xml excluding "1" from the layout name.
Change
<fragment class="com.example.hw_07_final_.TitleListFragment"
To
<fragment android:name="com.example.hw_07_final_.TitleListFragment"
Run your app and it will inflate your fragment.

Unfortunately "app_name" has stopped

Hello I am new in android developping, I made a small test but it's giving me that error :
'Unfortunately android test has stopped'
I sought some similar topics here, but no one resolved my problem, here is my code :
main activity :
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
final EditText username = (EditText) findViewById(R.id.username);
final EditText password = (EditText) findViewById(R.id.password);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(checkLogin(username.getText().toString(),password.getText().toString())){
Intent i = new Intent(MainActivity.this, HelloActivity.class);
startActivity(i);
}
else{
username.setText("");
password.setText("");
}
}
});
}
private boolean checkLogin(String u,String p){
if (u == "hello" && p == "world")
return true;
else return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
the main layout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.androidtest.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:ems="10"
android:hint="username" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/username"
android:layout_below="#+id/username"
android:ems="10"
android:hint="password"
android:inputType="textPassword" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/username"
android:layout_below="#+id/password"
android:text="Button" />
</RelativeLayout>
the second acivity
package com.androidtest;
import android.app.Activity;
import android.os.Bundle;
public class HelloActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.hello_layout);
}
}
its layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="193dp"
android:text="Afin akhay lpchiiwr"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
and finally the Manifest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.androidtest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.androidtest.HelloActivity"></activity>
</application>
</manifest>
Thanx
The first xml block you've posted looks like it's from the fragment_main.xml file. If so, then your problem is that findViewById() is looking for Views in the Activity that have been inflated into the Fragment. If you don't need the Fragment, then move that xml to activity_main.xml and remove the code for the Fragment. Otherwise, move the View initializations and methods to your Fragment.
And, as Kedarnath points out, you should use the String.equals() method to compare Strings.
First of all let me tell you that you are comparing String in wrong way,
private boolean checkLogin(String u,String p)
{
if (u == "hello" && p == "world") // Wrong way
return true;
else return false;
}
You need to compare string in following way,
private boolean checkLogin(String u,String p)
{
if (u.equals("hello") && p.equals("world") ) // Right way
return true;
else return false;
}

Android: problem creating user form from a menu

I'm very new to programming in Android, but have been struggling all day with a problem and would appreciate your help.
I'm trying to create a form to get user information (essentially a new contact) which is accessed from the menu. When I click the button to create the new form, I get the following error:
"Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#626fd5e0"
This is my code:
The menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/search"
android:title="#string/settings_search"
android:alphabeticShortcut="#string/settings_shortcut_search" />
<item android:id="#+id/new_contact"
android:title="#string/settings_new"
android:alphabeticShortcut="#string/settings_shortcut_new" />
</menu>
The code for calling the new activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_contact:
//activities to create a new account
//startActivity(new Intent(this, Prefs.class));
Intent i = new Intent(MainActivity.this, NewContact.class);
startActivity(i);
//addSaver("String");
return true;
case R.id.search:
return true;
// More items go here (if any) ...
}
return false;
}
The view for the new contact activity:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">"
<LinearLayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="top">
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is a test\nsecond line\n"/>
<Button
android:id="#+id/new_contact_button"
android:layout_height="wrap_content"
android:text="#string/submit" />
</LinearLayout>
</ScrollView>
And the code for the new activity:
public class NewContact extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_contact);
// Set up click listeners for all the buttons
View newContactButton = findViewById(R.id.new_contact_button);
newContactButton.setOnClickListener(this);
}
Bizarrely if I comment out the button from the class and from the xml then it works correctly and opens up the new activity (but of course I can't do anything with that activity).
In your button xml code, you are missing
android:layout_width="wrap_content"
add that and give it a shot.

Categories

Resources