getListView() not working showing null pointer exception - java

I have a ListFragment OnItemClick is not working; it's basically not getting called. I have been unable to find any errors in my code. Is this somehow a problem with getListView?
I've explored Google and StackOverflow but did not find a solution. Here's my code:
public class FragmentSongs extends ListFragment implements OnFragmentCreatedListener,OnItemClickListener {
static ListView lv;
private static final String TAG = FragmentSongs.class.getSimpleName();
MediaMetadataRetriever metaRetriver1;
Vector<ForPLaylist> gtuMcaBean= new Vector<ForPLaylist>();
Forplaylistadapter adaptor;
String artist="";
static int i=0,f=0,k=0;;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
trial t=new trial();
t.onCreate();
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.playlist, container,false);
metaRetriver1 = new MediaMetadataRetriever();
lv=(ListView) root.findViewById(android.R.id.list);
//data calculation here
lv.setAdapter(adaptor);
// lv = getListView();//showing error here if i call it
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int songIndex=position;
Intent in = new Intent(getActivity(), AndroidBuildingMusicPlayerActivity.class);
in.putExtra("songIndex",songIndex);
startActivityForResult(in, 100);
closefragment();
}
});
return root;
}
OnFragmentCreatedListener listener;
private void closefragment() {
getActivity().getFragmentManager().popBackStack();
}
#Override
public void onFragmentCreated(ArrayList<String> msg) {
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int songIndex=position;
Intent in = new Intent(null, AndroidBuildingMusicPlayerActivity.class);
in.putExtra("songIndex",songIndex);
startActivityForResult( in,100);
finish();
}
private void finish() {
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "onActivityCreated");
if(savedInstanceState != null) {
Log.d(TAG, "saved variable number: " + savedInstanceState.getInt("number"));
}
super.onActivityCreated(savedInstanceState);
// lv=getListView();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// lv = getListView();
}
}

try move your getListView();to onActivityCreated and make sure you call super.onActivityCreated(savedInstanceState) first

I think you should check the code in onItemClick of ListFragment (not the code of onItemClick inside onCreateView method):
Intent in = new Intent(null, AndroidBuildingMusicPlayerActivity.class);
Just change it to:
Intent in = new Intent(getActivity(), AndroidBuildingMusicPlayerActivity.class);

Related

how to access from an object created in a different class?

I have two fragments, a HomeFragment and a SettingsFragment. In the Settingsfragment I have a spinner. Depending on what item is selected in the spinner, i want to either set the maximum of progress bar higher or lower. So I have a string variable (spinnerTime) in settingsfragment class, but I want to have access to this string variable in the home class. How can I do this? Do I have to work with an interface here? Heres the code a function in homefragment class:
public void handleProgress(){
countDownTimer = new CountDownTimer(86400*1000,1000) {
#Override
public void onTick(long millisUntilFinished) {
//EDIT: added thes lines:
SharedPreferences sp =
getContext().getSharedPreferences("spinner",
Context.MODE_PRIVATE);
String spinnerTime = sp.getString("spinner", "");
progress = progress +1;
progressBar.setProgress(progress);
if (spinnerTime.equals("1min")){
progressBar.setMax(60);
} else if (spinnerTime.equals("30min")){
progressBar.setMax(1800);
} else if (spinnerTime.equals("1h")) {
progressBar.setMax(3600);
} else if (spinnerTime.equals("24h")) {
progressBar.setMax(3600*24);
}
}
The following code shows the settingsfragment class:
public class SettingsFragment extends Fragment {
Spinner spinner;
ImageView ring_spinner;
String item;
String spinnerTime;
TextView tv_timeOfCircle;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.settingsfragment, container);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
ring_spinner = (ImageView) view.findViewById(R.id.ring_spinner);
tv_timeOfCircle = view.findViewById(R.id.textView);
spinner = (Spinner) view.findViewById(R.id.spinner);
handleSpinner();
super.onViewCreated(view, savedInstanceState);
}
public void handleSpinner(){
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.numbers, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
spinnerTime = spinner.getSelectedItem().toString();
//EDIT: added the four following lines to the
//settingsfragment class
sp = getActivity().getSharedPreferences("spinner",
getContext().MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("spinnerStr", spinnerTime);
editor.commit();
Toast showItem = Toast.makeText(parent.getContext(),
spinnerTime, Toast.LENGTH_SHORT);
showItem.show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Now of course i have got a cannot resolve symbol "spinnerTime" error. Has somebody an idea to solve this? Id be really grateful for any advice

My list from JSON not showing on listview in mobile application, why?

This is my code. What can I change?
Notification fragment
public class NotificationsFragment extends Fragment {
private ArrayList<String> arrayList;
private ListView listView;
private RequestQueue queue;
private ArrayAdapter arrayAdapter;
private List<Earthquake> quakeList;
private int contentView;
private View view;
I think I have problem with this listview and this line of code: listView = getActivity().findViewById(R.id.listview) . I try to fix this but no success.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_notifications);
quakeList = new ArrayList<>();
listView = getActivity().findViewById(R.id.listview);
queue = Volley.newRequestQueue(getActivity().getApplicationContext());
arrayList = new ArrayList<>();
getAllQuakes(Constants.URL);
}
The rest of the code.What can i return to show list?
private void setContentView(int fragment_notifications) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_notifications, container, false);
return view;
}
void getAllQuakes(String url) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Earthquake earthquake = new Earthquake();
How can I send from console to listview? Should I change something?
try {
JSONArray features = response.getJSONArray("features");
for (int i = 0; i < Constants.LIMIT; i++) {
JSONObject properties = features.getJSONObject(i).getJSONObject("properties");
JSONObject geometry = features.getJSONObject(i).getJSONObject("geometry");
JSONArray coordinates = geometry.getJSONArray("coordinates");
double lon = coordinates.getDouble(0);
double lat = coordinates.getDouble(1);
//Log.d("Quake", lon + ", " + lat);
Log.d("Lat", properties.getString("place"));
earthquake.setPlace(properties.getString("place"));
earthquake.setType(properties.getString("type"));
earthquake.setTime(properties.getLong("time"));
earthquake.setMagnitude(properties.getDouble("mag"));
earthquake.setLon(lon);
earthquake.setLat(lat);
arrayList.add(earthquake.getPlace());
}
ArrayAdapter:
final ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "Clicked " + position, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Clicked"+ position,Toast.LENGTH_LONG).show();
}
});
arrayAdapter.notifyDataSetChanged();
you know the life cycle of fragment is differnt with activity..
so in onCreate fragmnet dont need do any thing:
write your code in onViewCreated()
it is work for me :
public class BlankFragment extends Fragment {
ListView listView;
ArrayList<String> arrayList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
listView=getActivity().findViewById(R.id.list);
arrayList=new ArrayList<>();
getAllQuakes("");
}
void getAllQuakes(String url) {
for(int i=0;i<10;i++){
arrayList.add("vaa"+i);
}
final ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "Clicked " + position, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Clicked"+ position,Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
}
}
Just change listView.setAdapter(arrayAdapter) to listView.setAdapter(adapter).

Why is sharedPreference not saving here?

I am trying to set some strings in the sharedPreferences but when I restart the app , the preference is coming empty and so "null" is returned in getString method .
public class settingsView extends Fragment {
DataSnapshot citiesSnap;
Spinner theaterSpinner, citySpinner;
String selectedCity, selectedTheater;
String[] cities = {"Bagalkot", "Belgaum", "Bellary", "Bijapur", "Chitradurga", "Davanagere", "Dharwad", "Gadag", "Hassan", "Hosapete", "Hospet", "Hubli", "Mysore", "Shimoga", "Tumkur"};
List<String>theaters ;
public settingsView() {
Log.d("testing" , "settingsview constructor called");
citiesSnap = null;
theaterSpinner = null;
citySpinner = null;
selectedCity = null;
selectedTheater = null;
theaters = null ;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d("testing", "Called onActivityCreated");
citySpinner = (Spinner) getActivity().findViewById(R.id.citySpinner);
theaterSpinner = (Spinner) getActivity().findViewById(R.id.theaterSpinner);
final SharedPreferences mSettings = this.getActivity().getPreferences(Context.MODE_PRIVATE);
selectedCity = mSettings.getString("selectedCity", "null" );
selectedTheater = mSettings.getString("selectedTheater", "null");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, cities);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(adapter);
updateTheatersSpinner(selectedCity);
if(theaters!=null)
theaterSpinner.setSelection(theaters.indexOf(selectedTheater));
FirebaseDatabase.getInstance().getReference("movies/karnataka").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
citiesSnap = dataSnapshot;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
updateTheatersSpinner(citySpinner.getSelectedItem().toString());
mSettings.edit().putString("selectedCity" , citySpinner.getSelectedItem().toString()).commit();
}
});
theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
mSettings.edit().putString("selectedTheater" , theaterSpinner.getSelectedItem().toString()).commit() ;
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settingsview, container, false);
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
Log.d("testing" , "On save instancestate") ;
super.onSaveInstanceState(outState);
SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
preferences.edit().putString("selectedCity", selectedCity).putString("selectedTheater", theaterSpinner.getSelectedItem().toString()).commit();
}
public void updateTheatersSpinner(String city) {
if (citiesSnap != null) {
ArrayList<String> theaterlist = new ArrayList<>();
for (DataSnapshot snapshot : citiesSnap.child(city).getChildren()) {
theaterlist.add(snapshot.getKey());
}
this.theaters = theaterlist ;
Log.d("firebasedata", "theaterlist : " + theaterlist.toString());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, theaterlist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.theaterSpinner.setAdapter(adapter);
}
}
}
You have the class fields selectedCity and selectedTheater which you never update so they are always null, but then in onSaveInstanceState you save those fields, so when your activity closes, it writes null to both fields in the SharedPreferences. You should update those fields when the spnner changes.
citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
selectedCity = citySpinner.getSelectedItem().toString(); // <--
updateTheatersSpinner(selectedCity);
mSettings.edit().putString("selectedCity", selectedCity).commit();
}
});
theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
selectedTheater = theaterSpinner.getSelectedItem().toString(); // <--
mSettings.edit().putString("selectedTheater", selectedTheater).commit();
}
});
Then, in onSaveInstanceState
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
Log.d("testing" , "On save instancestate") ;
super.onSaveInstanceState(outState);
SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
preferences.edit()
.putString("selectedCity", selectedCity)
.putString("selectedTheater", selectedTheater)
.commit();
}

onListitemClick is never used

I am using onListItemClick with simple_list_item_1
public class DrinkCategoryActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listDrinks = getListView();
ArrayAdapter<Drinks> listAdapter = new ArrayAdapter<Drinks>(this,
android.R.layout.simple_list_item_1,
Drinks.drinks);
listDrinks.setAdapter(listAdapter);
}
#Override
public void onListItemClick(ListView listView, View itemview, int position, int id){
Intent intent = new Intent(this, DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKNO, id);
startActivity(intent);
}
}
It says that onListItemClick is never used
When I open my app it doesn't respond to click.
I don't want to use a new layout activity.
I am using list activity which doesn't always require layout
You should use setOnItemClickListener
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object listItem = list.getItemAtPosition(position);
}
});
you can try below
public class DrinkCategoryActivity extends Activity implements AdapterView.OnItemClickListener
{
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_drink_category);
ListView listDrinks = (ListView)findViewById(R.id.your_list_view_id);
ArrayAdapter<Drinks> listAdapter = new ArrayAdapter<Drinks>(this,
android.R.layout.simple_list_item_1,
Drinks.drinks);
listDrinks.setAdapter(listAdapter);
listDrinks.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Callback logic here for clicked items
}
...
}
Try this
listDrinks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
Just add
public class DrinkCategoryActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listDrinks = getListView();
ArrayAdapter<Drinks> listAdapter = new ArrayAdapter<Drinks>(this,
android.R.layout.simple_list_item_1,
Drinks.drinks);
listDrinks.setAdapter(listAdapter);
// Add this block
listDrinks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKNO, id);
startActivity(intent);
}
});
}
Remove
#Override
public void onListItemClick(ListView listView, View itemview, int position, int id){
Intent intent = new Intent(this, DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKNO, id);
startActivity(intent);
}

Start Acitvity from Fragment

I got my MainActivity(FragmentActivity) with ViewPager with FragmentPagerAdapter which creates OrdersFragment in which i have ListView. Now i want to start new Activity OnItemClickListener but i can't figure out how to do this.
This is OrdersFragment class:
public class OrdersFragment extends Fragment {
ListView lv;
private ArrayList<Order> d = new ArrayList<Order>();
private ordersAdapter adapter;
public OrdersFragment (){
}
public OrdersFragment setArguments(ArrayList<Order> orders){
if(adapter == null) return this;
adapter.setData(orders);
Log.d("fragment", "zmiana");
adapter.notifyDataSetChanged();
return this;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//d.add(new Order());
Log.d("fragment", "orders fragment created" + d.toString());
lv = (ListView) inflater.inflate(R.layout.orders_list, container, false);
lv.setOnItemClickListener(itemClicked);
adapter = new ordersAdapter(inflater, d);
lv.setAdapter(adapter);
return lv;
}
public ArrayList<Order> getOrders(){
return d;
}
OnItemClickListener itemClicked = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
startActivity(new Intent(OrdersFragment.this, OrderActivity.class));
}
};
}
It says that Intent constructor is undefined and also when i move over startActivity it says Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found. And it states that this fuction is defined in android.support.v4.app.Fragment.startActivity but I'm acually import this:
import android.app.Activity;
import android.content.Intent;
What I'm doing wrong?
Try this pass context as getActivity() to intent
OnItemClickListener itemClicked = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
startActivity(new Intent(getActivity(), OrderActivity.class));
}
};
In Fragment we have to pass context as getActivity(), replace your code with this below code it will work.
OnItemClickListener itemClicked = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
startActivity(new Intent(getActivity(), OrderActivity.class));
}
};
OnItemClickListener itemClicked = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(getActivity() != null) {
Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
startActivity(new Intent(getActivity(), OrderActivity.class));
}
}
};
getActivity() will give you the Activity context that you can use to start the new Activity. In some rare cases getActivity() can return null so checking getActivity() is not null might not harm in your case.

Categories

Resources