This question already has answers here:
What does the "Assigned value is never used" warning mean?
(5 answers)
Closed 7 years ago.
After creating my activity, I get this warning:
Variable 'station' is never used
I not certain as to what that warning means nor how to fix it. I'm guessing the 'station' variable hasn't been declared however I don't know the correct way to declare it. All help would be appreciated.
FragmentWCLine.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FragmentWCLine extends android.support.v4.app.Fragment {
public final static String EXTRA_MESSAGE = "Station_key";
private class WC {
private CharSequence station;
private CharSequence zone;
private Class<? extends Activity> activityClass;
private Class<? extends android.support.v4.app.Fragment> fragmentClass;
public WC(int stationResId, int zoneResId, Class<? extends Activity> activityClass, Class<? extends android.support.v4.app.Fragment> fragmentClass) {
this.fragmentClass = fragmentClass;
this.activityClass = activityClass;
this.station = getResources().getString(stationResId);
this.zone = getResources().getString(zoneResId);
}
#Override
public String toString() { return station.toString(); }
public String getzone(){ return zone.toString(); }
}
private static WC[] mWC;
private boolean mTwoPane;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_wc_line, container, false);
// Instantiate the list of stations.
mWC = new WC[]{
new WC(R.string.bank, R.string.zone_1, WCBankActivity.class, FragmentWCBank.class),
new WC(R.string.wat, R.string.zone_1, WCWATActivity.class, FragmentWCWAT.class)
};
final ListView listView = (ListView)v.findViewById(R.id.list_wc);
listView.setAdapter(new MyAdapter(getActivity(), mWC));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mTwoPane){
setItemNormal();
View rowView = view;
setItemSelected(rowView);
}
else{
Intent intent = new Intent(getActivity(), mWC[position].activityClass);
String station = mWC[position].station.toString();
intent.putExtra(EXTRA_MESSAGE, station);
startActivity(intent);
}
}
public void setItemSelected(View view){
View rowView = view;
view.setBackgroundColor(Color.parseColor("#66CCCC"));
TextView tv0 = (TextView)rowView.findViewById(R.id.list_item_station);
tv0.setTextColor(Color.parseColor("#000099"));
TextView tv1 = (TextView)rowView.findViewById(R.id.list_item_zone);
tv1.setTextColor(Color.parseColor("#000099"));
}
public void setItemNormal()
{
for (int i=0; i< listView.getChildCount(); i++) {
View v = listView.getChildAt(i);
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.list_item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.list_item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
}
});
return v;
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView station;
TextView zone;
}
LayoutInflater inflater;
WC[] mWC;
public MyAdapter(Context contexts, WC[] samples) {
this.mWC = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mWC.length;
}
#Override
public Object getItem(int position) {
return mWC[position];
}
#Override
public long getItemId(int position) {
return 0;
}
/**set selected position**/
private int selectPosition = -1;
public void setSelectPosition(int position){
if(position!=selectPosition){
selectPosition = position;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_dualline, null);
viewHolder = new ViewHolder();
viewHolder.station = (TextView) convertView.findViewById(R.id.list_item_station);
viewHolder.zone = (TextView) convertView.findViewById(R.id.list_item_zone);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.station.setText(mWC[position].station);
viewHolder.zone.setText(mWC[position].getzone());
//change item color
if(position==selectPosition){
convertView.setBackgroundColor(Color.parseColor("#000099"));
viewHolder.station.setTextColor(Color.parseColor("#000099"));
}else {
}
return convertView;
}
}
}
WCBankActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
public class WCBankActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "Station_key";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_wc_bank);
if (savedInstanceState == null) {
// Get the message from the intent
Intent intent = getIntent();
// Notice to specify the sender Activity for the message
String station = intent.getStringExtra(WCBankActivity.EXTRA_MESSAGE);
FragmentWCBank newFragment = new FragmentWCBank();
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
}
}
}
FragmentWCBank.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentWCBank extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wc_bank, container, false);
return v;
}
}
What you are seeing is a Warning rather than an Error. The difference being a Warning will not prevent your program from running, but an Error would.
The warning you are seeing is due to the fact that you are declaring a variable station but then never using it. Your IDE is smart enough to notice this and is trying to warn you as a reminder that you aren't using the variable that you created.
In this case it's this line:
String station = intent.getStringExtra(WCBankActivity.EXTRA_MESSAGE);
You declare a variable station and give it a value but then you never read that value or do anything else with it. Therefore you could theoretically remove the variable with no other impact to your app.
Related
Howdy, I'm working on a project and I'm running into some issues. Namely, I have two fragments, each with their own adapter as both fragments are meant to be able to swipe horizontally. A photo should be attached of the layout I have for further clarity. I would like to be able to tap the bottom fragment, which when I tap a place on the top fragment, the image I tapped or "Structure" will be placed down. However, what I can't figure out is how to smoothly transfer this data and if I were to do it through the activity, how do I do it as the activity has already run through all its code. Could somebody please help, it would be greatly appreciated.
Main Activity
public class MainMap extends AppCompatActivity
{
MapData data = MapData.get();
StructureData structure = StructureData.get();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map);
FragmentManager frag = getSupportFragmentManager(); //To manage the map fragment
MapCellFragment rv = (MapCellFragment) frag.findFragmentById(R.id.map);
FragmentManager selectionFrag = getSupportFragmentManager(); //To manage the selection fragment
SelectionCellFragment cf = (SelectionCellFragment) selectionFrag.findFragmentById(R.id.bar);
if (rv == null)
{
rv = new MapCellFragment(data);
frag.beginTransaction().add(R.id.map, rv).commit();
}
if (cf == null)
{
cf = new SelectionCellFragment(structure);
selectionFrag.beginTransaction().add(R.id.bar, cf).commit();
}
}
Map Fragment
public MapData data;
public MapCellFragment() {
// Required empty public constructor
}
public MapCellFragment(MapData data)
{
this.data = data;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment gridCellFragment.
*/
// TODO: Rename and change types and number of parameters
public static MapCellFragment newInstance(String param1, String param2) {
MapCellFragment fragment = new MapCellFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.map_fragment, container, false);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
rv.setLayoutManager(new GridLayoutManager(getActivity(), MapData.HEIGHT, GridLayoutManager.HORIZONTAL,false));
MapAdapter myAdapter = new MapAdapter(data);
rv.setAdapter(myAdapter);
return view;
}
Bottom Bar Fragment
This was essentially a copy and paste of the other fragment, just changing the data which goes in and the XML it's attached to.
Map Adapter
package com.example.map;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MapAdapter extends RecyclerView.Adapter<MapViewHolder>
{
MapData data;
public MapAdapter(MapData data)
{
this.data = data;
}
#NonNull
#Override
public MapViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.grid_cells,parent,false);
//Resizes the images within the grid cells xml file
int size = parent.getMeasuredHeight() / MapData.HEIGHT + 1;
ViewGroup.LayoutParams lp = view.getLayoutParams();
lp.width = size;
lp.height = size;
MapViewHolder myViewHolder = new MapViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MapViewHolder holder, int position)
{
int row = position % MapData.HEIGHT;
int col = position / MapData.HEIGHT;
MapElement ele = data.get(row, col);
holder.ne.setImageResource(ele.getNorthEast());
holder.nw.setImageResource(ele.getNorthWest());
holder.se.setImageResource(ele.getSouthEast());
holder.sw.setImageResource(ele.getSouthWest());
if(ele.getStructure() != null)
{
holder.mapStruct.setImageResource(ele.getStructure().getDrawableId());
}
}
#Override
public int getItemCount()
{
return 300;
}
}
Map View Holder
package com.example.map;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Objects;
public class MapViewHolder extends RecyclerView.ViewHolder {
ImageView nw;
ImageView ne;
ImageView sw;
ImageView se;
ImageView mapStruct;
public MapViewHolder(#NonNull View itemView)
{
super(itemView);
nw = itemView.findViewById(R.id.northWest);
ne = itemView.findViewById(R.id.northEast);
sw = itemView.findViewById(R.id.southWest);
se = itemView.findViewById(R.id.southEast);
mapStruct = itemView.findViewById(R.id.structure);
}
}
Bar Adapter
package com.example.map;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SelectionAdapter extends RecyclerView.Adapter<SelectionViewHolder>
{
StructureData data;
public SelectionAdapter(StructureData data)
{
this.data = data;
}
#NonNull
#Override
public SelectionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.list_selection,parent,false);
SelectionViewHolder myViewHolder = new SelectionViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull SelectionViewHolder holder, int position)
{
Structure s = data.get(position);
holder.structure.setImageResource(s.getDrawableId());
holder.label.setText(s.getLabel());
holder.bind(s);
}
#Override
public int getItemCount()
{
return data.size();
}
}
Bar ViewHolder
package com.example.map;
import android.annotation.SuppressLint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Objects;
public class SelectionViewHolder extends RecyclerView.ViewHolder
{
Structure selectObject;
ImageView structure;
TextView label;
public SelectionViewHolder(#NonNull View itemView)
{
super(itemView);
structure = itemView.findViewById(R.id.image);
label = itemView.findViewById(R.id.label);
structure.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
SelectionCellFragment.selectedData = selectObject;
}
});
}
public void bind(Structure s)
{
selectObject = s;
}
//Maybe, I need to place this bind function in MapViewHolder as well
//When I press on the button, I must share the information over to the Map fragment
//Then the new information will form a ImageView on the big one
}
You could use ViewModel to solve your use-case. You could have something like SelectedStructureViewModel that will be set in the SelectionCellFragment when the user taps to select the structure. While the MapCellFragment can observe this SelectedStructureViewModel to be notified whenever the user selects the structure. You can then query it when user taps a place on the Map.
I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
then dashpercent and dashsubject give an error that they are not declared.
Adapter
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
#Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
dashboadfragment:
package com.example.attendance;
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 androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
dashbord_recycler_componets:
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
MainActivity:
package com.example.attendance;
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.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
Your percentage in dashboard_recycler_components is an int if you want to assign
your percentage is an int if you want to assign it to your dashpercent you have to first make this int a String such as : dashpercent.setText(String.valueOf(data.percentage));
PS:
You should rename your class object dashboard_recycler_components to dashboardRecyclerComponents and use camelCase instead of snake_case
The Problem is you are trying to get the layout views inside onBindViewHolder and you can't this you can declare your viewes in your custom ViewHolder and get the views inside onBindViewHolder like this ... i think this gonna solve your problem
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
#Override
public int getItemCount() {
return dashlist.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView dashpercent;
TextView dashsubject;
ProgressBar dashProgress;
RecyclerViewHolder(#NonNull View itemView) {
super(itemView);
dashpercent = itemView.findViewById(R.id.dashPercent);
dashsubject = itemView.findViewById(R.id.dashSubject);
dashProgress = itemView.findViewById(R.id.recycler_progress);
}
}
}
I have a button inside a fragment that is inside an activity. The fragment contains Edittext for user to enter input then press a button and some action is processed. When I click the button I don't even see Log.v output on my logcat tab. That means android is not detecting the onClickListener event. I wonder if is because that event needs to happen in the activity thread and the fragment works in another thread. If someone could clarify how to get this working?
Activity
public class TracerouteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_traceroute);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
Fragment
package org.pctechtips.netdroid.traceroute;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
public class TraceRouteFragment extends Fragment {
public static final String tag = "TraceroutePing";
public static final String INTENT_TRACE = "INTENT_TRACE";
private Button buttonLaunch;
private EditText editTextPing;
private ProgressBar progressBarPing;
private ListView listViewTraceroute;
private TraceListAdapter traceListAdapter;
protected ProgressDialog scanProgressDialog;
private TracerouteWithPing tracerouteWithPing;
private final int maxTtl = 40;
private List<TracerouteContainer> traces;
/**
* onCreate, init main components from view
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.traceroute, container, false);
this.tracerouteWithPing = new TracerouteWithPing(this);
this.traces = new ArrayList<TracerouteContainer>();
this.buttonLaunch = (Button) view.findViewById(R.id.buttonLaunch);
this.editTextPing = (EditText) view.findViewById(R.id.editTextPing);
this.listViewTraceroute = (ListView) view.findViewById(R.id.listViewTraceroute);
this.progressBarPing = (ProgressBar) view.findViewById(R.id.progressBarPing);
traceListAdapter = new TraceListAdapter(getContext());
listViewTraceroute.setAdapter(traceListAdapter);
buttonLaunch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editTextPing.getText().length() == 0) {
Toast.makeText(getContext(), getString(R.string.no_text_trace), Toast.LENGTH_SHORT).show();
} else {
traces.clear();
traceListAdapter.notifyDataSetChanged();
startProgressBar();
hideSoftwareKeyboard(editTextPing);
tracerouteWithPing.executeTraceroute(editTextPing.getText().toString(), maxTtl);
}
Log.v(tag, "traceroute to " + editTextPing.getText().toString());
}
});
return view;
}
/**
* initView, init the main view components (action, adapter...)
*/
private void initView() {
}
/**
* Allows to refresh the listview of traces
*/
/*public void refreshList(TracerouteContainer trace) {
final TracerouteContainer fTrace = trace;
runOnUiThread(new Runnable() {
#Override
public void run() {
traces.add(fTrace);
traceListAdapter.notifyDataSetChanged();
}
});
}*/
/**
* The adapter of the listview (build the views)
*/
public class TraceListAdapter extends BaseAdapter {
private Context context;
public TraceListAdapter(Context c) {
context = c;
}
public int getCount() {
return traces.size();
}
public TracerouteContainer getItem(int position) {
return traces.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// first init
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.item_list_trace, null);
TextView textViewNumber = (TextView) convertView.findViewById(R.id.textViewNumber);
TextView textViewIp = (TextView) convertView.findViewById(R.id.textViewIp);
TextView textViewTime = (TextView) convertView.findViewById(R.id.textViewTime);
ImageView imageViewStatusPing = (ImageView) convertView.findViewById(R.id.imageViewStatusPing);
// Set up the ViewHolder.
holder = new ViewHolder();
holder.textViewNumber = textViewNumber;
holder.textViewIp = textViewIp;
holder.textViewTime = textViewTime;
holder.imageViewStatusPing = imageViewStatusPing;
// Store the holder with the view.
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
TracerouteContainer currentTrace = getItem(position);
if (position % 2 == 1) {
convertView.setBackgroundResource(R.drawable.table_odd_lines);
} else {
convertView.setBackgroundResource(R.drawable.table_pair_lines);
}
if (currentTrace.isSuccessful()) {
holder.imageViewStatusPing.setImageResource(R.drawable.ic_check_green_24dp);
} else {
holder.imageViewStatusPing.setImageResource(R.drawable.ic_close_red_24dp);
}
holder.textViewNumber.setText(position + "");
holder.textViewIp.setText(currentTrace.getHostname() + " (" + currentTrace.getIp() + ")");
holder.textViewTime.setText(currentTrace.getMs() + "ms");
return convertView;
}
// ViewHolder pattern
class ViewHolder {
TextView textViewNumber;
TextView textViewIp;
TextView textViewTime;
ImageView imageViewStatusPing;
}
}
/**
* Hides the keyboard
*
* #param currentEditText The current selected edittext
*/
public void hideSoftwareKeyboard(EditText currentEditText) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(currentEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public void startProgressBar() {
progressBarPing.setVisibility(View.VISIBLE);
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
scanProgressDialog = new ProgressDialog(getContext(), R.style.NewDialog);
scanProgressDialog.setCancelable(false);
scanProgressDialog.getWindow().setGravity(Gravity.CENTER);
scanProgressDialog.setTitle("Tracing.... Please wait");
scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
scanProgressDialog.show();
}
public void stopProgressBar() {
// progressBarPing.setVisibility(View.GONE);
// getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
scanProgressDialog.dismiss();
}
#Override
public void onPause() {
super.onPause();
}
}
In your buttonLaunch.setOnClickListener() method parameter, you have used ' new View.onClickListener(){}', you have to change this to 'new OnClickListener(){}', everything else inside it will be same.
Check out this post for more:
Android Fragment onClick button Method
It should work. Check your adapter to be sure it works fine. Also it best you show us your logs.
try using
buttonLunch = (ImageButton) getActivity().findViewById(R.id.buttonLaunch);
Please am having issue with this null error message java.lang.NullPointerException (no error message). I really need assistance on how and where to add the appropriate code so that the application would not crash. Here is the JAVA file that i am having issues with. I am trying to create a recycler view and jpg images from my drawable folder
HorizontalListAdapter.java
import android.app.Activity;
import android.graphics.Picture;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class HorizontalListAdapter extends RecyclerView.Adapter<HorizontalListAdapter.ViewHolder>
{
private Activity activity;
int[] images= {R.drawable.vb1,R.drawable.pota,R.drawable.vb1,
R.drawable.pota,R.drawable.vb1,R.drawable.download1,R.drawable.pota};
String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};
public HorizontalListAdapter(Activity activity)
{
this.activity = activity;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(R.layout.item_horizontal_list, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(HorizontalListAdapter.ViewHolder viewHolder, final int position) {
viewHolder.imageView.setImageResource(images[position]);
viewHolder.txtview.setText(food_items[position].toUpperCase());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Position clicked: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return images.length;
}
/**
* View holder to display each RecylerView item
*/
protected class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private ImageView imageView;
private TextView txtview;
public ViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.imageview);
txtview = (TextView) view.findViewById(R.id.txtview);
linearLayout = (LinearLayout) view.findViewById(R.id.layout);
}
}
}
The second java class VerticalListAdapter.java
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.ViewHolder> {
private Activity activity;
public VerticalListAdapter(Activity activity) {
this.activity = activity;
}
int[] images= {R.drawable.images,R.drawable.images,R.drawable.images,
R.drawable.images,R.drawable.images,R.drawable.images,R.drawable.images};
String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};
String[] cost={"Rs 200","Rs 300","Rs 150","R 320","Rs 450","Rs 120","Rs 380"};
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(R.layout.item_recycler_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// if ((position + 1) % 2 == 0) {
viewHolder.imageView.setImageResource(images[position]);
viewHolder.txtview.setText(food_items[position].toUpperCase());
viewHolder.txtCost.setText("Cost Per Person "+cost[position]);
// } else {
// viewHolder.imageView.setImageResource(R.drawable.awadhi_lucknow_biryani);
//}
viewHolder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Position: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return images.length;
}
/**
* View holder to display each RecylerView item
*/
protected class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView txtview;
private TextView txtCost;
private RelativeLayout container;
public ViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.image);
txtview = (TextView) view.findViewById(R.id.text);
txtCost= (TextView) view.findViewById(R.id.textView);
container = (RelativeLayout) view.findViewById(R.id.container);
}
}
}
Please i need assistance with this i guess it is the int[]images causing the error i may be wrong please correct me with the right code i would use to replace and make the code work.
changeimageview accessibility form private to any other modifier & try again
I am trying to write different functionalities for my FloatingActionButton depending on the fragment that the mainActivity is currently hosting. Yet for for reason in my onClick() method, getSupportFragmentManager().findFragmentById() returns null.
I haven't seen any examples of this question implemented with a viewpager and I am curious if there is a different approach I have to take.
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
public class MainActivity extends FragmentActivity {
private Adapter mAdapter;
private ViewPager mViewPager;
private static FloatingActionButton bButton;
private static String UID;
private Intent intent;
public static String getUID(){
return UID;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new Adapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.vPager);
mViewPager.setAdapter(mAdapter);
intent = getIntent();
UID = intent.getStringExtra("uid");
bButton = (FloatingActionButton)findViewById(R.id.bButton);
bButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragContainer);
if(fragment == null){
Log.e("TAG","FRAGMENT IS NULL!!");
}
else{
Log.e("TAG","FRAGMENT IS NOT NULL!!");
}
}
});
}
}
NewsFeedFragment
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.mycompany.neighbors.R;
import com.mycompany.neighbors.SinglePost;
import java.util.ArrayList;
/**
* Created by joshua on 5/25/2016.
*/
public class NewsFeedFragment extends ListFragment implements AdapterView.OnItemClickListener{
private ListView lv;
private TextView tvUserName;
private TextView tvStatus;
private ArrayList<SinglePost> posts = new ArrayList<>();
private static final String POSTS_PATH = "MY_PATH";
private Firebase postsRef;
// private static final String FRAGMENT_POST = "post";
public void postFragment(){
Log.d("TAG", "Doing something else");
PostFragment postFragment = new PostFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragContainer,postFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onViewCreated(View v, Bundle s){
lv = getListView();
lv.setOnItemClickListener(this);
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_post_feed_item,parent,false);//changed
tvUserName = (TextView)v.findViewById(R.id.tvUN);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
postsRef = new Firebase(POSTS_PATH);
postsRef.addChildEventListener(new com.firebase.client.ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
SinglePost post = dataSnapshot.getValue(SinglePost.class);
post.setKey(dataSnapshot.getKey());
posts.add(0, post);
if(posts.size() > 0) {
PostAdapter adapter = new PostAdapter(posts);
setListAdapter(adapter);
}else{
Toast toast = Toast.makeText(getActivity(),"No data", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
SinglePost p = ((PostAdapter) getListAdapter()).getItem(position);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class PostAdapter extends ArrayAdapter<SinglePost>{
public PostAdapter(ArrayList<SinglePost> singlePost){
super(getActivity(),android.R.layout.simple_list_item_1,singlePost);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_post_feed_item,null);
}
SinglePost p = getItem(position);
TextView tvUserName = (TextView)convertView.findViewById(R.id.tvUN);
tvUserName.setText(p.getUserName());
TextView tvStatus = (TextView)convertView.findViewById(R.id.tvStatus);
tvStatus.setText(p.getStatus());
return convertView;
}
}
}
I have 2 other fragments but i'll post one as an example. Here is my adapter for the viewpager.
Adapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.mycompany.neighbors.Fragments.MapFragment;
import com.mycompany.neighbors.Fragments.NewsFeedFragment;
import com.mycompany.neighbors.Fragments.ProfileFragment;
/**
* Created by joshua on 5/25/2016.
*/
public class Adapter extends FragmentPagerAdapter {
private String Fragment[] = {"Posts" , "Map" , "Profile"};
public Adapter(FragmentManager fm){
super (fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new NewsFeedFragment();
case 1:
return new MapFragment();
case 2:
return new ProfileFragment();
default:
return null;
}
}
#Override
public int getCount(){return Fragment.length;}
#Override
public CharSequence getPageTitle(int position) {
return Fragment[position];
}
}
Please check below link, It has very good explanation for your problem:
http://tamsler.blogspot.in/2011/11/android-viewpager-and-fragments-part-ii.html
Or you can try below code snippet:
1.Where you add fragment in view pager or view pager adapter:
MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment,"Some Tag").commit();
2.To get the tag for the currently visible page, you then call:
int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);
3.and then get the fragment page:
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);