App crashes on clicking on textView in fragment - android-fragments

I'm creating an app in which there are three tab activity.In tab Three i have a textview name as login text whenever user click on this text a new activity should be opened but app crashes when we click on this.
I have done many research to resolve this problem but i'm unable to resolve at last i'm here for the solution of my problem Please help.
Thanks in advance.
This is my loginActivity.
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class loginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText email_Id;
private EditText password;
private TextView sign_Up;
private Button sign_In;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth=FirebaseAuth.getInstance();
// if(firebaseAuth.getCurrentUser()!=null){
// directly start user profile activity
// finish();
// startActivity(new Intent(this,userProfileActivity.class));
//}
progressDialog=new ProgressDialog(this);
email_Id=(EditText)findViewById(R.id.email_id);
password=(EditText)findViewById(R.id.password);
sign_In=(Button)findViewById(R.id.sign_In);
sign_Up=(TextView)findViewById(R.id.sign_up);
sign_In.setOnClickListener(this);
sign_Up.setOnClickListener(this);
}
private void user_Login(){
String email=email_Id.getText().toString().trim();
String pass_word=password.getText().toString().trim();
if(TextUtils.isEmpty(email)){
// email is empty
Toast.makeText(this,"please enter email",Toast.LENGTH_SHORT).show();
return;// to stop the function from executation.
}
if(TextUtils.isEmpty(pass_word)){
// email is empty
Toast.makeText(this,"please enter password",Toast.LENGTH_SHORT).show();
return;
}
// here if everything ok the user will be register
progressDialog.setMessage("Registering User,please wait...");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,pass_word)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()){
// start user profile activity
finish();
startActivity(new Intent(getApplicationContext(),userProfileActivity.class));
}
}
});
}
#Override
public void onClick(View view) {
if (view==sign_In){
// start user profile activity
user_Login();
}
if(view==sign_Up){
// go to registeration page
finish();
startActivity(new Intent(this,FragmentThree.class));
}
}
}
this is declaration
This is my login method

The following line in your code throws the exception:
sign_Up.setOnClickListener(this);
The problem is, that sign_Up is null!
You set sign_Up with: sign_Up=(TextView)findViewById(R.id.sign_up);
Make sure, that setContentView(R.layout.activity_login); (activity_login) is the right one. If, try to clean and rebuild your project and try again.
Update: It is possible, that sign_up should be a button? If, you make a wrong cast!
Change the TextView in this line:
sign_Up=(TextView)findViewById(R.id.sign_up);
to Button, like this:
sign_Up=(Button)findViewById(R.id.sign_up);

Related

Unable to fetch data from Firebase in Android Studio but able to save it

I am making my first app using Firebase. I am unable to fetch data from Firebase in Android Studio but I was able to upload it using login and sign up features which I created in my app.
Whenever I run the app, it does not show any error but app automatically closes after the splash screen. I am unable to resolve this error.
MainActivity.java
package com.example.blooddonationapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private NavigationView nav_view;
private CircleImageView nav_profile_image;
private TextView nav_fullname, nav_email, nav_bloodgroup, nav_type;
private DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Blood Donation App");
drawerLayout = findViewById(R.id.drawerLayout);
nav_view = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
nav_view.setNavigationItemSelectedListener(this);
nav_profile_image = nav_view.getHeaderView(0).findViewById(R.id.nav_user_image);
nav_fullname = nav_view.getHeaderView(0).findViewById(R.id.nav_user_fullname);
nav_email = nav_view.getHeaderView(0).findViewById(R.id.nav_user_email);
nav_bloodgroup = nav_view.getHeaderView(0).findViewById(R.id.nav_user_bloodgroup);
nav_type = nav_view.getHeaderView(0).findViewById(R.id.nav_user_type);
userRef = FirebaseDatabase.getInstance().getReference().child("users").child(
FirebaseAuth.getInstance().getCurrentUser().getUid()
);
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String name = snapshot.child("name").getValue().toString();
nav_fullname.setText(name);
String email = snapshot.child("email").getValue().toString();
nav_email.setText(email);
String bloodgroup = snapshot.child("bloodgroup").getValue().toString();
nav_bloodgroup.setText(bloodgroup);
String type = snapshot.child("type").getValue().toString();
nav_type.setText(type);
String imageUrl = snapshot.child("profilepictureurl").getValue().toString();
Glide.with(getApplicationContext()).load(imageUrl).into(nav_profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.profile:
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
ProfileActivity.java
package com.example.blooddonationapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileActivity extends AppCompatActivity {
private Toolbar toolbar;
private TextView type, name, email, idNumber, phoneNumber, bloodGroup;
private CircleImageView profileImage;
private Button backButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("My Profile");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
type = findViewById(R.id.type);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
idNumber = findViewById(R.id.idNumber);
phoneNumber = findViewById(R.id.phoneNumber);
bloodGroup = findViewById(R.id.bloodGroup);
profileImage = findViewById(R.id.profileImage);
backButton = findViewById(R.id.backButton);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
type.setText(snapshot.child("type").getValue().toString());
name.setText(snapshot.child("name").getValue().toString());
idNumber.setText(snapshot.child("idnumber").getValue().toString());
phoneNumber.setText(snapshot.child("phonenumber").getValue().toString());
bloodGroup.setText(snapshot.child("bloodgroup").getValue().toString());
email.setText(snapshot.child("email").getValue().toString());
Glide.with(getApplicationContext()).load(snapshot.child("profilepictureurl").getValue().toString()).into(profileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Firebase
LogCat

error: incompatible types: SearchFragment cannot be converted to Fragment

this code was working perfectly when i was using navigation drawer activity after making some changes to my project and start using bottom navigation activity it just wont work and give my the error of incompatible types .. i tried every possible answer related to this issue but i get the same error
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity {
private TextView mTextMessage;
SearchFragment searchFragment;
private FrameLayout Eframe;
private HomeFragment homeFragment;
private BottomNavigationView eNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Eframe = findViewById(R.id.main_frame);
searchFragment = new SearchFragment();
setFragment(searchFragment);
eNav = findViewById(R.id.Nav);
eNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Search:
> setFragment(searchFragment);
return true;
case R.id.Home:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.Profile:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Menu:
mTextMessage.setText(R.string.title_notifications);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
}
}
instead of extends AppCompatActivity
write extends Fragment.

Android upload to Firebase Bucket with SchedulerAPI

Background:
I am using Firebase for my Android App Development This app require every user upload an object from their phone to the bucket/ Firebase Storage once a day. So, I want to make the process of "object upload" as a background service with JobSchedulerAPI.
I have copied source code from Firebase and a youtube video related to Job Scheduler. But when I clicked the button, the app stopped immediately.
MainActivity.Java
package com.scheduleupload;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final ComponentName mComponentName = new ComponentName(this, Scheduler.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JobInfo info = new JobInfo.Builder(123, mComponentName)
.setPeriodic(15 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
});
}
}
Scheduler.Java
package com.scheduleupload;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.net.Uri;
import android.util.Log;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class Scheduler extends JobService {
private static final String TAG = "ExampleJobService";
private boolean jobCancelled =false;
private StorageReference mStorage;
mStorage = FirebaseStorage.getInstance().getReference();
String myUri = "content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3D693";
final Uri uri = Uri.parse(myUri);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job Started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(JobParameters params) {
new Thread(new Runnable() {
#Override
public void run() {
filepath.putFile(uri);
}
}).start();
}
#Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
Thx a lot for spending such a long while to read my question
crash log:
05-07 21:53:52.775 6261-6261/com.scheduleupload E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.scheduleupload, PID: 6261
java.lang.IllegalArgumentException: No such service ComponentInfo{com.scheduleupload/com.scheduleupload.Scheduler}
at android.os.Parcel.readException(Parcel.java:2008)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:180)
at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
at com.scheduleupload.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Have found solution, it is because the Scheduler can't access to some of the storage. Simply change to file location to somewhere it is accessible by Job Scheduler can solve the problem

java.lang.RuntimeException: Unable to start activity ComponentInfo java.lang.IllegalStateException:Fragment not attached to Activity

I'm working with a fragment but its always throwing the error that it cannot start the activity because the fragmentis not attached to the activity,
kindly assist me figure out where I'm messing
Below is my code for the Fragment and Activity:
Fragment
package com.sarham.kabs.fruity;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import adapters.CategoriesListAdapter;
/**
* Created by Kabunyi Wanja on 22/03/2015.
*/
public class CategoriesFragment extends ListFragment {
private ListView categoriesListView;
private String[] categoriesArray = getResources().getStringArray(R.array.drawer_list);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.categories_fragment, container, false);
categoriesListView = (ListView)v.findViewById(android.R.id.list);
//setCategoriesListAdapter();
//Log.d("ADAPTER: ", "Adapter has been set for listview");
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setCategoriesListAdapter();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
//set adapter to categoriesListView
public void setCategoriesListAdapter(){
categoriesListView.setAdapter(new CategoriesListAdapter(getActivity(), categoriesArray));
}
}
Activity
package com.sarham.kabs.fruity;
import android.content.res.Configuration;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener{
private DrawerLayout drawerLayout;
private ListView listView;
private String[] planets;
private ActionBarDrawerToggle drawerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
listView = (ListView)findViewById(R.id.drawerListView);
planets = getResources().getStringArray(R.array.planets);
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, planets));
listView.setOnItemClickListener(this);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Toast.makeText(MainActivity.this,"Drawer Open", Toast.LENGTH_LONG).show();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Toast.makeText(MainActivity.this, "Drawer Closed", Toast.LENGTH_LONG).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CategoriesFragment categories = new CategoriesFragment();
addFragment(R.id.drawerLayout, categories, "CATEGORIES");
}
#Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
drawerListener.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
#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.
if(drawerListener.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, planets[position]+" Was selected", Toast.LENGTH_SHORT).show();
selectItem(position);
switch (position){
case 0:
CategoriesFragment categories = new CategoriesFragment();
addFragment(R.id.drawerLayout, categories, "CATEGORIES");
break;
case 1:
Toast.makeText(this, "Settings was selected", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "Exit was selected", Toast.LENGTH_SHORT).show();
finish();
break;
default:
}
}
public void selectItem(int position){
listView.setItemChecked(position, true);
setTitle(planets[position]);
}
//set ActionBar title
public void setTitle(String title){
getSupportActionBar().setTitle(title);
}
//call this method to add a fragment
public void addFragment(int containerViewId, Fragment fragment, String tag){
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(containerViewId, fragment, tag);
transaction.commit();
}
}
Below is the LogCat ouput:
Caused by: java.lang.IllegalStateException: Fragment CategoriesFragment{41545e80} not attached to Activity
at android.support.v4.app.Fragment.getResources(Fragment.java:619)
at com.sarham.kabs.fruity.CategoriesFragment.<init>(CategoriesFragment.java:21)
at com.sarham.kabs.fruity.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211)
            at android.app.ActivityThread.access$600(ActivityThread.java:149)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            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:821)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)
On carefull analysis of the Fragment lifecycle, Its not possible to carry out operations like fetching of string resources using the getResources().getStringArray(...) as I was doing, this has to be done within the method onActivityCreated(...)

Android Open WebView inside Fragment - crash

App need to open some websites when i touch buttons. There are 2 tabs (2 fragments) with different buttons (1 button = 1 link)
When i click a Button that need to open WebView (to open a link) application crash. I think, mistake is somewhere in AFragment.java
main.java (it's good 99,9%)
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
public static Context appContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab PTab = actionbar.newTab().setText("One");
ActionBar.Tab DTab = actionbar.newTab().setText("Two");
Fragment OneFragment = new AFragment();
Fragment TwpFragment = new BFragment();
PTab.setTabListener(new MyTabsListener(OneFragment));
DTab.setTabListener(new MyTabsListener(TwoFragment));
actionbar.addTab(PTab);
actionbar.addTab(DTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
//Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
AFragment.java:
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class AFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
SavedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.afragment, container, false);
}
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
}
openPage.class:
import android.webkit.WebView;
import android.app.Activity;
import android.os.Bundle;
public class openPage extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://safhkalfsd.com");
}
}
Layouts are fine 99,99%
i put
android:onClick="openIt"
in afragment.xml inside Button
THANK YOU
SOLVED!
I need to put:
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
in MainActivity, not in 'AFragment'.

Resources