Unable to Display Toast in Fragment - java

Here I have added the Java And Xml File In which I just want to display a Toast when the user clicks on the button.
This is just to check whether the Fragment is working or not.
Here onClickListener is not working for me in the Fragment. Even setText on TextView was not working when I tried. I Think there is sometihing problem with the components or some problem between the connection of java and xml file
Setting.java
package com.example.dell.jsonexp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class setting extends Fragment {
BackgroundTask b;
String e;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.setting, container, false);
final Button logout= (Button) RootView.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Button Pressed",Toast.LENGTH_LONG).show();
}
});
return inflater.inflate(R.layout.setting, container, false);
}
}
setting.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">
<Button
android:id="#+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:text="Logout" />
</RelativeLayout>

You are setting a click listener to a button that is never shown.
You need to return the rootView instead of inflating another view.
return rootView;

In a Fragment you cant access view components in onCreateView() method, You have to Override onViewCreated() method.
Please update your code as below.
package com.example.dell.jsonexp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class setting extends Fragment {
BackgroundTask b;
String e;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.setting, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button logout= (Button) view.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Button Pressed",Toast.LENGTH_LONG).show();
}
});
}
}
Thanks!

You need to return
return RootView;
and for the Toast you have to write
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "Whatever you want here", Toast.LENGTH_SHORT).show();
}
});

Related

How to get next activity when clicked from frag button

Hi i am trying to get my NextActivity when i press on Fab in my View 1
View 1 xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/Fbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="180dp"
android:clickable="true"
android:paddingRight="16dp"
android:paddingBottom="16dp"
/>
</RelativeLayout>,
View.java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class View1 extends Fragment {
private FloatingActionButton mFab;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.view1, container, false);
mFab.findViewById(R.id.Fbutton);
mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),NextActivity.class);
startActivity(intent);
}
});
return view;
}
}
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.floatingactionbutton.FloatingActionButton.findViewById(int)' on a null object reference
at com.example.myapplication.View1.onCreateView(View1.java:21)
i have tried
getContext()
View1.this
nothing worked
You haven't complete the floating button assigning.
Remove mFab.findViewById(R.id.Fbutton); this line.
Add
mFab = view.findViewById(R.id.Fbutton);
Here view is used to get the ID from the layout.
From the code that you posted most probably the problem is that you are not assigning the return value of findViewById(R.id.Fbutton); to the mFab.
mFab = findViewById(R.id.Fbutton);

Fragment in Android unnecessarily repeating more than once

Iam trying to keep a simple fragment with only one button.But it is coming 2 times like this
I had a linear layout and another nested linear layout in it.These are all present in activity_welcome.xml whose content is as follows :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99cc00"
android:orientation="vertical"
tools:context="com.acs.AfterLogin.WelcomeActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/replacable_container"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Iam trying to replace the replacable_container(Linear Layout) with the fragment whose java class is this :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.acs.AfterLogin.WelcomeActivity;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeFragment1 extends Fragment{
View v;
CardView cardView1,cardView2,cardView3;
CircleImageView userIcon;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return inflater.inflate(R.layout.welcome_fragment_1,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The xml content of fragment is this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e0ebe5"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"/>
</LinearLayout>
The operations like fragment transcation and all are contained in the mainactivity whose java code is this :
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.acs.AfterLogin.WelcomeFragments.WelcomeFragment1;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeActivity extends AppCompatActivity {
FragmentTransaction transaction;
WelcomeFragment1 frag1;
FragmentManager manager;
String imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
(new FragTask()).execute();
}
private class FragTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
transaction = manager.beginTransaction();
frag1 = new WelcomeFragment1();
transaction.replace(R.id.replacable_container, frag1, "welcome_1");
transaction.commit();
return null;
}
}
}
Thanks a lot in advance :)
Try to change this line
v=inflater.inflate(R.layout.welcome_fragment_1,container);
to
v=inflater.inflate(R.layout.welcome_fragment_1,container, false);
And return the inflated view. The boolean value indicates that you don't want to attach your view to container. Check this. Fragment will attach it later by itself.
Please return inflated view instead of inflating again in return statement.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return v;
}

Android Fragment not showing in app

So I'm creating an app and I'm stuck with this problem of my fragment not showing on screen. It looks just fine on Android Studio preview, but when run on real device I only see action bar and nothing else.
Here's my fragment code:
<?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:gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/fragment_login_userEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"/>
<EditText
android:id="#+id/fragment_login_userPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment_login_loginButton"
android:text="Sign In"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment_login_registerButton"
android:text="Sign Up"/>
</LinearLayout>
LoginFragment code:
package com.dario.beastchat.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.dario.beastchat.R;
import com.dario.beastchat.R2;
import com.dario.beastchat.activities.BaseFragmentActivity;
import com.dario.beastchat.activities.RegisterActivity;
import com.dario.beastchat.utils.Constants;
import java.net.URISyntaxException;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.socket.client.IO;
import io.socket.client.Socket;
public class LoginFragment extends BaseFragment {
#BindView(R2.id.fragment_login_userEmail)
EditText mUserEmailEt;
#BindView(R2.id.fragment_login_userPassword)
EditText mUserPasswordEt;
#BindView(R2.id.fragment_login_loginButton)
Button mLoginButton;
#BindView(R2.id.fragment_login_registerButton)
Button mRegisterButton;
private Unbinder mUnbinder;
private Socket mSocket;
public static LoginFragment newInstance(){
return new LoginFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mSocket = IO.socket(Constants.IP_LOCAL_HOST);
} catch (URISyntaxException e) {
Log.i(LoginFragment.class.getSimpleName(), e.getMessage());
Toast.makeText(getActivity(), "Cant connect to the server", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
mSocket.connect();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
mUnbinder = ButterKnife.bind(this, rootView);
return rootView;
}
#OnClick(R2.id.fragment_login_registerButton)
public void setmRegisterButton(){
startActivity(new Intent(getActivity(), RegisterActivity.class));
}
#Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
#Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
}
}
BaseFragment class:
package com.dario.beastchat.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public class BaseFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
And BaseFragment activity:
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.dario.beastchat.R;
public abstract class BaseFragmentActivity extends AppCompatActivity {
abstract Fragment createFragment();
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_fragment_base);
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.activity_fragment_base_fragmentContainer);
if (fragment ==null) {
fragment = createFragment();
fragmentManager.beginTransaction()
.add(R.id.activity_fragment_base_fragmentContainer, fragment)
.commit();
}
}
}
What am I doing wrong?
if (fragment ==null) {
fragment = createFragment();
fragmentManager.beginTransaction()
.add(R.id.activity_fragment_base_fragmentContainer, fragment)
.commit();
}
Problems is .add
try to replace it to replace

Error while using ListFragement

I am developing an android app for online payment for which I want to display Lists of restaurants under the tab named Restaurants. Same as this some other tabs will have list below them and a few tabs will have form under them (if possible and not difficult otherwise I will stay with the lists only)
Here is the code I have written. It contains an error in the Adapter class and may be some logical errors which I am not sure about as this is my first ever android app.
Main.java File
package com.example.tabswithswipe;
import com.example.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Retaurants", "Super Store", "Fuel Stations"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
acivity_main.xml File
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
items_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
TabPagerAdapter.java Adapter File (Error in this file)
package com.example.tabsswipe.adapter;
import com.example.tabsswipe.*;
import android.app.ListFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SuperStoreFragment();
case 1:
return new FuelStationsFragment();
case 2:
return new RestaurantsFragment(); //Error Here
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
RestaurantsFragment.java
package com.example.tabsswipe.adapter;
//import com.example.MainActivity.MyAdapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RestaurantsFragment extends ListFragment {
LayoutInflater inflater;
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.list_items, container, false);
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.textView1, getResources().getStringArray(R.array.items)));
return rootView;
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, container, false);
String [] items = getResources().getStringArray(R.array.items);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("kfc"))
{
iv.setImageResource(R.drawable.kfc);
}
else if(items[position].equals("pizzaHut"))
{
iv.setImageResource(R.drawable.pizzahut);
}
else if(items[position].equals("Domino"))
{
iv.setImageResource(R.drawable.dominos);
}
else if(items[position].equals("hardees") )
{
iv.setImageResource(R.drawable.hardees);
}
else if(items[position].equals("TuttiFrutti"))
{
iv.setImageResource(R.drawable.tuttifrutti);
}
else if(items[position].equals("McDonalds"))
{
iv.setImageResource(R.drawable.mcdonalds);
}
else if(items[position].equals("21 Street"))
{
iv.setImageResource(R.drawable.ic_launcher);
}
return row;
}
}
// View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
// return rootView;
// }
}
SuperStoreFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SuperStoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_super_stores, container, false);
return rootView;
}
}
fragment_super_stores.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"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Super Stores Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
FuelStationsFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FuelStationsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fuel_stations, container, false);
return rootView;
}
}
fragment_fuel_stations.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"
android:orientation="vertical"
android:background="#ff8400" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Fuel Stations Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Please tell me how, where and what error occurred. Any kind of help will be really appreciated e.g. Tutorial, code example or even the error resolution of this code. Please ignore my silliness if any. Thank You.

Application stopped working when loading layout with setContentView

Here's the XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/search_lyt"
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"
android:name="search_act"
tools:context="com.example.app.Hisp$PlaceholderFragment">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/hispania_lgs"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/back2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Info"
android:id="#+id/info2"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/model_list"
android:layout_below="#+id/textViewML"
android:layout_alignParentRight="true"
android:layout_above="#+id/back2"
android:choiceMode="singleChoice" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select any of the models below and press Info for the model's specifications"
android:id="#+id/textViewML"
android:layout_below="#+id/imageView2"
android:layout_alignLeft="#+id/model_list" />
And using the setContentView method results in an 'Application stopped working'.
setContentView(R.layout.search_hisp);
Any idea on how to fix this? I'm quite new to Android Development and still trying to find how to switch layouts the correct way.
Well, even I change the onCreate()' setContentView to R.layout.search_hisp and gave me the error on startup. So my guess is it's probably from the XML file or something.
Thanks in advance!
Edit, there's the error:
>
03-25 12:10:23.415 20858-20858/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
at com.example.app.Hisp.beginSearch(Hisp.java:121)
at com.example.app.Hisp$3.onClick(Hisp.java:107)
at android.view.View.performClick(View.java:4231)
at android.view.View$PerformClick.run(View.java:17537)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Process: com.example.app
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Package: com.example.app v1 (1.0)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ Application Label: Hisp_Selector
And here's the code:
package com.example.app;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.preference.DialogPreference;
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.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.ViewGroup;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Window;
import android.view.WindowManager;
import android.os.Build;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.widget.LinearLayout;
public class Hisp extends ActionBarActivity {
public static ActionBarActivity activity;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
activity = this;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_hisp);
TextView txt = (TextView) findViewById(R.id.textViewML);
Button btn = (Button) g(R.id.search);
Button rst = (Button) g(R.id.reset);
rst.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
finish();
startActivity(getIntent());
}
});
OnClickListener _rdb = new OnClickListener() {
#Override
public void onClick(View view) {
((CheckBox) g(R.id.R134a)).setChecked(false);
((CheckBox) g(R.id.R22)).setChecked(false);
((CheckBox) g(R.id.R404A)).setChecked(false);
((CheckBox) g(R.id.R507A)).setChecked(false);
((CheckBox) view).setChecked(true);
}
};
((CheckBox) g(R.id.R134a)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R22)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R404A)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R507A)).setOnClickListener(_rdb);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
beginSearch();
}
});
/*
if (stanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
*/
}
public void beginSearch() {
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Boolean err = false;
try {
if (!(Double.parseDouble((((EditText) g(R.id.capacity)).getText().toString().trim())) >= 0 &&
isBetween(-35, 5, Integer.parseInt(((EditText) g(R.id.evaptemp)).getText().toString().trim())) &&
isBetween(28, 58, Integer.parseInt(((EditText) g(R.id.condtemp)).getText().toString().trim())) &&
isBetween(5, 13, Integer.parseInt(((EditText) g(R.id.dt1)).getText().toString().trim()))
)) err = true;
} catch(Exception e) {
err = true;
}
if (err) {
showMessageBox("ERROR", "Make sure you have filled all the fields correctly.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else {
setContentView(R.layout.search_hisp);
}
}
public View g(int id) {
return activity.findViewById(id);
}
public Boolean isBetween(Integer i1, Integer i2, Integer ix) {
if (ix >= i1 && ix <= i2) return true;
return false;
}
public void showMessageBox(Object ttl, Object msg, DialogInterface.OnClickListener rt) {
new AlertDialog.Builder(activity)
.setMessage(msg.toString())
.setTitle(ttl.toString())
.setCancelable(false)
.setNeutralButton(android.R.string.ok, rt)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hisp, 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_hisp, container, false);
return rootView;
}
}
}
Because in onCreate() you have used
EditText textViewML = (EditText) findViewById(R.id.textViewML);
instead of
TextView txt = (TextView) findViewById(R.id.textViewML);
so you got problem. So you need to use after your setContentView() method.
TextView txt = (TextView) findViewById(R.id.textViewML);
Put in the onCreate :
TextView textViewML = (TextView) findViewById(R.id.textViewML);
The error was from
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Thanks a lot guys for pointing this out!
you are casting Textview to EditText dont do that
EditText textViewML = (EditText) findViewById(R.id.textViewML);
change it as
TextView textViewML = (TextView) findViewById(R.id.textViewML);
Exception is not your layout file it is in your java file you are casting TextView into EditText.
You can not Cast Super class in to sub class.
you can cast Sub class into Super Class.
You can Cast EditText into TextView but not TextView in to EditText.
Change this line
TextView txt = (TextView) findViewById(R.id.textViewML);
Thanx

Categories

Resources