This piece of Android code keeps crashing. I need assistance? - java

This is the code I did. But it did not work. Please help?
The app itself lets the user enter his/her name on the EditText, he clicks on the button and the TextView will say like for example his name is Sam. "Your name is Sam".
package com.example.myfirstandroidapp;
import java.text.Format.Field;
import java.util.EventListener;
import javax.security.auth.PrivateCredentialPermission;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
import android.provider.ContactsContract.CommonDataKinds.Event;
public class MainActivity extends ActionBarActivity {
EditText nameTextBox;
TextView nameTextView;
Button nameButton;
#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();
}
nameTextBox = (EditText)findViewById(R.id.nameTextBox);
nameTextView = (TextView)findViewById(R.id.nameTextView);
nameButton = (Button)findViewById(R.id.nameButton);
nameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Clicker();
}
});
}
public void Clicker()
{
if (nameTextBox.getText().toString() != "")
{
nameTextView.setText("Your name is " + nameTextBox.getText().toString());
}
}
#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;
}
}
}
Xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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.example.myfirstandroidapp.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Enter your name:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/nameTextBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nameTextBox"
android:layout_below="#+id/nameTextBox"
android:text="I&apos;m Done!" />
<TextView
android:id="#+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nameButton"
android:layout_below="#+id/nameButton"
android:text="Your name has not been entered yet"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Replace
nameTextBox.getText().toString() != ""
with
!nameTextBox.getText().toString().equals("")
Probably this is your error.

Just Change your code by below code :
package com.example.myfirstandroidapp;
import java.text.Format.Field;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
EditText nameTextBox;
TextView nameTextView;
Button nameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTextBox = (EditText)findViewById(R.id.nameTextBox);
nameTextView = (TextView)findViewById(R.id.nameTextView);
nameButton = (Button)findViewById(R.id.nameButton);
nameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Clicker();
}
});
}
public void Clicker()
{
if (!nameTextBox.getText().toString().equals(""))
{
nameTextView.setText("Your name is " + nameTextBox.getText().toString());
}
}
}
As per your need there is not any requirement of fragments.

Your error probably is that this should be inside onCreateView() in your PlaceHolderFragment rather than in activity
nameTextBox = (EditText)findViewById(R.id.nameTextBox);
nameTextView = (TextView)findViewById(R.id.nameTextView);
nameButton = (Button)findViewById(R.id.nameButton);

In your layout nameTextBox,nameTextBox,nameButton are null,because those are part of fragment not activity_main.
So either use nameTextBox,nameTextBox,nameButton in activity_main layout. or use in onCreateView method of fragment.
For more info see Access Fragment View from Activity's onCreate

The lifecycle of a Fragment is tied to that of its host activity. For example the onActivityCreate() method of a Fragment is called after the host Activity calls its own onCreate method. You are getting an error because you are trying to access View objects that are contained within your Fragment layout from within your activity. This creates a problem because (1) those views do not exist yet at the time the host Activity calls onCreate() because the fragment has yet to be created; (2) findViewById() only searches within the contentView of Activity or Fragment that it is called from (i.e. if you look for a view that is within your Fragment's layout from within the host activity it findViewById will return null becuase the view is not within the Activity's layout).
What you need to do is move the code from your activity's onCreate method to your fragment. You can put this in either onActivityCreated or onViewCreated within your fragment and should access and set content from within the fragment itself. If you need access to the fragment contents you can keep a reference to the fragment within your hosting activity and access public methods within your fragment class.
You should set things up like this
public class PlaceholderFragment1 extends Fragment{
private EditText mNameTextBox;
private TextView mNameTextView;
private Button mNameButton;
public void onActivityCreate(Bundle savedInstanceState){
mNameTextBox = (EditText)findViewById(R.id.nameTextBox);
mNameTextView = (TextView)findViewById(R.id.nameTextView);
mNameButton = (Button)findViewById(R.id.nameButton);
mNameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mNameTextBox.getText().toString().isEmpty()){
mNameTextView.setText(
"Your name is "+mNameTextBox.getText().toString());
}
});
}
}
I adapted your dropbox code to fix the issues you mentioned.

Related

how to implement pull-down to refresh in java

I am going to make a pull down refresh option for my webview , i got the xml code and its working, but i don't know how to make it work properly by using java, i am using app drawer activity and this is my first fragment (home_fragment in code)
here is the xml code
<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"
tools:context="com.fb.jaisonjoseph.facebookbasic.Home_Fragment">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" />
</android.support.v4.widget.SwipeRefreshLayout>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:animationResolution="#integer/abc_max_action_buttons"
android:clickable="false"
android:theme="#style/Base.Theme.AppCompat"
android:indeterminate="false"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
here is my java code in the Home_Fragment.java
package com.fb.jaisonjoseph.facebookbasic;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.view.KeyEvent;
/**
* A simple {#link Fragment} subclass.
*/
public class Home_Fragment extends Fragment {
public ProgressBar bar;
SwipeRefreshLayout mySwipeRefreshLayout;
public WebView mwebView;
public Home_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home_, null);
final WebView view=(WebView) rootView.findViewById(R.id.webView);
view.loadUrl("https://mbasic.facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
view.getSettings().setBuiltInZoomControls(true);
view.getSettings().setDisplayZoomControls(false);
bar=(ProgressBar)rootView.findViewById(R.id.progressBar);
return rootView;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
}
First declare swiperefresh in .Java file.
SwipeRefreshLayout swiperefresh=(SwipeRefreshLayout) findViewById(R.id.swiperefresh);
then you need to use setOnRefreshListener, so whenever the layout is swiped down, setOnRefreshListener will be called
swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// code to refresh
swiperefresh.setRefreshing(false); //code to stop refresh animation
}
});
Add this into your onCreateView() method ,
mySwipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swiperefresh);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// logic to refresh then add the following line to stop refresh animation
mSwipeRefreshLayout.setRefreshing(false);
}
});
Disable vertical scrolling in WebView, set its 'height' attribute to 'wrap_content'. By doing so, WebView will take entire hight of web page. Then put WebView to ScrollView and it, in turn, into SwipeRefreshLayout.

BottomBar fragments in Android studio

How can I add fragments for each tab in BottomBar in Android studio please a good example like list view or grid view for each tab..thanks
You need to implement SetOnTabSelectListerner.
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
Fragment fragment = null;
Class fragmentClass = null;
switch (tabId) {
case R.id.tab_one:
fragmentClass = TabOneFragment.class;
break;
case R.id.tab_two:
fragmentClass = TabTwoFragment.class;
break;
case R.id.tab_three:
fragmentClass = TabThreeFragment.class;
break;
case R.id.tab_four:
fragmentClass = TabFourFragment.class;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
});
main_activity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements communicator{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(int i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00BBFF"
android:orientation="vertical"
tools:context="com.example.dhanya.myfragmentexample.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentexample.FragmentA"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentexample.FragmentB"
/>
</android.widget.LinearLayout>
fragmentA.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{
ListView list;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
list=(ListView)getActivity().findViewById(R.id.lv);
ArrayAdapter ad=ArrayAdapter.createFromResource(getActivity(),R.array.listval,android.R.layout.simple_list_item_1);
list.setAdapter(ad);
list.setOnItemClickListener(this);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt=(TextView)view;
String str=txt.getText().toString();
comm.respond(position);
}
}
fragmentA.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentexample.FragmentA"
android:background="#FFBB00">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv"/>
</FrameLayout>
fragmentB.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.textv);
}
public void changedata(int i)
{
Resources res=getResources();
String[] des=res.getStringArray(R.array.desciptions);
// String str=Integer.toString(i);
txt.setText(des[i]);
// txt.setText(str); }}
fragmentB.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentexample.FragmentB"
android:background="#99CC00"
>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textv"/>
</FrameLayout>
strings.xml
<resources>
<string name="app_name">MyFragmentExample</string>
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>
<string-array name="listval">
<item>fragments</item>
<item>Activities</item>
<item>Services</item>
<item>Content Providers</item>
</string-array>
<string-array name="desciptions">
<item>A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).</item>
<item>Activities are one of the fundamental building blocks of apps on the Android platform. They serve as the entry point for a user's interaction with an app, and are also central to how a user navigates within an app (as with the Back button) or between apps (as with the Recents button). </item>
<item>A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.</item>
<item>Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. Implementing a content provider has many advantages. </item>
</string-array>
</resources>
communicator.java
public interface communicator {
public void respond(int i);
}
//Grid view
main_activity.xml
<ScrollView xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="#+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="50dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
</RelativeLayout>
</ScrollView>
mainactivity.java
package com.example.harish.mylayoutexamples;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class GridActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
GridView gridView;
static final String[] numbers = new String[] {
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridView = (GridView) findViewById(R.id.gridview1);
// Create adapter to set value for grid view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
/* gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText() , Toast.LENGTH_SHORT).show();
}
});*/
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText() , Toast.LENGTH_SHORT).show();
}
}
fragments dynamic loading
Main activity. Java
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button firstFragment, secondFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of Button's
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = (Button) findViewById(R.id.secondFragment);
// perform setOnClickListener event on First Button
firstFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load First Fragment
loadFragment(new FirstFragment());
}
});
// perform setOnClickListener event on Second Button
secondFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load Second Fragment
loadFragment(new SecondFragment());
}
});
}
private void loadFragment(Fragment fragment) {
// create a FragmentManager
FragmentManager fm = getFragmentManager();
// android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
//fragmentTransaction.add(R.id.firstFragment,fragment);
fragmentTransaction.commit(); // save the changes
}
#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);
}
}
MAIN_ACTIVTY.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".MainActivity">
<!-- display two Button's and a FrameLayout to replace the Fragment's -->
<Button
android:id="#+id/firstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/button_background_color"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<Button
android:id="#+id/secondFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#color/button_background_color"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>
FIRST_FRAGMENT.JAVA
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstFragment extends Fragment {
View view;
Button firstButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_first, container, false);
// get the reference of Button
firstButton = (Button) view.findViewById(R.id.firstButton);
// perform setOnClickListener on first Button
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "First Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
FIRST_FRAGMENT>XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.fragmentexample.FirstFragment">
<!--TextView and Button displayed in First Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is First Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/firstButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
SECOND_FRAGMENT>JAVA
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class SecondFragment extends Fragment {
View view;
Button secondButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_second, container, false);
// get the reference of Button
secondButton = (Button) view.findViewById(R.id.secondButton);
// perform setOnClickListener on second Button
secondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "Second Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
SECOND_FRAGMENT>XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.fragmentexample.SecondFragment">
<!--TextView and Button displayed in Second Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is Second Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/secondButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
main_activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(String i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentcommsimple.MainActivity"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentA">
</fragment>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentB">
</fragment>
</android.widget.LinearLayout>
fragment_A.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
public class FragmentA extends Fragment implements View.OnClickListener{
int count=0;
Button bt;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
bt=(Button)getActivity().findViewById(R.id.btn);
bt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
count++;
comm.respond("The button is clicked "+ count+" times");
}
}
FRAGMET_A.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentcommsimple.FragmentA"
android:background="#99FF00">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn"
android:text="counter"
android:layout_margin="40dp"/>
</FrameLayout>
FRAGMENT_B.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.tv);
}
public void changedata(String i)
{
txt.setText(i);
}
}
FRAGMENT_B.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dhanya.myfragmentcommsimple.FragmentB"
android:background="#FFBB00">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="haiiii"
android:id="#+id/tv"
android:layout_margin="50dp"/>
</FrameLayout>
COMMUNICATOR.java
package com.example.dhanya.myfragmentcommsimple;
public interface communicator {
public void respond(String i);
}

Text field and send button disappear when running MyFirsApp

I am trying to build my first android app (MyFirstApp) using the "Building Your First App" tutorial on the Android Developers website (https://developer.android.com/training/basics/firstapp/index.html). I have reached the end of the "Starting Another Activity" portion of the tutorial, where I am meant to run the app, type in some text and click the send button. When I run the app I get no errors, a few warnings and a blank screen with only the title of my app.How can I resolve this?
Below is my code so far:
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_messages"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_messages" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyFirstApp</string>
<string name="edit_messages">Enter a message</string>
<string name="button_send">Send</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="title_activity_display_message">My Message</string>
<string name="hello_world">Hello world!</string>
</resources>
MainActivity.java
package my.first.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.content.Intent;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#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;
}
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_messages);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package my.first.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
//Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
}
#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_display_message,
container, false);
return rootView;
}
}
}
fragment_display_message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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="my.first.app.DisplayMessageActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Please Add below code line after super.onCreate(savedInstanceState); in onCreate() Method of MainActivity Class, it will solve your problem.
setContentView(R.layout.fragment_main);
you forgot setContentView() in MainActivity..
Define setContentView(R.layout.fragment_main); after savedInstance

What's wrong with Eclipse (Unfortunately app has stopped) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm pretty new with eclipse im trying to set the text with the help of a button on eclipse (just first steps in learning)
But whenever i identify an onSetClickListener and try to run application on emulator i get this error "Unfortunately app has stopped"
Here are my codes
MainActivity.java
package com.example.androidjii;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button changer;
TextView changeme;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changer = (Button) findViewById(R.id.change1);
changeme = (TextView) findViewById (R.id.changeme1);
changer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
changeme.setText("Changed");
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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;
}
}
}
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
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.example.androidjii.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/changeme1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/yazi" />
<Button
android:id="#+id/change1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/changeme1"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="Change It" />
</RelativeLayout>
Need your help to solve it. What is wrong with my codes or way?
Update:
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.androidjii.MainActivity"
tools:ignore="MergeRootFrame" />
This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.
Move that piece of code in the onCreateView() method of the fragment:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
Notice that now you access it through rootView view:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.
In your code, move
changer = (Button) findViewById(R.id.change1);
changeme = (TextView) findViewById (R.id.changeme1);
changer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
changeme.setText("Changed");
}
});
to onCreateView() method of the fragment

Can't get text from editText Android Eclipse

I'm having some issues with my school project. I can't get the text from the textbox. I searched for a solution but nothing found.. I'll be grateful if somebody help me :)
So here is my Java code:
package com.src.vicnote;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class NewNoteActivity extends ActionBarActivity {
Button saveButton;
EditText textData;
Context context;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
//text = "this is sparta!";
Log.d("ADebugTag", "string: \"" + text + "\" end of note text");
new SaveClass(text/*, context.getApplicationContext()*/);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_note, 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_new_note,
container, false);
return rootView;
}
}
}
And my XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.src.vicnote.NewNoteActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonSave"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Save" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
Also I want to ask you what will happen if the text is cyrillic? Will be there any problem?
Try initializing textData outside of your OnClickListener:
textData = (EditText) findViewById(R.id.editText);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() { //...
I was also stuck at finding method to get text from edittext. I got resolved this issue by doing the below,
String selQuantity = (((TextView)findViewById(R.id.etxtQuantity)).getText()).toString();
Try this. It works.

Categories

Resources