Android App Stops Working Immediately - java

I have created an android app that features an add button, a subtract button, and a counter variable.
However, as soon as the app opens on my device (Samsung Galaxy S3), I receive an error message stating that the app has stopped working.
Below is my MainActivity.java file.
package com.example.first;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int counter;
Button add, sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.btnAdd);
sub = (Button) findViewById(R.id.btnSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter += 1;
display.setText("The total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter -= 1;
display.setText("The total is " + counter);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
The fragment_main.xml file is below:
<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: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.first.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDisplay"
android:layout_centerHorizontal="true"
android:layout_marginTop="54dp"
android:text="#string/add_button" />
<Button
android:id="#+id/btnSub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btnAdd"
android:layout_below="#+id/btnAdd"
android:layout_marginTop="40dp"
android:text="#string/sub_button" />
Are there any ideas as to why the app stops working immediately after it starts running?
Thank you.

I imagine that you're getting a NullPointerException around Line 31. The reason you're getting a NullPointerException is because you're trying to find Views in your ActionBarActivity that are being inflated into your PlaceholderFragment. Change your code as follows:
// import statements omitted
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit();
}
}
// onCreateOptionsMenu() and onOptionsItemSelected()
// method remain the same.
public static class PlaceholderFragment extends Fragment {
int counter = 0;
Button add, sub;
TextView display;
public PlaceholderFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
add = (Button) rootView.findViewById(R.id.btnAdd);
sub = (Button) rootView.findViewById(R.id.btnSub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter += 1;
display.setText("The total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter -= 1;
display.setText("The total is " + counter);
}
});
return rootView;
}
}
}

Remove counter = 0; and Just Do this:
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
tv1.setText("The total is : " + String.valueOf(counter));
}
});
sub.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
tv1.setText("The total is : " + String.valueOf(counter));
}
});
Hope this helps..

Related

Data reset when moving from one to another fragment using Bottom Navigation Bar

I am using bottom navigation bar dan fragment in my project.
When it moved from one to another fragment, I dont want to lose the state or data
How can I do it?
This is activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F9FAFD">
<FrameLayout
android:id="#+id/page_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_bar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:background="#android:color/white"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_menu" />
</RelativeLayout>
And this is the MainActivity.java
package com.noval.tugas_6;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.noval.tugas_6.computer.ComputerFragment;
import com.noval.tugas_6.home.HomeFragment;
import com.noval.tugas_6.home_services.HomeServicesFragment;
import com.noval.tugas_6.phone.PhoneFragment;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
private Fragment fragment;
private long exitTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_bar);
getFragmentPage(new HomeFragment());
setBottomNavigationView();
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
private boolean getFragmentPage(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.addToBackStack(null)
.replace(R.id.page_fragment, fragment)
.commit();
return true;
}
return false;
}
#Override
public void onBackPressed() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
}
This is one of the fragment that I am using
PhoneFragment.java
package com.noval.tugas_6.phone;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.noval.tugas_6.R;
public class PhoneFragment extends Fragment {
public int[] imgID = new int[]{R.drawable.infinix_zero, R.drawable.realme_c35,
R.drawable.galaxy_a33, R.drawable.samsung_galaxy_a13, R.drawable.samsung_galaxy_a23};
public String[] namaHP = new String[]{"Infinix Zero 5G", "Realme C35", "Samsung Galaxy A33 5G",
"Samsung Galaxy A13", "Samsung Galaxy A23"};
public String[] hargaHP = new String[]{"Rp3.600.000", "Rp2.150.000", "Rp4.700.000", "Rp2.500.000", "Rp3.500.000"};
ImageView imgHP;
TextView txtNama, txtHarga;
Button btnNext, btnPrevious;
int position = 0;
public PhoneFragment() {
// Required empty public constructor
}
// public static PhoneFragment newInstance() {
// PhoneFragment fragment = new PhoneFragment();
// Bundle args = new Bundle();
// fragment.setArguments(args);
// return fragment;
// }
//
// #Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (getArguments() != null) {
//
// }
// }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone, container, false);
}
// method ini dipanggil sesaat setelah onCreateView di atas dipanggil
// semua pembacaan view dan penambahan listener dilakukan disini
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
imgHP = (ImageView) getActivity().findViewById(R.id.imgHP);
txtNama = (TextView) getActivity().findViewById(R.id.txtNamaHP);
txtHarga = (TextView) getActivity().findViewById(R.id.txtHargaHP);
btnNext = (Button) getActivity().findViewById(R.id.btnNextHP);
btnPrevious = (Button) getActivity().findViewById(R.id.btnPreviousHP);
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
btnPrevious.setVisibility(View.GONE);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
position += 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
// jika posisi item yang terakhir, hilangkan tombol next
if (position == (imgID.length - 1)) {
btnNext.setVisibility(View.GONE);
} else if (position > 0) {
btnPrevious.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
position -= 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
if (position == 0) {
btnPrevious.setVisibility(View.GONE);
} else {
btnNext.setVisibility(View.VISIBLE);
}
}
});
}
}
Please show me how to not lose the fragment data when moving to another fragment
Thanks
because every time user click on navigation bottom u create new instance of fragment every time :
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
try this :
private homeFragment = new HomeFragment();
private computerFragment = new ComputerFragment();
private phoneFragment = new PhoneFragment();
private homeServicesFragment = new HomeServicesFragment();
private Fragment active;
private final FragmentManager fm = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
initFragment();
...
}
private void changeFragment(Fragment fragment, Bundle bundle) {
fm.beginTransaction()
.hide(active)
.show(fragment)
.commit();
active = fragment;
active.setArguments(bundle);
}
private void initFragment() {
fm.beginTransaction().add(R.id.frameLayout, homeFragment, homeFragment.class.getSimpleName()).commit();
fm.beginTransaction().add(R.id.frameLayout, computerFragment, computerFragment.class.getSimpleName()).hide(computerFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, phoneFragment, PhoneFragment.class.getSimpleName()).hide(phoneFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, homeServicesFragment, HomeServicesFragment.class.getSimpleName()).hide(homeServicesFragment).commit();
active = homeFragment;
changeFragment(homeFragment, null);
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
changeFragment(homeFragment, null);
return true;
case R.id.computer_menu:
changeFragment(computerFragment, null);
return true;
case R.id.phone_menu:
changeFragment(phoneFragment, null);
return true;
case R.id.home_services_menu:
changeFragment(homeServicesFragment, null);
return true;
}
return homeFragment;
}
});
}

Navigation Drawer can't navigate

i'm trying to make a navigation to one of my fragment but I can't seem to invoke that fragment here's my code
MainActivity.java
package ics115_4ite_lim.bookings;
import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
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 ics115_4ite_lim.bookings.Fragments.ScheduleFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
int id = item.getItemId();
if (id == R.id.schedule_fragment) {
fragment = new ScheduleFragment();
} else if (id == R.id.driver_fragment) {
} else if (id == R.id.transaction_fragment) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and this is the fragment I want to go to
ScheduleFragment.java
package ics115_4ite_lim.bookings.Fragments;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import com.daimajia.swipe.util.Attributes;
import java.util.ArrayList;
import ics115_4ite_lim.bookings.DividerItemDecoration;
import ics115_4ite_lim.bookings.R;
import ics115_4ite_lim.bookings.Student;
/**
* Created by Mark Terrance on 12/7/2017.
*/
public class ScheduleFragment extends Fragment {
private ArrayList<Student> mDataSet;
private Toolbar toolbar;
private TextView tvEmptyView;
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment_packages
final View view = inflater.inflate(R.layout.schedule_fragment, container, false);
initScheduleView(view);
return view;
}
private void initScheduleView(View view){
mRecyclerView = view.findViewById(R.id.recycleView);
// Layout Managers:
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// Item Decorator:
//mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
mDataSet = new ArrayList<Student>();
loadData();
if (mDataSet.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
// Creating Adapter object
SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter(getActivity(), mDataSet);
// Setting Mode to Single to reveal bottom View for one item in List
// Setting Mode to Mutliple to reveal bottom Views for multile items in List
((SwipeRecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
mRecyclerView.setAdapter(mAdapter);
/* Scroll Listeners */
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.e("RecyclerView", "onScrollStateChanged");
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
}
// load initial data
public void loadData() {
for (int i = 0; i <= 20; i++) {
mDataSet.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
private class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {
private Context mContext;
private ArrayList<Student> studentList;
public SwipeRecyclerViewAdapter(Context context, ArrayList<Student> objects) {
this.mContext = context;
this.studentList = objects;
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.swipe_row_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
final Student item = studentList.get(position);
viewHolder.tvName.setText((item.getName()) + " - Row Position " + position);
viewHolder.tvEmailId.setText(item.getEmailId());
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
// Drag From Left
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));
// Drag From Right
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));
// Handling different events when swiping
viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
//when the SurfaceView totally cover the BottomView.
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
//you are swiping.
}
#Override
public void onStartOpen(SwipeLayout layout) {
}
#Override
public void onOpen(SwipeLayout layout) {
//when the BottomView totally show.
}
#Override
public void onStartClose(SwipeLayout layout) {
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
/*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
//Start your activity
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
}
});*/
viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Edit " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
studentList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, studentList.size());
mItemManger.closeAllItems();
Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
// mItemManger is member in RecyclerSwipeAdapter Class
mItemManger.bindView(viewHolder.itemView, position);
}
#Override
public int getItemCount() {
return studentList.size();
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
// ViewHolder Class
public class SimpleViewHolder extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
TextView tvName;
TextView tvEmailId;
TextView tvDelete;
TextView tvEdit;
TextView tvShare;
ImageButton btnLocation;
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
tvShare = (TextView) itemView.findViewById(R.id.tvShare);
btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);
}
}
}
}
I have tried debugging it and I ended up on a null fragment
I don't know what's wrong because I just followed a tutorial
Help pls ? thanks :D
edit:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="ics115_4ite_lim.bookings.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
You need to actually do something with the Fragment you created.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
int id = item.getItemId();
if (id == R.id.schedule_fragment) {
fragment = new ScheduleFragment();
} else if (id == R.id.driver_fragment) {
} else if (id == R.id.transaction_fragment) {
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_id, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Make sure your fragment is not null, all your if branches should
initialize it to something
R.id.container_id should be an id of a ViewGroup in your layout that is empty and this is where the fragment will be placed.

How do I add a click listener to a CardView?

I'm new to android development and fairly new to coding in general, and I'm trying to make it so that when I click on one of my cards, it will display a toast. A different one for each card. I've looked everywhere and nothing works.
This is one of my cards. All of my cards are contained within a RelativeLayout
<FrameLayout
android:id="#+id/frame_orange"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/ripple"
android:foreground="?android:attr/selectableItemBackground">
<ImageView
android:id="#+id/imageView2"
android:layout_width="118dp"
android:layout_height="123dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/pi" />
</FrameLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal|bottom"
android:paddingBottom="10dp"
android:text="Definition"
android:textColor="#android:color/black"
android:textSize="25dp" />
</android.support.v7.widget.CardView>
This is my what I've added to my MainActivity.java
public static class PlaceHolderFragment extends Fragment implements View.OnClickListener{
View rootView;
public PlaceHolderFragment(){
}
public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_main, container, false);
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.card_definition:
Toast.makeText(getActivity().getApplication(), "Test",
Toast.LENGTH_LONG).show();
}
}
}
I'm not sure If I'm doing this completely wrong but I would appreciate help.
Edit: the entirety of my MainActivity.java
package com.piplex.kylefoster.piplex;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
public static class PlaceHolderFragment extends Fragment {
View rootView;
public PlaceHolderFragment() {
}
public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_main, container, false);
CardView cardView = (CardView) findViewById(R.id.card_definition);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplication(), "Test",
Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
}
You can easily do it with adding this code to public View OnCreateView :
CardView cardView = (CardView) findViewById(R.id.card_view);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//write your function here.
}
});

Programming a Counter for a Android Application

My goal is to programm an Counter-Application. There is a picture in the middle of the smartphone and under the picture is a countdown starting at 100.
Every time you click on the picture the picture should flash and the counter should decrease till you have clicked 100 times and reached 0.
I have a little bit of code, but every time I run the project on my VM the application crashes.
package com.syntaix.appleclicker;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int counter = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView) findViewById(R.id.TextView01);
final ImageView image = (ImageView) findViewById(R.id.appel);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
text.setText("" + counter);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Here is the LogCat Screenshot:
LogCat
You can find the views in fragment when its created . But your are trying to get the views before attaching the fragment to the activity. You need to move some code to fragment as below...
MainActivity.java
#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();
}
}
PlaceholderFragment.java
public static class PlaceholderFragment extends Fragment {
int counter = 100;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final TextView text = (TextView) rootView.findViewById(R.id.TextView01);
final ImageView image = (ImageView) rootView.findViewById(R.id.appel);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
text.setText("" + counter);
}
});
return rootView;
}
}

How to add a Button to my EmptyView?

Hi I'm trying to insert a Button into anEmptyView. The only thing I can seem to get to work is the EmptyText where a text value is displayed when the list is empty. This code works for just displaying a textview. How can I successfully add a button to the view?
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.text.format.DateFormat;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.robertrichardson.crimeproofassistant.R.string;
public class crimeListFragment extends ListFragment {
private ArrayList<crime> mcrime;
private boolean mSubtitleVisible;
public static final String TAG = "crimeListFragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.app_name);
mcrime = crimeLab.get(getActivity()).getcrime();
crimeAdapter adapter = new crimeAdapter(mcrime);
setListAdapter(adapter);
setRetainInstance(true);
mSubtitleVisible = false;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setEmptyText(getResources().getString(string.new_crime_attack_empty_desc));
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mSubtitleVisible) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
}
}
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Use floating point context menus on Froyer and Gingerbread
registerForContextMenu(listView);
} else {
// Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
// ActionMode.Callback methods
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.crime_list_item_context, menu);
return true;
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// required but not used in this implementation
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
crimeAdapter adapter = (crimeAdapter)getListAdapter();
crimeLab crimeLab = crimeLab.get(getActivity());
for (int i = adapter.getCount() - 1; i >= 0; i--) {
if (getListView().isItemChecked(i)) {
crimeLab.deletecrime(adapter.getItem(i));
}
}
mode.finish();
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
// Required, but not used in this implementation
}
public void onDestroyActionMode(ActionMode mode) {
}
});
}
return v;
}
public void onListItemClick(ListView l, View v, int position, long id) {
crime c = ((crimeAdapter)getListAdapter()).getItem(position);
// Start crime Activity
Intent i = new Intent(getActivity(), crimePagerActivity.class);
i.putExtra(crimeFragment.EXTRA_crime_ID, c.getId());
startActivity(i);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
((crimeAdapter)getListAdapter()).notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible && showSubtitle != null) {
showSubtitle.setTitle(R.string.hide_subtitle);
}
}
#TargetApi(11)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
crime crime = new crime();
crimeLab.get(getActivity()).addcrime(crime);
Intent i = new Intent(getActivity(), crimePagerActivity.class);
i.putExtra(crimeFragment.EXTRA_crime_ID, crime.getId());
startActivityForResult(i,0);
return true;
case R.id.menu_item_show_subtitle:
if (getActivity().getActionBar().getSubtitle() != null) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
mSubtitleVisible = true;
item.setTitle(R.string.hide_subtitle);
} else {
getActivity().getActionBar().setSubtitle(null);
mSubtitleVisible = false;
item.setTitle(R.string.show_subtitle);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.crime_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
crimeAdapter adapter = (crimeAdapter)getListAdapter();
crime crime = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
crimeLab.get(getActivity()).deletecrime(crime);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
private class crimeAdapter extends ArrayAdapter<crime> {
public crimeAdapter(ArrayList<crime> crime) {
super(getActivity(), 0, crime);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_crime, null);
}
// Enter the view of this crime Attack
crime c = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.crime_list_item_titleTextView);
titleTextView.setText(c.getTitle());
TextView dateTextView =
(TextView)convertView.findViewById(R.id.crime_list_item_dateTextView);
dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy hh : mm a", c.getDate()).toString());
CheckBox resolvedCheckBox =
(CheckBox)convertView.findViewById(R.id.crime_list_item_resolvedCheckBox);
resolvedCheckBox.setChecked(c.isResolved());
return convertView;
}
}
#Override
public void onResume() {
super.onResume();
((crimeAdapter)getListAdapter()).notifyDataSetChanged();
}
}
Here's my XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#f2f3f4"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#android:id/list"
android:background="#f2f3f4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
<linearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f3f4"
android:orientation="vertical"
>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="#string/new__empty_desc"
/>
<Button
android:id="#+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="#string/new_attack_empty"
/>
</linearLayout>
</FrameLayout>
public class MainActivity extends Activity {
private CustomBaseAdapter customBaseAdapter;
private ListView lv;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout fl = new FrameLayout(this);
btn = new Button(this);
btn.setText("Hit me");
lv = new ListView(this);
customBaseAdapter = new CustomBaseAdapter(this);
lv.setAdapter(customBaseAdapter);
fl.addView(lv);
fl.addView(btn);
setContentView(fl);
handleVisbility();
}
public void handleVisbility() {
if (customBaseAdapter.getCount() == 0) {
lv.setVisibility(View.GONE);
btn.setVisibility(View.VISIBLE);
} else {
lv.setVisibility(View.VISIBLE);
btn.setVisibility(View.GONE);
}
}
public class CustomBaseAdapter extends BaseAdapter {
private Context context;
View superView;
public CustomBaseAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int arg0) {
return new Object();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
FrameLayout fl = new FrameLayout(context);
Button btn = new Button(context);
btn.setText("Hello, im a Button");
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Yay hit me again", Toast.LENGTH_LONG).show();
}
});
fl.addView(btn);
return fl;
}
}
}
Ok, this is kinda what you want to do here. It shows a ListView, if there is an Item in the List, and will show the Button if the List is Empty. Only thing you have to do, is to call handleVisbility() everytime you make a change to the ListViews content. Especially after you add something to the List.
The default implementation of the ListFragment involves setting up a textView as the empty view for the list.
http://developer.android.com/reference/android/app/ListFragment.html#setEmptyText(java.lang.CharSequence)
You can change this by extending a Fragment and create your own ListView inside it. you can use the code from the ListFragment if you like some of the things it offers.
As an alternative you can try to do getListView().setEmptyView() and set up the view that you need. Again see how they do it in the code in the ListFragment and reproduce it with a different View (instead of TextView use a Button or ImageButton whatever you need)
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/app/ListFragment.java

Categories

Resources