Android: Error inflating class fragment, using edittext and seekbar - android

I'm trying to write a project with an activity where there is a fragment with an edit text, a seekbar and a button and below a fragment with a textview. If you write on the editText and you move the seekbar you change the content and the size of the text in the textView of the fragment below. I used the following already done commented project and then I rename some elements and I corrected some parts:here
However I get an error "
Error inflating class fragment
": the following is part of the error message:
03-21 08:33:11.174 2830-2830/com.example.utente.fragmentconmutamenti
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.utente.fragmentconmutamenti, PID: 2830
java.lang.RuntimeException: Unable to start activity ComponentInfo {com.example.utente.fragmentconmutamenti/com.example.utente.fragmentconmutamenti.MainActivity}:
android.view.InflateException: Binary XML file line #13: Binary
XML file line #13: Error inflating class fragment
I read similar questions like this and their answers but I still didn't find what is the error in my code.
MainActivity.java
package com.example.utente.fragmentconmutamenti;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(int fontsize, String text) {
TextFragment textFragment =
(TextFragment)
getFragmentManager().findFragmentById(R.id.text_fragment);
textFragment.changeTextProperties(fontsize, text);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.utente.fragmentconmutamenti.MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.utente.fragmentconmutamenti.ToolbarFragment"
android:id="#+id/toolbar_fragment"
tools:layout="#layout/toolbar_fragment"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.utente.fragmentconmutamenti.TextFragment"
android:id="#+id/text_fragment"
android:layout_marginTop="130dp"
android:layout_below="#+id/toolbar_fragment"
android:layout_centerHorizontal="true"
tools:layout="#layout/text_fragment" />
</RelativeLayout>
ToolbarFragment.java
package com.example.utente.fragmentconmutamenti;
import android.app.Activity;
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.Button;
import android.widget.EditText;
import android.widget.SeekBar;
public class ToolbarFragment
implements SeekBar.OnSeekBarChangeListener
{
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view_toolbar_fragment =inflater.inflate(R.layout.toolbar_fragment, container, false);
edittext = (EditText) view_toolbar_fragment.findViewById(R.id.editText1);
final SeekBar seekbar =
(SeekBar) view_toolbar_fragment.findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
final Button button =
(Button) view_toolbar_fragment.findViewById(R.id.button_text);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view_toolbar_fragment;
}
public void buttonClicked (View view) {
activityCallback.onButtonClick(seekvalue,
edittext.getText().toString());
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekvalue = progress;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
}
toolbar_fragment.xml
package com.example.utente.fragmentconmutamenti;
import android.app.Activity;
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.Button;
import android.widget.EditText;
import android.widget.SeekBar;
public class ToolbarFragment
implements SeekBar.OnSeekBarChangeListener
{
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view_toolbar_fragment =inflater.inflate(R.layout.toolbar_fragment, container, false);
edittext = (EditText) view_toolbar_fragment.findViewById(R.id.editText1);
final SeekBar seekbar =
(SeekBar) view_toolbar_fragment.findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
final Button button =
(Button) view_toolbar_fragment.findViewById(R.id.button_text);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view_toolbar_fragment;
}
public void buttonClicked (View view) {
activityCallback.onButtonClick(seekvalue,
edittext.getText().toString());
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekvalue = progress;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
}
TextFragment.java
package com.example.utente.fragmentconmutamenti;
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;
public class TextFragment
extends Fragment {
private static TextView textview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view_text_fragment =inflater.inflate(R.layout.text_fragment, container, false);
textview = (TextView) view_text_fragment.findViewById(R.id.TextView1);
return view_text_fragment;
}
public void changeTextProperties(int fontsize, String text)
{
textview.setTextSize(fontsize);
textview.setText(text);
}
}
text_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Fragment Two"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Update: i replaced android.app.Fragment with android.support.v4.app.Fragment; and getFragmentManager() with
getSupportFragmentManager()
but it get a very similar error:
Process: com.example.utente.fragmentconmutamenti, PID: 3170
java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.example.utente.fragmentconmutamenti/com.example.utente.fragmentconmutamenti.MainActivity}:
android.view.InflateException: Binary XML file line #13: Binary XML
file line #13: Error inflating class fragment
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)

Check your imports in both of the Fragments
You should go with
import android.support.v4.app.Fragment;
instead of
import android.app.Fragment;
and on click
TextFragment textFragment =
(TextFragment)
getSupportFragmentManager().findFragmentById(R.id.text_fragment);

Related

I get No view found for id ....for fragment YouTubePlayerSupportFragment which closes my application

I am creating an application that should display within a fragment a youtube video by using YouTube API. I need to use a YouTubePlayerSupportFragment because i cannot extend my class to YouTubeBaseActivity (as I am already extending to AppCompatActivity).
See error here
AndroidRuntime: java.lang.IllegalArgumentException: No view found for id 0x7f0f00a5 (com.[].[]:id/youtube_player) for fragment YouTubePlayerSupportFragment{d4c0c78 #4 id=0x7f0f00a5}
where i need to show the fragment
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
import com.google.android.youtube.player.YouTubePlayerView;
public class CharityPopup extends DialogFragment {
private YouTubePlayerView youTubeView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().setDimAmount(0.0f);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().setCanceledOnTouchOutside(true);
View v = inflater.inflate(R.layout.charity_popup, container, false);
Fragment fragment = YouTubePlayerSupportFragment.newInstance();
getFragmentManager().beginTransaction().replace(R.id.youtube_player,fragment).commit();
return v;
}
#Override
public void onResume() {
super.onResume();
Window window = getDialog().getWindow();
window.setLayout(1000, 1000);
window.setGravity(Gravity.CENTER);
}
}
The corresponding 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:orientation="vertical"
android:id="#+id/charity_popup">
<fragment android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
My Youtube class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
import com.google.android.youtube.player.YouTubePlayerView;
public class YouTubeVideoFragment extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
public static YouTubeVideoFragment newInstance() {
YouTubeVideoFragment fragment = new YouTubeVideoFragment();
return fragment;
}
private void init(){
initialize("AIzaSyCq543mRV_C5bxdcMxxkXN8U-_bacu8I-Y", this);
}
public YouTubeVideoFragment () {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(getActivity(), RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), youTubeInitializationResult.toString());
Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubeView;
}
}
and my youtube xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".YouTubeVideoFragment">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
In the end what fixed my problem was: 1 a better understanding of nested fragments (youtube.com/watch?v=V4kcdvzF5cY), also extremely important AND 2. the answer how to work with YouTubePlayerSupportFragment. This is the link that saved me: Struggling with Youtube Player Support Fragment . Look for the answer from CzarMatt AND the correction from Silmarilos. For my xml code for the fragment to be replaced with the youtube fragment:used a FrameLayout & android:name="com.google.android.youtube.player.YouTubePlaye‌​rSupportFragment". Note I put there ...SupportFragment, and this is bacause I use YouTubePlayerSupportFragment. IF you use YouTubePlayerFragment then you have to put: android:name="com.google.android.youtube.player.YouTubePlaye‌​rFragment" in your FrameLayout.

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;
}

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

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.

Android Picasso Fragment Pic from URL

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!

Fragment in layout

I'am trying to communicate betwen two fragment extended classes with the help of MainActivity bt always get an error{03-01 14:30:42.675: E/AndroidRuntime(1724): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfrag/com.example.myfrag.Tool}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment}
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ToolBoxFrag extends FragmentActivity implements OnSeekBarChangeListener {
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
public void onAttach(Fragment activity) {
super.onAttachFragment(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekvalue = progress;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_main);
edittext = (EditText)findViewById(R.id.editText1);
final SeekBar seekbar =
(SeekBar) findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
final Button button =
(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return ;
}
public void buttonClicked (View view) {
activityCallback.onButtonClick(seekvalue,
edittext.getText().toString());
}
}
TextFragment.java
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends FragmentActivity {
private static TextView textview;
#Override
public void onCreate( Bundle savedInstanceState) {
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textView1);
return;
}
public void changeTextProperties(int fontsize, String text)
{
textview.setTextSize(fontsize);
textview.setText(text);
}
}
MainActivity
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class Tool extends FragmentActivity implements ToolBoxFrag.ToolbarListener {
//public TextFragment tf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag2);
}
public void onButtonClick(int fontsize, String text) {
TextFragment tf = new TextFragment();
getSupportFragmentManager().findFragmentById(R.id.main);
tf.changeTextProperties(fontsize, text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main,
menu);
return true;
}
}
xml layout
<?xml version="1.0" encoding="utf-8"?>
<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=".FragmentExampleActivity" >
<fragment
android:id="#+id/activity_main"
android:name="com.example.fragmentexample.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/activity_main" />
<fragment
android:id="#+id/main"
android:name="com.example.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/main" />
</RelativeLayout>
Problem is the class path you have described the fragment name path wrong ..
it should be com.example.myfrag not com.example.fragmentexample
<?xml version="1.0" encoding="utf-8"?>
<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=".FragmentExampleActivity" >
<fragment
android:id="#+id/activity_main"
android:name="com.example.myfrag.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/activity_main" />
<fragment
android:id="#+id/main"
android:name="com.example.myfrag.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/main" />
</RelativeLayout>

Categories

Resources