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;
}
Related
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.
I've got problem to load pic from URL do my fragment by Picasso.
When I start app it's start without any errors but pic is not loading.
My app has one MainActivity and three fragments. Below I paste xml of mainlayout and one fragment class. The best for me is this scenario:
when user click button on fragment three(red on image), pic will load from url to imageView which is located on fragment two (yellow on image) above of fragment three.
Please help
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasadown extends Fragment {
private klasadownlistener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentdown, container, false);
ImageView img = (ImageView) view.findViewById(R.id.imgVV);
Context c = getActivity().getApplicationContext();
Picasso.with(c).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
.fit().into(img);
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnMenu:
updateText("Menu");
SetImage();
break;
case R.id.btnKontakt:
updateText("Kontakt");
break;
default:
break;
}
}
};
Button btnMenu = (Button) view.findViewById(R.id.btnMenu);
Button btnKontakt = (Button) view.findViewById(R.id.btnKontakt);
btnKontakt.setOnClickListener(clickListener);
btnMenu.setOnClickListener(clickListener);
return view;
}
public interface klasadownlistener {
public void onItemSelected(String txt);
}
private void updateText(String txt) {
listener.onItemSelected(txt);
}
public void SetImage() {
ImageView img = (ImageView) getView().findViewById(R.id.imgVV);
Picasso.with(getActivity().getApplicationContext()).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").into(img);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof klasadownlistener) {
listener = (klasadownlistener) activity;
} else {
throw new ClassCastException(activity.toString() + " musi implementowa� interfejs: OverviewFragment.OverviewFragmentActivityListener");
}
}
}
<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">
<fragment
android:id="#+id/fragmentup"
class="testowy.com.testowyfragment2.Klasaup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5">
</fragment>
<fragment
android:id="#+id/fragmentcenter"
class="testowy.com.testowyfragment2.Klasacenter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
<fragment
android:id="#+id/fragmetdown"
class="testowy.com.testowyfragment2.Klasadown"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
</LinearLayout>
package testowy.com.testowyfragment2;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasacenter extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragmentcenter, container, false);
return view;
}
public void SetText(String txt){
TextView view = (TextView) getView().findViewById(R.id.fragmentcenterText);
view.setText(txt);
}
}
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends Activity implements Klasadown.klasadownlistener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemSelected(String txt) {
Klasacenter fragment = (Klasacenter) getFragmentManager()
.findFragmentById(R.id.fragmentcenter);
// sprawdzamy czy fragment istnieje w tej aktywno�ci
if (fragment != null && fragment.isInLayout()) {
// ustawiamy teskt we fragmencie
fragment.SetText(txt);
ImageView img = (ImageView) findViewById(R.id.imgV);
Picasso.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").fit().into(img);
}
}
}
It's stupid to say but I forget to add internet permission:)
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
now everything is ok!
Something very weird is happening in my program. I try to use the button with the first program below (using an emulator) and the program did not even open. So I changed to the second version, using the android:OnClick, and it did not work either (the program opened, but in the click it crashed). Then I tried the third program, using android:onCLick and the instanciation of the EditText in the treatment function, and the program worked.
Can someone explain to me why the first two programs did not worked?
Edit: I noticed now that LogCat is pointing to the following error: error opening trace file: No such file oor directory (2), what is that? Can it have any relation to this error?
And if I comment the definition of the onClickListener to b1 the program do not crash anymore.
First code:
package app.projetnf33;
import android.app.Activity;
import android.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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
status.setText("Connect");
}
});
if (savedInstanceState == null) {
getFragmentManager().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;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Second code
package app.projetnf33;
import android.app.Activity;
import android.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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void treatment_connect(View v){
status.setText("Connect");
}
public void treatment_persons(View v){
status.setText("Persons");
}
public void treatment_lecture(View v){
status.setText("Lecture");
}
public void treatment_execute(View v){
status.setText("Execute");
}
#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;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Third code (which worked):
package app.projetnf33;
import android.app.Activity;
import android.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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void treatment_connect(View v){
status = (EditText) findViewById(R.id.text);
status.setText("Connect");
}
public void treatment_persons(View v){
status.setText("Persons");
}
public void treatment_lecture(View v){
status.setText("Lecture");
}
public void treatment_execute(View v){
status.setText("Execute");
}
#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;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Fragment_layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tex_status" />
<EditText
android:id="#+id/text"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par1" />
<EditText
android:id="#+id/par1"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par2" />
<EditText
android:id="#+id/par2"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par3" />
<EditText
android:id="#+id/par3"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_usb"
android:gravity="center_vertical"
android:text="#string/connect"
android:onClick="treatment_connect" />
<Button
android:id="#+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_computer"
android:gravity="center_vertical"
android:text="#string/read"
android:onClick="treatment_lecture" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_accept"
android:gravity="center_vertical"
android:text="#string/execution"
android:onClick="treatment_execution" />
<Button
android:id="#+id/b4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_warning"
android:gravity="center_vertical"
android:text="#string/disconnect"
android:onClick="treatment_disconnect" />
</LinearLayout>
</LinearLayout>
In the first and seconds layout you tried to call
status = (EditText) findViewById(R.id.text);
b1 = (Button) findViewById(R.id.b1);
before
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
So you tried to reference a Button and EditText contained in the PlaceholderFragment layout before you created the fragment.
The views are in the fragment layout. It only becomes a part of the activity view hierarchy after the fragment transaction has been run. Your pending fragment transaction is executed in activity super.onStart() which comes only after onCreate(). In essence, you're calling findViewById() too early in the first two versions. The third version works because the findViewById() is in the click handler and gets invoked when the fragment is attached to the activity.
Usually you'd call findViewById() to set up listeners and so on at the earliest possibility in fragment onCreateView(), just after the fragment layout is inflated.
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
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.