xml layout loads but my activity doesn't respond to button clicks - android

I'm new at this but I already made a small app that worked the same way.
I can't see what I'm doing wrong because the code looks quiet the same as my previous app.
When I run it or debug my app it shows my layout on my emulator so it does load the page that has to be loaded but that's all it does, it doesn't listen to button clicks. I also gives me no errors.
Here's my XML code for fragment_main.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:text="Eventaris"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="100px"
android:textStyle="bold"
android:id="#+id/lblEventaris"
/>
<LinearLayout
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:id="#+id/login">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Gebruikersnaam"
android:id="#+id/txtGebruikersnaam"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Wachtwoord"
android:inputType="textPassword"
android:layout_below="#id/txtGebruikersnaam"
android:id="#+id/txtWachtwoord"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Inloggen"
android:id="#+id/btnInloggen"
android:layout_below="#id/txtWachtwoord"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_below="#id/login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nog geen account?"
android:gravity="center"
android:id="#+id/lblRegistratie"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registeren"
android:id="#+id/btnRegistreren"
android:layout_below="#id/lblRegistratie"/>
</RelativeLayout>
</RelativeLayout>
Here's my fragmennt activity MainFragment.Java
package com.example.arno.eventaris;
import android.app.Activity;
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.EditText;
import java.sql.SQLException;
/**
* Created by Arno on 28/04/2015.
*/
public class MainFragment extends Fragment {
private OnMainFragmentInteractionListener mListener;
private View view;
public MainFragment()
{
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.fragment_main, container, false);
Button btnInloggen = (Button) view.findViewById(R.id.btnInloggen);
btnInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
inloggen();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
Button btnRegistreren = (Button) view.findViewById(R.id.btnRegistreren);
btnRegistreren.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
navigeerRegistratie();
}
});
return view;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try{
mListener = (OnMainFragmentInteractionListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + "must implement OnFragmentInteractionListener");
}
}
public void inloggen() throws SQLException {
EditText gebr=(EditText) view.findViewById(R.id.txtGebruikersnaam);
EditText wachtw=(EditText) view.findViewById(R.id.txtWachtwoord);
String gebruiker = gebr.getText().toString();
String wachtwoord = wachtw.getText().toString();
mListener.login(gebruiker, wachtwoord);
}
public void navigeerRegistratie()
{
mListener.navigeerRegistratie();
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnMainFragmentInteractionListener {
//Todo: Update argument type and name
public void login(String gebruiker, String wachtwoord) throws SQLException;
public void navigeerRegistratie();
}
}
Here is my Main Activity MainActivity.java
package com.example.arno.eventaris;
import android.app.DialogFragment;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
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.widget.LinearLayout;
import android.widget.Toast;
import com.example.arno.eventaris.Database.DBAdapter;
import java.sql.SQLException;
public class MainActivity extends ActionBarActivity implements MainFragment.OnMainFragmentInteractionListener,RegistratieFragment.OnRegistratieFragmentInteractionListener{
private Cursor gebruikerCursor;
#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();
}
}
#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);
}
#Override
public void login(String gebruiker, String wachtwoord) throws SQLException {
DBAdapter db = new DBAdapter(this);
db.open();
gebruikerCursor = db.getGebruiker(gebruiker);
if(gebruikerCursor.moveToFirst()) {
gebruikerCursor.moveToFirst();
String wwControle = gebruikerCursor.getString(gebruikerCursor.getColumnIndex("wachtwoord"));
if (wachtwoord.equals(wwControle)) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("gebruikersnaam", gebruiker);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
} else {
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Wachtwoord incorrect!");
}
}
else
{
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Gebruikersnaam incorrect!");
}
db.close();
}
#Override
public void navigeerRegistratie() {
getFragmentManager().beginTransaction().replace(R.id.container, new RegistratieFragment()).commit();
}
#Override
public void registreren(String gebruiker, String voornaam, String naam, String email, String wachtwoord, String herhaalWachtwoord) {
if(wachtwoord.equals(herhaalWachtwoord)) {
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertGebruiker(gebruiker, voornaam, naam, email, wachtwoord);
getFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit();
}
else
{
DialogFragment errorregistratie = new ErrorRegistratie();
errorregistratie.show(getFragmentManager(), "Wachtwoorden komen niet overeen!");
}
}
/**
* 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;
}
}
}
And as last here is my 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=".MainActivity" tools:ignore="MergeRootFrame" />
Thanks in advance!

Fixed it by making a new project with the same code, had to be a problem way deeper than my code.

Related

EditText editable but getText() return empty string

I'm trying to make a simple messaging system in my app. The user type the message in an EditTextat the bottom of the screen. Somehow, the EditTextthat's displayed on the screen isn't actually the one that I get using findViewById().
I tried adding default value to the EditTextin the xml and it works. But if I change the default text, the text on the screen changes but editText.getText()still returns the default value. editText.setText() doesn't change the text displayed on the screen but does change the actual value (editText.getText() returns the new text).
Here's my code:
fragment_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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.gloriovin.helpio.Views.MessageFragment"
android:id="#+id/message_fragment"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/sendMessageSection"
android:id="#+id/listView"
android:clipToPadding="false"
android:divider="#color/Transparent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"></ListView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="45dp"
android:id="#+id/sendMessageSection"
android:layout_alignParentBottom="true"
android:background="#color/LightGrey">
<com.mikepenz.iconics.view.IconicsImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/sendButton"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="3dp"
app:iiv_size="25dp"
app:iiv_color="#color/DarkGrey"
app:iiv_icon="gmd-send" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/messageField"
android:layout_toLeftOf="#id/sendButton"
android:singleLine="true"
android:text="kuda"
android:layout_marginLeft="10dp"
android:layout_marginRight="3dp"
android:gravity="bottom"/>
</RelativeLayout>
</RelativeLayout>
chatActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.gloriovin.helpio.R;
public class ChatActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Message");
MessageFragment messageFragment = new MessageFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, messageFragment). 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.menu_message, 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);
}
}
messageFragment.java
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import com.gloriovin.helpio.Adapters.friendAdapters;
import com.gloriovin.helpio.Adapters.messageAdapters;
import com.gloriovin.helpio.Globals;
import com.gloriovin.helpio.HelpioApp;
import com.gloriovin.helpio.Models.Message;
import com.gloriovin.helpio.Models.MessageRoom;
import com.gloriovin.helpio.R;
import com.mikepenz.iconics.view.IconicsImageView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.zip.Inflater;
import cz.msebera.android.httpclient.Header;
import io.paperdb.Paper;
public class MessageFragment extends Fragment {
private Activity activity;
private int mid;
public MessageFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_message, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mid = getActivity().getIntent().getIntExtra("mid", -1);
this.activity = getActivity();
Log.e("mid", String.valueOf(mid));
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView = (ListView) getActivity().findViewById(R.id.listView);
messageAdapters adapter = new messageAdapters(getActivity(), FAKECHAT);
listView.setDivider(null);
listView.setAdapter(adapter);
IconicsImageView sendButton = (IconicsImageView) getActivity().findViewById(R.id. sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText newMessage = (EditText) getActivity().findViewById(R.id.messageField);
String msg = newMessage.getText().toString();
Log.e("message is", "asd"+msg);
}
});
}
#Override
public void onDetach() {
super.onDetach();
}
}
TLDR:
in messageFragment.java, the EditText value(.getText()) is different (empty string "") than what actually typed in the EditText.
setText()doesn't change the appearance of the EditTextbut does change the result of getText()
Here:
EditText newMessage = (EditText) getActivity().findViewById(R.id.messageField);
Probably getting NPE Exception because newMessage is null.
EditText with messageField is inside fragment_message layout which is layout of Fragment. so use getView method for initializing newMessage object instead of getActivity() which return the Context of Activity in which Fragment is current available.
override onViewCreated and initialize all views using v.findViewById :
ListView listView;
IconicsImageView sendButton;
EditText newMessage;
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
listView = (ListView) v.findViewById(R.id.listView);
sendButton = (IconicsImageView) v.findViewById(R.id. sendButton);
newMessage = (EditText) v.findViewById(R.id.messageField);
}
Write this line, outside of your click listener
EditText newMessage = (EditText) getActivity().findViewById(R.id.messageField);
You are not fetching EditText properly.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_message, container, false);
newMessage = (EditText) mView.findViewById(R.id.messageField);
String msg = newMessage.getText().toString();
return mView;
}

Text is not getting entered in the edit text control

When I am trying to create tab control and add an edit text in Android, and then enter any character from UI (within Tab1 for Edit Text), the text is not getting entered in the edit text control. I am using Android Studio 1.1.0. Code is as follows.
Main Activity.class
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static final String TAB_1_TAG = "one";
private static final String TAB_2_TAG = "two";
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tabs);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle b = new Bundle();
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Tab1"), FirstContainerFragment.class, b);
b.putString("key", "One");
b = new Bundle();
b.putString("key", "Two");
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Tab2"), SecondContainerFragment.class, b);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
}
my_tab.xml
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
BaseContainerFragment.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
container_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
FirstContainerFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
private void initView() {
replaceFragment(new FirstFragment(), false);
}
}
FirstFragment.java
import android.app.Activity;
import android.os.Bundle;
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.EditText;
import android.widget.TextView;
public class FirstFragment extends Fragment {
EditText edtTxt;
TextView txtView;
Button btnEnter;
public FirstFragment() {
// TODO Auto-generated constructor stub
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(getActivity()).inflate(R.layout.first_layout,null);
edtTxt =(EditText)v.findViewById(R.id.editText);
txtView =(TextView)v.findViewById(R.id.textText222);
btnEnter = (Button)v.findViewById(R.id.button);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
txtView.setText(edtTxt.getText());
}
});
}
}
similarly I have the following class and layouts
SecondContainerFragment.java
SecondFragment.java

Android Fragments UI Design Example

I am getting error following error. give me a suggestion if you faced the same issue.
fragmentslayout\app\src\main\java\com\example\fragmentslayout\app\MainActivity.java
Error:(9, 8) error: MainActivity is not abstract and does not override abstract method Message(String) in Communicator
fragmentslayout\app\src\main\java\com\example\fragmentslayout\app\MyListFragment.java
Error:(23, 28) error: incompatible types: OnItemSelectedListener cannot be converted to Communicator
My Code:
MainActivity.java
package com.example.fragmentslayout.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity implements Communicator
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
#Override
public void onRssItemSelected(String OS_Name) {
DetailFragment detailfragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail_Fragment);
if (detailfragment != null && detailfragment.isInLayout()) {
detailfragment.setText(OS_Name);
}
}
}
DetailFragment.java
package com.example.fragmentslayout.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
return view;
}
// we call this method when button from listfragment is clicked
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.display_tv);
view.setText(item);
}
}
MyListFragment.java
package com.example.fragmentslayout.app;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MyListFragment extends Fragment implements OnClickListener
{
private Communicator communicator;
Button android_btn, ios_btn, windows_btn;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.Communicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
// Initialize Views
android_btn = (Button) view.findViewById(R.id.android_btn_id);
ios_btn = (Button) view.findViewById(R.id.ios_btn_id);
windows_btn = (Button) view.findViewById(R.id.windows_btn_id);
// set on click Listeners for buttons
android_btn.setOnClickListener(this);
ios_btn.setOnClickListener(this);
windows_btn.setOnClickListener(this);
return view;
}
public interface OnItemSelectedListener {
public void Message(String OS_Name);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.android_btn_id:
updateFragment("Android");
break;
case R.id.ios_btn_id:
updateFragment("IOS");
break;
case R.id.windows_btn_id:
updateFragment("Windows");
break;
}
}
private void updateFragment(String OS_Name) {
communicator.Message(OS_Name);
}
}
Communicator Interface
package com.example.fragmentslayout.app;
public interface Communicator {
public void Message(String tutUri);
}
Layout:
activity_main.xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<fragment
android:id="#+id/list_Fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
class="com.example.fragmentslayout.app.MyListFragment" >
</fragment>
<fragment
android:id="#+id/detail_Fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
class="com.example.fragmentslayout.app.DetailFragment" >
</fragment>
</LinearLayout>
detail_fragment.xml
<?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="#FFFF99"
android:orientation="vertical"
android:padding="20dp" >
<TextView
android:id="#+id/display_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="40sp" />
</LinearLayout>
list_fragment.xml
<?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="#CCFF99"
android:orientation="vertical"
android:padding="5dp" >
<Button
android:id="#+id/android_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android" />
<Button
android:id="#+id/ios_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IOS" />
<Button
android:id="#+id/windows_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Windows" />
</LinearLayout>
Your MainActivity implements Communicator,so you must override abstract method Message(String). Just add the method Message(String) to your MainActivity.
Your MainActivity implements Communicator, is your Communicator in activity same Communicator in fragment!!,so you must override abstract method Message(String), move your code in onRssItemSelected(string) function to new message function
just add this function to mainactivity
#Override
public void Message(String OS_Name) {
DetailFragment detailfragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail_Fragment);
if (detailfragment != null && detailfragment.isInLayout()) {
detailfragment.setText(OS_Name);
}
}

Android app stop when is being to run

I'm new to android and java. this is my first app. an example of a book. I did all steps according the book. the app is going to increase the number by click on + button
this is my Java file :
package com.example.myprayercounter;
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.widget.Button;
import android.widget.TextView;
import android.os.Build;
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();
}
}
#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 {
int counter;
TextView tView;
Button btn;
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
tView.setText(" " + counter);
}
});
return rootView;
}
}
}
xml file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fbfbdd"
android:gravity="center_horizontal"
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="com.example.myprayercounter.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/txt_textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="تعداد ذکرهای من"
android:textColor="#763f05"
android:textSize="20dp" />
<TextView
android:id="#+id/txt_textTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#763f05"
android:textSize="40dp" />
<Button
android:id="#+id/btn_buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#763f05"
android:text="+"
android:textColor="#fbfbdd"
android:textSize="40dp" />
</LinearLayout>
I got this error at first run of the app :
What is my mistakes? and how i can fix them?
Thanks in advance
change:
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
to ( getActivity() --> rootView)
tView = (TextView)rootView.findViewById(R.id.txt_textTwo);
btn = (Button)rootView.findViewById(R.id.btn_buttonOne);
in PlaceholderFragment, your View is rootView and you need find your view from that

get null pointer error when trying to getText

I am new to Android, so please forgive my ignorance. I have tried searching the forums, but haven't been able to find anything to get this to work. I am trying to use .getText().toString() (see below), but get a java.lang.NullPointerException error. I changed my setContentView so that it would look at the fragment_main.xml, but still returns a null for my different components. The goal of this is very simple, just to change the text on the TextView, since I am just getting started. Any help would be appreciated.
package com.example.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.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Button changeTxt = (Button) findViewById(R.id.btnChangeText);
final TextView textView = (TextView) findViewById(R.id.txtMessage);
changeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = textView.getText().toString();
if (text.contains("World")) {
textView.setText("Hello Android!");
}
else {
textView.setText(("Hello World!"));
}
}
});
}
public void onStart(){
super.onStart();
}
public void onResume(){
super.onResume();
}
public void onPause(){
super.onPause();
}
public void onStop(){
super.onStop();
}
public void onDestroy(){
super.onDestroy();
}
#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;
}
}
}
Here is the xml:
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/txtMessage"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/btnChangeText"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Fllo, updated code:
XML fragment_main.xml
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/txtMessage1"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/btnChangeText1"
android:layout_gravity="center" />
</FrameLayout>
</LinearLayout>
main activity
package com.example.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.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void onStart(){
super.onStart();
}
public void onResume(){
super.onResume();
}
public void onPause(){
super.onPause();
}
public void onStop(){
super.onStop();
}
public void onDestroy(){
super.onDestroy();
}
#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);
Button changeTxt = (Button) findViewById(R.id.btnChangeText);
final TextView textView = (TextView) findViewById(R.id.txtMessage);
changeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String text = textView.getText().toString();
if (text.contains("World"))
{
textView.setText("Hello Android!");
}
else
{
textView.setText(("Hello World!"));
}
}
});
return rootView;
}
}
}
The NullPointerException occurs because, it seems that you have the same layout for your Activity and your Fragment:
// Activity
setContentView(R.layout.fragment_main);
// Fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
You need to check if your views (TextView & Button) are in the right layout and not into aonther (I guess activity_main).
Two solutions:
Copy/past your views inside fragment_main to activity_main and change setContentView(R.layout.activity_main).
Or let your views inside fragment_main and use the following code to find your view inside your Fragment, as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button changeTxt = (Button) rootView.findViewById(R.id.btnChangeText);
final TextView textView = (TextView) rootView.findViewById(R.id.txtMessage);
changeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = textView.getText().toString();
if (text.contains("World")) {
textView.setText("Hello Android!");
}
else {
textView.setText(("Hello World!"));
}
}
});
return rootView;
}
Hope this helps.
UPDATE:
1 . Remove your FrameLayout inside fragment_main. Create a new layout named activity_main and add the FrameLayout into it (with an id) as:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container" />
2 . Set this layout in onCreate method into your Activity like:
// onCreate method Activity
setContentView(R.layout.activity_main);
3 . Then, remove static in your Fragment declaration, this should be:
public class PlaceholderFragment ... { }
4 . Finally, when you try to find ids elements inside onCreateView method, you ALWAYS MUST to use the inflated view as:
rootView.findViewById(R.id.some_id_example);
Voila! This should work now.

Categories

Resources