Error getting value from EditText - java

For some reason I can't get text from EditText with OnClickListener for my button. I want to get these values and place them into data[] and then transfer it to my main activity. For some reason it breaks on if statement in onClick() method. I've checked all the ids of layout elements and that's not the problem.
Here is the source code for my fragment:
package com.xivi0n.materialcalculator;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class FirstFragment extends Fragment implements View.OnClickListener {
RadioGroup rd;
CheckBox cb;
Button calculate;
OnHeadlineSelectedListener sendData;
private EditText yEditText;
private EditText xEditText;
private RadioGroup type;
float data[] = new float[6];
public FirstFragment() {
// Required empty public constructor
}
public interface OnHeadlineSelectedListener {
public void onArticleSelected(float data[]);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
sendData = (OnHeadlineSelectedListener)context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
rd = (RadioGroup) v.findViewById(R.id.isolationOptions);
cb = (CheckBox)v.findViewById(R.id.isolationCB);
xEditText = (EditText) v.findViewById(R.id.xValue);
yEditText = (EditText) v.findViewById(R.id.yValue);
type = (RadioGroup) v.findViewById(R.id.typeOf);
calculate = (Button) v.findViewById(R.id.calculateButton);
cb.setOnClickListener(this);
calculate.setOnClickListener(this);
return v;
}
public void onClick(View v) {
if (v==cb) {
if (cb.isChecked()) {
rd.setVisibility(View.VISIBLE);
} else {
rd.setVisibility(View.INVISIBLE);
}
} else if (v==calculate){
if ((xEditText.getText().toString()!="") && (yEditText.getText().toString()!="")){
data[0] = (float)1;
data[1] = Float.parseFloat(xEditText.getText().toString());
data[2] = Float.parseFloat(yEditText.getText().toString());
data[3] = (float) type.indexOfChild(getActivity().findViewById(type.getCheckedRadioButtonId()));
if (cb.isChecked()){
data[4] = (float)1;
data[5] = (float) rd.indexOfChild(getActivity().findViewById(type.getCheckedRadioButtonId()));
} else {
data[4] = (float)0;
data[5] = (float)0;
}
sendData.onArticleSelected(data);
} else {
Toast.makeText(getActivity(), "Invalid input, check all the parameters!", Toast.LENGTH_LONG).show();
}
}
}
}

Switch on the id of the view:
public void onClick(View v) {
switch (v.getId()){
case R.id.isolationCB:
//do something
break;
case R.id.calculateButton:
//do something else
}
}

Use .equals to compare strings.
Instead of ((xEditText.getText().toString()!= "")) use (!(xEditText.getText().toString().equals("")); as the condition of if statement.

Related

Why my recyclerview isn't showing any item?

I just created my recyclerview to show a cardview when I just filling the required data on AddNewTimerFragment.java. But somehow it wont show the card that contains the data that I've fill in before. I've tried to changes something, but doesn't work.
Code :
MainActivity.java
package com.mobprog.ius.dwasu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private ArrayList<MyListDataTimer> mintervalTimeList = new ArrayList();
private RecyclerView mRecyclerView;
private alarmListAdapter mAdapter;
public boolean isFragmentAddNewAlarmDisplayed = false;
static final String STATE_FRAGMENT = "state_of_fragment";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.textUserName)).setText("Hello " + getSharedPreferences("Dwasu", 0).getString("user", ""));
if (getSharedPreferences("Dwasu", 0) == null || !getSharedPreferences("Dwasu", 0).contains("user")) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
// Create recycler view.
mRecyclerView = findViewById(R.id.recyclerView);
// Create an adapter and supply the data to be displayed.
mAdapter = new alarmListAdapter(getApplicationContext(), mintervalTimeList);
// Connect the adapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
if (savedInstanceState != null)
isFragmentAddNewAlarmDisplayed = savedInstanceState.getBoolean(STATE_FRAGMENT);
Button mnewReminderButton = findViewById(R.id.newReminder);
mnewReminderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(MainActivity.class.getSimpleName(),"Button Clicked");
displayFragment();
}
});
ImageButton mlogOutButton = findViewById(R.id.logOutButton);
findViewById(R.id.logOutButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSharedPreferences("Dwasu", 0).edit().clear().apply();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
// // Get the Drawable custom_progressbar
// Drawable draw = ResourcesCompat.getDrawable(getResources(), R.drawable.progress_bar, null);
// // set the drawable as progress drawable
// ProgressBar.setProgressDrawable(draw);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the state of the fragment (true=open, false=closed).
savedInstanceState.putBoolean(STATE_FRAGMENT, isFragmentAddNewAlarmDisplayed);
super.onSaveInstanceState(savedInstanceState);
}
public void closeFragment(){
// Get the FragmentManager.
FragmentManager fragmentManager = getSupportFragmentManager();
// Check to see if the fragment is already showing.
AddNewTimerFragment simpleFragment = (AddNewTimerFragment) fragmentManager
.findFragmentById(R.id.FragmentContainer_AddNewAlarm);
if (simpleFragment != null) {
// Create and commit the transaction to remove the fragment.
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.remove(simpleFragment).commit();
}
// Set boolean flag to indicate fragment is closed.
isFragmentAddNewAlarmDisplayed = false;
}
public void displayFragment(){
AddNewTimerFragment simpleFragment = AddNewTimerFragment.newInstance();
// Get the FragmentManager and start a transaction.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// Add the SimpleFragment.
fragmentTransaction.add(R.id.FragmentContainer_AddNewAlarm,
simpleFragment).addToBackStack(null).commit();
// Set boolean flag to indicate fragment is open.
isFragmentAddNewAlarmDisplayed = true;
}
}
AddNewTimerFragment.java
package com.mobprog.ius.dwasu;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
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.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import org.apache.http.entity.mime.content.StringBody;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import static android.content.Context.MODE_PRIVATE;
public class AddNewTimerFragment extends Fragment {
Button startTime;
Button endTime;
Button meditConfirm_button;
int startHour;
int startMinute;
int endHour;
int endMinute;
int position = 1;
long totalSize = 0;
String value;
ProgressDialog progDailog;
View rootview;
private SharedPreferences mPreferences;
private String sharedPrefFile =
"com.mobprog.ius.dwasu";
public AddNewTimerFragment() {
// Required empty public constructor
}
public static AddNewTimerFragment newInstance() {
return new AddNewTimerFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_new_alarm,
container, false);
rootview = rootView;
/*Shared Pref*/
mPreferences = this.getActivity().getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
SharedPreferences.Editor mPreferencesEditor = mPreferences.edit();
ImageButton mbtnCloseFragment = rootView.findViewById(R.id.btnCloseFragment);
mbtnCloseFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).closeFragment();
}
});
// initiate the edit text
startTime = rootView.findViewById(R.id.startTimePick);
startTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
startTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
startHour = mcurrentTime.get(Calendar.HOUR);
startMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mStartTimePicker;
mStartTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedStartHour, int selectedStartMinute) {
if (selectedStartMinute == 0) {
startTime.setText(selectedStartHour + ":00");
} else if (selectedStartMinute < 10) {
if (selectedStartHour < 10) {
startTime.setText("0" + selectedStartHour + ":0" + selectedStartMinute);
}
} else {
startTime.setText(selectedStartHour + ":" + selectedStartMinute);
}
startHour = selectedStartHour;
}
}, startHour, startMinute, true);//Yes 24 hour time
mStartTimePicker.show();
}
});
endTime = rootView.findViewById(R.id.endTimePick);
endTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
endTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
endHour = mcurrentTime.get(Calendar.HOUR);
endMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mEndTimePicker;
mEndTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedEndHour, int selectedEndMinute) {
if (selectedEndMinute == 0) {
endTime.setText(selectedEndHour + ":00");
} else if (selectedEndMinute < 10) {
if (selectedEndHour < 10) {
endTime.setText("0" + selectedEndHour + ":0" + selectedEndMinute);
}
} else {
endTime.setText(selectedEndHour + ":" + selectedEndMinute);
}
endHour = selectedEndHour;
}
}, endHour, endMinute, true);//Yes 24 hour time
mEndTimePicker.show();
}
});
Spinner spinner = (Spinner) rootView.findViewById(R.id.timeIntervalPick);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.listtimer, R.layout.spinner_support);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.spinner_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String[] valueListTimer = getResources().getStringArray(R.array.valueListTimer);
value = valueListTimer[position];
Log.e("Value of Spinner", value);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
meditConfirm_button = rootView.findViewById(R.id.editConfirm_button);
meditConfirm_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String.valueOf(startHour);
String.valueOf(endHour);
String.valueOf(value);
new MyListDataTimer(String.valueOf(startHour),String.valueOf(endHour),String.valueOf(value),String.valueOf(position));
new UploadAlarmDataToServer().execute();
position++;
}
});
// Inflate the layout for this fragment
return rootView;
}
private class UploadAlarmDataToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progDailog = new ProgressDialog(getContext());
progDailog.setMessage("Menyimpan...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(false);
progDailog.setCanceledOnTouchOutside(false);
progDailog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
String data = null;
try {
data = sendDataTimer();
} catch (Exception e) {
e.printStackTrace();
data = "Gagal";
}
return data;
}
public String sendDataTimer() throws Exception {
URL url = new URL("https://ius.mobile.indoserver.web.id/alarmData.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
entity.addPart("startHour", new StringBody(startHour + ""));
entity.addPart("endHour", new StringBody(endHour + ""));
entity.addPart("intervalWaktu", new StringBody(value + ""));
totalSize = entity.getContentLength();
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.addRequestProperty("Content-length", totalSize + "");
con.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = con.getOutputStream();
entity.writeTo(con.getOutputStream());
os.close();
con.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
#Override
protected void onPostExecute(String result) {
progDailog.dismiss();
if (result != null) {
Log.e("UPLOAD", result);
if (result.equalsIgnoreCase("OK")) {
Toast.makeText(getContext(), "Data Alarm tersimpan", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getContext(), MainActivity.class));
}
}
super.onPostExecute(result);
}
}
}
alarmListAdapter.java
package com.mobprog.ius.dwasu;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedList;
public class alarmListAdapter extends RecyclerView.Adapter<alarmListAdapter.alarmListHolder>{
private final ArrayList<MyListDataTimer> mintervalTimeList;
private LayoutInflater mInflater;
public alarmListAdapter(Context context, ArrayList<MyListDataTimer> mintervalTimeList) {
mInflater = LayoutInflater.from(context);
this.mintervalTimeList = mintervalTimeList;
}
#Override
public alarmListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.alarm_item,
parent, false);
return new alarmListHolder(mItemView, this);
}
#Override
public void onBindViewHolder(alarmListAdapter.alarmListHolder holder, int position) {
final MyListDataTimer myListData = mintervalTimeList.get(position);
holder.mintervalTime.setText(myListData.getIntervalWaktu());
holder.mtimeWork.setText(myListData.getStartHour() +":00 - " + myListData.getEndHour() +":00");
}
#Override
public int getItemCount() {
return mintervalTimeList.size();
}
public class alarmListHolder extends RecyclerView.ViewHolder {
public TextView mintervalTime;
public TextView mtimeWork;
final alarmListAdapter mAdapter;
public alarmListHolder(View itemView, alarmListAdapter adapter) {
super(itemView);
mintervalTime = itemView.findViewById(R.id.intervalTime);
mtimeWork = itemView.findViewById(R.id.timeWork);
this.mAdapter = adapter;
}
}
}
**MyListDataTimer.java**
package com.mobprog.ius.dwasu;
public class MyListDataTimer {
private String startHour;
private String endHour;
private String intervalWaktu;
private String position;
public MyListDataTimer(String startHour, String endHour, String intervalWaktu, String position) {
this.startHour = startHour;
this.endHour = endHour;
this.intervalWaktu = intervalWaktu;
this.position = position;
}
public String getStartHour() {
return startHour;
}
public void setStartHour(String startHour) {
this.startHour = startHour;
}
public String getEndHour() {
return endHour;
}
public void setEndHour(String endHour) {
this.endHour = endHour;
}
public String getIntervalWaktu() {
return intervalWaktu;
}
public void setIntervalWaktu(String intervalWaktu) {
this.intervalWaktu = intervalWaktu;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}

SetOnClickListener Not Working When Button Clicked in Fragment

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

I have a code break in this fragment but I can't solve it.. It showing that I have null reference ob set text but when I debug I see data

## fragment 1
I am geting null reference on setText on TextView control but I can't find a reason why...
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.helper.Util;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.OpstinaVM;
import ba.fit.app.hci_odbrana.podaci.PosiljkaVM;
public class PosiljaocFragment extends Fragment {
public static final String NEKI_KLJUC = "nekiKljuc";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView viewImePosiljaoca;
private TextView adresaPosiljaoca;
private PosiljkaVM posiljkaVM = new PosiljkaVM();
private OpstinaVM opstina;
public PosiljaocFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PosiljaocFragment newInstance(PosiljkaVM posiljka) {
PosiljaocFragment fragment = new PosiljaocFragment();
Bundle args = new Bundle();
args.putSerializable(NEKI_KLJUC, posiljka);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
posiljkaVM = (PosiljkaVM) getArguments().getSerializable(NEKI_KLJUC);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_posiljaoc, container, false);
viewImePosiljaoca = (TextView) view.findViewById(R.id.viewImePosiljaoca);
adresaPosiljaoca = (TextView) view.findViewById(R.id.viewAdresaPosiljaoca);
final Button btnPromjeniPosiljaoca = (Button) view.findViewById(R.id.btnPromjeniPosiljaoca);
Button btnDalje = (Button) view.findViewById(R.id.btnDalje);
if (posiljkaVM.posljiaoc != null){
viewImePosiljaoca.setText(posiljkaVM.posljiaoc.getIme() + " " + posiljkaVM.posljiaoc.getPrezime());
adresaPosiljaoca.setText(posiljkaVM.posljiaoc.getAdresa() + " - " + posiljkaVM.posljiaoc.getOpstinaVM().getNaziv());
}
btnDalje.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnDaljeClick();
}
});
btnPromjeniPosiljaoca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPromjeniPosiljaocaClick();
}
});
return view;
}
private void btnDaljeClick() {
if (posiljkaVM.primaoc == null){
posiljkaVM.primaoc = new KorisnikVM("", "", new OpstinaVM(0,"",""), "");
}
if (posiljkaVM.posljiaoc == null){
posiljkaVM.posljiaoc = new KorisnikVM(posiljkaVM.posljiaoc.getIme(), posiljkaVM.posljiaoc.getPrezime(), opstina, "");
}
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PrimaocFragment.newInstance(posiljkaVM));
}
private void btnPromjeniPosiljaocaClick() {
MyRunnable<KorisnikVM> callback = new MyRunnable<KorisnikVM>() {
#Override
public void run(KorisnikVM result) {
posiljkaVM.posljiaoc = result;
viewImePosiljaoca.setText(result.getIme() + " " + result.getPrezime());
adresaPosiljaoca.setText(result.getAdresa() + " - " + result.getOpstinaVM().getNaziv());
posiljkaVM.posljiaoc.setIme(result.getIme());
posiljkaVM.posljiaoc.setPrezime(result.getPrezime());
posiljkaVM.posljiaoc.setOpstinaVM(result.getOpstinaVM());
posiljkaVM.posljiaoc.setAdresa(result.getAdresa());
}
};
Util.otvoriFragmentKaoDijalog(getActivity(), KorisniciFragment.newInstance(callback));
}
}
### dialog fragment
package ba.fit.app.hci_odbrana.fragmenti;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.Storage;
public class KorisniciFragment extends DialogFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private MyRunnable<KorisnikVM> callback;
private String mParam2;
private EditText txtImePrezime;
private ListView listKorisnici;
private TextView linija1;
private TextView linija2;
private List<KorisnikVM> podaci;
public KorisniciFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static KorisniciFragment newInstance(MyRunnable<KorisnikVM> myCallback) {
KorisniciFragment fragment = new KorisniciFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, myCallback);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
callback = (MyRunnable<KorisnikVM>) getArguments().getSerializable(ARG_PARAM1);
}
setStyle(STYLE_NORMAL, R.style.MojDijalog);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_korisnici, container, false);
txtImePrezime = (EditText) view.findViewById(R.id.txtImePrezime);
listKorisnici = (ListView) view.findViewById(R.id.listKorisnici);
Button btnTrazi = (Button) view.findViewById(R.id.btnTrazi);
popuniPodatke("");
btnTrazi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnTraziClick();
}
});
listKorisnici.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
KorisnikVM x = podaci.get(position);
getDialog().dismiss();
callback.run(x);
}
});
return view;
}
private void btnTraziClick() {
popuniPodatke(txtImePrezime.getText().toString());
}
private void popuniPodatke(String name) {
podaci = Storage.getKorisniciByName(name);
listKorisnici.setAdapter(new BaseAdapter() {
#Override
public int getCount() {
return podaci.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
KorisnikVM x = podaci.get(position);
if( view == null)
{
final LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.stavka_korisnici, viewGroup, false);
}
linija1 = (TextView) view.findViewById(R.id.linija1);
linija2 = (TextView) view.findViewById(R.id.linija2);
linija1.setText(x.getIme() + " " + x.getPrezime());
linija2.setText(x.getOpstinaVM().getNaziv() + " - " + x.getAdresa());
return view;
}
});
}
}
## Fragment 2
Here everything works fine and it's very similar to first one.
package ba.fit.app.hci_odbrana.fragmenti;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.helper.Util;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.PosiljkaVM;
/**
* A simple {#link Fragment} subclass.
* Use the {#link PrimaocFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PrimaocFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private PosiljkaVM mParam1;
private TextView viewImePrimaoca;
private TextView adresaPrimaoca;
public PrimaocFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PrimaocFragment newInstance(PosiljkaVM param1) {
PrimaocFragment fragment = new PrimaocFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (PosiljkaVM) getArguments().getSerializable(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_primaoc, container, false);
viewImePrimaoca = (TextView) view.findViewById(R.id.viewImePrimaoca);
adresaPrimaoca = (TextView) view.findViewById(R.id.viewAdresaPrimaoca);
final Button btnPromjeniPrimaoca = (Button) view.findViewById(R.id.btnPromjeniPrimaoca);
final Button btnNazad = (Button) view.findViewById(R.id.btnNazad);
final Button btnDalje2 = (Button) view.findViewById(R.id.btnDalje2);
if (getArguments() != null){
viewImePrimaoca.setText(mParam1.primaoc.getIme() + " " + mParam1.primaoc.getPrezime());
adresaPrimaoca.setText(mParam1.primaoc.getAdresa() + " - " + mParam1.primaoc.getOpstinaVM().getNaziv());
}
btnDalje2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnDalje2Click();
}
});
btnNazad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNazadClick();
}
});
btnPromjeniPrimaoca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPromjeniPrimaocaClick();
}
});
return view;
}
private void btnNazadClick() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PosiljaocFragment.newInstance(mParam1));
}
private void btnDalje2Click() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PaketFragment.newInstance(mParam1));
}
private void btnPromjeniPrimaocaClick() {
MyRunnable<KorisnikVM> callback = new MyRunnable<KorisnikVM>() {
#Override
public void run(KorisnikVM result) {
mParam1.primaoc = result;
viewImePrimaoca.setText(result.getIme() + " " + result.getPrezime());
adresaPrimaoca.setText(result.getAdresa() + " - " + result.getOpstinaVM().getNaziv()); //here is where I get that null reference
}
};
Util.otvoriFragmentKaoDijalog(getActivity(), KorisniciFragment.newInstance(callback));
}
}
## package fragment
This is for showing some details on package that is been sent when you chose sender and receiver
public class PaketFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
// TODO: Rename and change types of parameters
private PosiljkaVM mParam1;
private EditText txtMasa;
private EditText txtNapomena;
public PaketFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PaketFragment newInstance(PosiljkaVM param1) {
PaketFragment fragment = new PaketFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (PosiljkaVM) getArguments().getSerializable(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_paket, container, false);
txtMasa = (EditText) view.findViewById(R.id.txtMasa);
txtNapomena = (EditText) view.findViewById(R.id.txtNapomena);
final Button btnZavrsi = (Button) view.findViewById(R.id.btnZavrsi);
final Button btnNazad2 = (Button) view.findViewById(R.id.btnNazad2);
btnNazad2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNazad2Click();
}
});
btnZavrsi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnZavrsiClick();
}
});
return view;
}
private void btnZavrsiClick() {
try {
mParam1.masa = Float.parseFloat(txtMasa.getText().toString());
mParam1.napomena = txtNapomena.getText().toString();
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PosiljaocFragment.newInstance(mParam1));
Toast.makeText(getActivity(), "Uspješno spremljena pošiljka!", Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(getActivity(), "Greška: " + e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private void btnNazad2Click() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PrimaocFragment.newInstance(mParam1));
}
}
That's it.. hope someone can help me. Have a pleasant day.

How to refer to a fragment within a ViewPager with FragmentManager?

So I've been working on a basic weather app for android, and after implementing a viewpager with tabs the app throws a NullPointerException every time I try to use the changeCity method within the main activity; this needs to refer to the fragment and since I have changed the way the fragment is instantiated I have no clue how to do this.
My main activity:
import android.app.AlertDialog;
import android.support.v4.app.FragmentManager;
import android.content.DialogInterface;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class WeatherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Current Weather"));
tabLayout.addTab(tabLayout.newTab().setText("Forecast"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
/*if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new WeatherFragment())
.commit();
}*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_weather, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.change_city) {
showInputDialog();
}
return false;
}
private void showInputDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Change city");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
changeCity(input.getText().toString());
}
});
builder.show();
}
public void changeCity(String city){
FragmentManager fm = getSupportFragmentManager();
WeatherFragment wf = (WeatherFragment)fm.findFragmentById(R.id.fragment_weather);
//EXCEPTION IS THROWN HERE
wf.changeCity(city);
new CityPreference(this).setCity(city);
}
public void changeBackground(String timeOfDay) {
String day = "DAY";
String dusk = "DUSK";
String night = "NIGHT";
RelativeLayout layout = (RelativeLayout) findViewById(R.id.container);
if (timeOfDay.equals(day)) {
layout.setBackgroundColor(getResources().getColor(R.color.background_day));
//setTheme(R.style.CustomAppTheme_NoActionBarTitle_Day);
} else if(timeOfDay.equals(dusk)){
layout.setBackgroundColor(getResources().getColor(R.color.background_dusk));
//setTheme(R.style.CustomAppTheme_NoActionBarTitle_Dusk);
} else if(timeOfDay.equals(night)){
layout.setBackgroundColor(getResources().getColor(R.color.background_night));
//setTheme(R.style.CustomAppTheme_NoActionBarTitle_Night);
}
}
}
My PagerAdapter class where the fragments get instantiated:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by User on 31/08/2015.
*/
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs){
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
WeatherFragment tab1 = new WeatherFragment();
return tab1;
case 1:
ForecastFragment tab2 = new ForecastFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
The WeatherFragment class:
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
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 android.os.Handler;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Weather app fragment, handles the display of all elements within the FrameLayout of the main
* activity.
*/
public class WeatherFragment extends Fragment {
public static final String TAG = "SimpleWeather Fragment";
Typeface weatherFont;
TextView cityField;
TextView updatedField;
TextView localTimeField;
TextView detailsField;
TextView currentTemperatureField;
TextView weatherIcon;
ImageButton refreshButton;
Handler handler;
public WeatherFragment(){
handler = new Handler();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_weather, container, false);
cityField = (TextView)rootView.findViewById(R.id.city_field);
updatedField = (TextView)rootView.findViewById(R.id.updated_field);
localTimeField = (TextView)rootView.findViewById(R.id.local_time_field);
detailsField = (TextView)rootView.findViewById(R.id.details_field);
currentTemperatureField = (TextView)rootView.findViewById(R.id.current_temperature_field);
weatherIcon = (TextView)rootView.findViewById(R.id.weather_icon);
refreshButton = (ImageButton)rootView.findViewById(R.id.refresh_button);
refreshButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
updateWeatherData(new CityPreference(getActivity()).getCity());
}
});
weatherIcon.setTypeface(weatherFont);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
weatherFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/weather.ttf");
updateWeatherData(new CityPreference(getActivity()).getCity());
}
private void updateWeatherData(final String city){
new Thread(){
public void run(){
final JSONObject json = RemoteFetch.getJSON(getActivity(), city);
if (json == null){
handler.post(new Runnable(){
public void run(){
Toast.makeText(getActivity(),
getActivity().getString(R.string.place_not_found),
Toast.LENGTH_LONG).show();
}
});
} else {
handler.post(new Runnable(){
#Override
public void run() {
renderWeather(json);
}
});
}
}
}.start();
}
private void renderWeather(JSONObject json){
try {
cityField.setText(json.getString("name").toUpperCase(Locale.UK) +
"," +
json.getJSONObject("sys").getString("country"));
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
detailsField.setText(
details.getString("description").toUpperCase(Locale.UK) +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + "hPa");
currentTemperatureField.setText(
String.format("%.2f", main.getDouble("temp")) + " ℃");
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
String updatedOn = df.format(new Date(json.getLong("dt") * 1000));
updatedField.setText("Last update: " + updatedOn);
/* TODO local time field */
setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
String t = new TimeOfDay().getTimeOfDay(
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
((WeatherActivity)getActivity()).changeBackground(t);
}catch (Exception e) {
Log.e("SimpleWeather", "One or more fields not found in JSON data");
}
}
private void setWeatherIcon(int id, long sunrise, long sunset){
int shortId = id / 100;
long currentTime = new Date().getTime();
String icon = "";
if(id==800 || id==801 || id==802 || id==803 || shortId==3){
if (currentTime>=sunrise && currentTime<sunset) {
if(shortId==3){
icon = getActivity().getString(R.string.weather_day_showers);
} else {
switch (id) {
case 800 : icon = getActivity().getString(R.string.weather_sunny);
break;
case 801 : icon = getActivity().getString(R.string.weather_day_few_clouds);
break;
case 802: icon = getActivity().getString(R.string.weather_day_overcast);
break;
case 803: icon = getActivity().getString(R.string.weather_day_overcast);
break;
}
}
} else {
if (shortId==3){
icon = getActivity().getString(R.string.weather_night_showers);
} else {
switch (id) {
case 800: icon = getActivity().getString(R.string.weather_clear_night);
break;
case 801: icon = getActivity().getString(R.string.weather_night_few_clouds);
break;
case 802: icon = getActivity().getString(R.string.weather_night_overcast);
break;
case 803: icon = getActivity().getString(R.string.weather_night_overcast);
break;
}
}
}
} else {
switch (shortId) {
case 2 : icon = getActivity().getString(R.string.weather_thunder);
break;
case 7 : icon = getActivity().getString(R.string.weather_foggy);
break;
case 8 : icon = getActivity().getString(R.string.weather_cloudy);
break;
case 6 : icon = getActivity().getString(R.string.weather_snowy);
break;
case 5 : icon = getActivity().getString(R.string.weather_rainy);
break;
}
}weatherIcon.setText(icon);
}
public void changeCity(String city){
updateWeatherData(city);
}
}
And the LogCat:
08-31 14:57:15.704 15649-15649/simpleweather.ockmore.will.simpleweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: simpleweather.ockmore.will.simpleweather, PID: 15649
java.lang.NullPointerException: Attempt to invoke virtual method 'void simpleweather.ockmore.will.simpleweather.WeatherFragment.changeCity(java.lang.String)' on a null object reference
at simpleweather.ockmore.will.simpleweather.WeatherActivity.changeCity(WeatherActivity.java:95)
at simpleweather.ockmore.will.simpleweather.WeatherActivity$2.onClick(WeatherActivity.java:84)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
The Fragments are auto Tagged by the ViewPager
private static String makeFragmentName(int viewPagerId, int index) {
return "android:switcher:" + viewPagerId + ":" + index;
}
see Android getting fragment that is in FragmentPagerAdapter

Why does my ArrayList add elements itself on my fragment event?

How i have said in my question i have a fragment with a list of check boxes and an ArrayList of items choosen (they are the labels of the check boxes). When the event of a check box is fired the fragment calls the method of the interface in the main activity but in it the list of items choosen has already the item in it, although there isn't in the entire code any method that can add items to it.
Here the code:
MainActivity :
package com.fp.testfragment1;
import java.util.ArrayList;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import com.fp.testfragment1.MultiChoiceFragment.OnMultiSelectedListener;
public class MainActivity extends Activity implements OnMultiSelectedListener
{
FrameLayout frameLayout1;
FrameLayout frameLayout2;
Button transitionButton;
FragmentManager fragmentManager;
MultiChoiceFragment multiChoiceFragment;
Boolean replace;
ArrayList<String> list;
ArrayList<String> mylis;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<String>();
mylis = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
list.add("item4");
list.add("item5");
transitionButton = (Button)findViewById(R.id.transitionButton);
transitionButton.setOnClickListener(transitionListener);
frameLayout1 = (FrameLayout)findViewById(R.id.frameLayout1);
frameLayout1 = (FrameLayout)findViewById(R.id.frameLayout2);
fragmentManager = getFragmentManager();
}
#Override
protected void onStart()
{
super.onStart();
replace = false;
}
OnClickListener transitionListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
multiChoiceFragment = new MultiChoiceFragment(MainActivity.this, list, mylis, 8);
fragmentTransaction.setCustomAnimations(R.animator.card_flip_right_in, R.animator.card_flip_right_out, R.animator.card_flip_left_in, R.animator.card_flip_left_out);
if(replace)
{
fragmentTransaction.replace(R.id.frameLayout1, multiChoiceFragment);
}
else
{
fragmentTransaction.add(R.id.frameLayout1, multiChoiceFragment);
replace = true;
}
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
#Override
public void onGroupMCheckListener(String itemName, Boolean checked, int nf)
{
if(nf == 8)
{
//here i have the list already full
// this is for debug
mylis = mylis;
}
}
}
MultiChoiceFragment :
package com.fp.testfragment1;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MultiChoiceFragment extends Fragment
{
Context context;
OnMultiSelectedListener mCallback;
LinearLayout groupsListLinearLayout;
TableRow congiungiTableRow;
TextView groupsTextView;
ArrayList<String> groups;
ArrayList<String> groupsChoosen;
int nFragment;
public MultiChoiceFragment(Context context, ArrayList<String> groups, ArrayList<String> groupsChoosen, int nFragment)
{
this.context = context;
this.groups = new ArrayList<String>();
this.groupsChoosen = new ArrayList<String>();
this.groups = groups;
this.groupsChoosen = groupsChoosen;
this.nFragment = nFragment;
}
public MultiChoiceFragment()
{
groups = new ArrayList<String>();
groupsChoosen = new ArrayList<String>();
}
public interface OnMultiSelectedListener
{
public void onGroupMCheckListener(String itemName, Boolean checked, int nf);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
mCallback = (OnMultiSelectedListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + " must implement OnMultiSelectedListener");
}
context = activity;
}
#Override
public void onSaveInstanceState(Bundle outState)
{
outState.putStringArrayList("groups", groups);
outState.putStringArrayList("groupsChoosen", groupsChoosen);
outState.putInt("nFragment", nFragment);
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.choice_fragment, container, false);
groupsListLinearLayout = (LinearLayout)v.findViewById(R.id.groupsLinearLayout);
groupsTextView = (TextView)v.findViewById(R.id.groupsTextView);
congiungiTableRow = (TableRow)v.findViewById(R.id.congiungiTableRow);
if(savedInstanceState != null)
{
groups = savedInstanceState.getStringArrayList("groups");
groupsChoosen = savedInstanceState.getStringArrayList("groupsChoosen");
nFragment = savedInstanceState.getInt("nFragment");
}
refreshListGUI();
return v;
}
public void refreshListGUI()
{
for(int a = 0; a < groups.size(); a++)
{
CheckBox checkBox = new CheckBox(context);
checkBox.setId(a);
if(groupsChoosen == null || groupsChoosen.isEmpty() == true)
{
checkBox.setChecked(false);
}
else if(groupsChoosen.isEmpty() == false && groupsChoosen.contains(groups.get(a)))
{
checkBox.setChecked(true);
}
checkBox.setText((String)groups.get(a));
checkBox.setOnCheckedChangeListener(checkBoxMItemListener);
groupsListLinearLayout.addView(checkBox);
}
}
OnCheckedChangeListener checkBoxMItemListener = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
String groupC = buttonView.getText().toString();
if(isChecked == true && groupsChoosen.contains(groupC) == false)
{
groupsChoosen.add(groupC);
mCallback.onGroupMCheckListener(groupC, isChecked, nFragment);
}
else if(isChecked == false && groupsChoosen.contains(groupC) == true)
{
groupsChoosen.remove(groupC);
mCallback.onGroupMCheckListener(groupC, isChecked, nFragment);
}
}
};
}
PS. I use the nf in another project

Categories