Preset spinner in onCreate is overwritten - android

In an activity I have a spinner where the user can select which date should be displayed in the activity.
But in the previous activity there can be a preselection done. This preselection is passed to the activity by intent.putExtra.
The problem is that when I want to set the preselection with setSelection in the onCreate function it is always overwritten by the onItemSelected function.
How can I do this in the right way?
The code locks like this:
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout
setContentView(R.layout.activity_list);
setTitle(getString(R.string.List_Title));
// for alerts
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
// RecyclerView
adapter = new ListAdapter_rc(this);
lvArticle = (RecyclerView)findViewById(R.id.listView);
lvArticle.setAdapter(adapter);
lvArticle.setLayoutManager(new LinearLayoutManager(this));
new ItemTouchHelper(itemTouchCallback).attachToRecyclerView(lvArticle);
spListSelect = (Spinner)findViewById(R.id.spListSelect);
adapter.dbm = new DBManager(this);
ListAdapter_rc a = adapter;
ArrayList<String> slDummy = new ArrayList<>();
slDummy.addAll(adapter.dbm.listListGetNames());
slDummy.add("Default");
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, R.layout.spinner_item, slDummy);
spListSelect.setAdapter(adapt);
spListSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
adapter.setList(adapter.dbm.listListGet().get(i).id);
// THIS IS CALLED SECOND (i is always 0)
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
adapter.adminMode = extras.getBoolean("adminMode");
int i = (int)extras.getLong("listSelcted", 0);
adapter.setList((long)i);
spListSelect.setSelection(i,false); // THIS IS CALLED FIRST (i has the desired value)
}
}

Related

Select item in ListView using value from Intent

I'm trying to select an item in a ListView based on a value I get from an Intent. I've tried ListView.setSelection, but it's not working.
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
Here is the rest of the code, for context:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sport_item);
ListView listView = findViewById(R.id.listview);
String[] sports = new String[] {
"Soccer",
"Running",
"Swimming",
"Volleyball",
"Tennis"
};
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.listview, R.id.textView, sports);
listView.setAdapter(arrayAdapter);
Button btnSelect = findViewById(R.id.btnSelect);
listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ListView.getCheckedItemPosition() != -1) {
Intent i = new Intent(SportActivity.this, InformationActivity.class);
i.putExtra("Sport", sports[listView.getCheckedItemPosition()]); |
i.putExtra("Position", listView.getCheckedItemPosition());
setResult(Activity.RESULT_OK, i);
finish();
} else
Toast.makeText(SportActivity.this, "Ban chua lya chon", Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SportActivity.this, "Sport selected :" + sports[i], Toast.LENGTH_SHORT).show();
}
});
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
}
show more code, post it in here. you should call setSelected only after setting adapter, before there is no content on list so nothing gets selected
in your case your problem is caused probably by comparing Strings with == operator. in Java it compares objects and one obtained from intent and second one from array arent same objects, even if they have same content (they still are two objects in two separated placed in memory). use equals method for comparing only content
if(sports[position].equals(sp))

Problem with using depended spinner (Multiple spinner) in android

I'm trying to populate value of the next spinner from the previous spinner. In this case, what I did yet is generating all values inside the spinner means, no matter which value I select in the previous spinner it is always showing all values in the next spinner. I'm using five spinners that needs to populate values according to the previous one. Here I'm using a library for the spinner. The library is as follows.
'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
Here I'm sharing my whole code/class for your consideration. There is no error and I get all values in respective spinner but I want to get values according to the previous one. here is my code.
import androidx.appcompat.app.AppCompatActivity;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;
public class Catchment extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public ArrayAdapter<String> regionAdapter;
public ArrayAdapter<String> districtAdapter;
public ArrayAdapter<String> upzAdapter;
public ArrayAdapter<String> unionAdapter;
public ArrayAdapter<String> villageAdapter;
public String[] Region = {"1", "2",
};
public String[] District = {"1","2","3","4","5","6","7","8",};
public String[] Upz = {"1","2"...."23";
public String[] Union = {"1","2"...."25"..."50"...."115"};
public String[] Village = { "1","2"...."25"..."50"...."150"...."500"...."947" };
Button catchment_code;
SearchableSpinner spinner_region, spinner_district, spinner_upz, spinner_union, spinner_village;
String[] region_code;
String[] district_code;
String[] upz_code;
String[] union_code;
String[] vill_code;
int positions;
String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catchment);
spinner_region = (SearchableSpinner) findViewById(R.id.region);
spinner_district = (SearchableSpinner) findViewById(R.id.district);
spinner_upz = (SearchableSpinner) findViewById(R.id.upz);
spinner_union = (SearchableSpinner) findViewById(R.id.union);
spinner_village = (SearchableSpinner) findViewById(R.id.village);
catchment_code = findViewById(R.id.catchment_code);
// Set spninner adapter
regionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Region);
districtAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, District);
upzAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Upz);
unionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Union);
villageAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Village);
//Set dropdown to the spinner
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
upzAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
unionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
villageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//assign to spinner
spinner_region.setAdapter(regionAdapter);
spinner_district.setAdapter(districtAdapter);
spinner_upz.setAdapter(upzAdapter);
spinner_union.setAdapter(unionAdapter);
spinner_village.setAdapter(villageAdapter);
spinner_region.setOnItemSelectedListener(this);
spinner_district.setOnItemSelectedListener(this);
spinner_upz.setOnItemSelectedListener(this);
spinner_union.setOnItemSelectedListener(this);
spinner_village.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.region) {
positions = spinner_region.getSelectedItemPosition();
region_code = this.getResources().getStringArray(R.array.region_code);
//Toast.makeText(this, region_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.district) {
positions = spinner_district.getSelectedItemPosition();
district_code = this.getResources().getStringArray(R.array.district_code);
//Toast.makeText(this, district_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.upz) {
positions = spinner_upz.getSelectedItemPosition();
upz_code = this.getResources().getStringArray(R.array.upz_code);
//Toast.makeText(this, upz_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.village) {
positions = spinner_village.getSelectedItemPosition();
vill_code = this.getResources().getStringArray(R.array.village_code);
//Toast.makeText(this, vill_code[positions], Toast.LENGTH_LONG).show();
}
if (parent.getId() == R.id.union) {
positions = spinner_union.getSelectedItemPosition();
union_code = this.getResources().getStringArray(R.array.union_code);
//Toast.makeText(this, union_code[positions], Toast.LENGTH_SHORT).show();
}
if (!(vill_code == null || region_code == null || district_code == null || upz_code == null ||
union_code == null)) {
test = region_code[positions] +
district_code[positions] +
upz_code[positions] +
union_code[positions] + vill_code[positions];
Toast.makeText(this, test, Toast.LENGTH_SHORT).show();
}
catchment_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Catchment.this, Participant_Details.class);
intent.putExtra("catment_code", test);
startActivity(intent);
}
});
//Toast.makeText(this, union_code[positions]+upz_code[positions], Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Catchment.this, SplashScreen.class);
Catchment.this.startActivity(intent);
Catchment.this.finish();}
}
So how can I get rid of this problem? I need help.
You are declaring all adapter at once in onCreate().
Instead declare just first adapter with values in onCreate() and declare other adapters with empty values.
#Override
protected void onCreate(Bundle savedInstanceState) {
--------;
// Set spninner adapter
regionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Region);
districtAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
upzAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
unionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
villageAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
------
spinner_region.setOnItemSelectedListener(this);
}
Now on itemSelectedListener, filter the desired values if needed and add the values to the next required adapter and notify the values along with adding listener to next spinner(adding listener is up to you, how you want to handle the things)
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.region) {
positions = spinner_region.getSelectedItemPosition();
String[] filteredDistrict = District.filter(Region[position]) // District.filter is not any predefined function, assuming some filter needed for selected Districts
districtAdapter.addValues(filteredDistrict);
districtAdapter.notifyDataSetChanged()
spinner_district.setOnItemSelectedListener(this);
}
}
Other than that filtering logic depends on your usecase.

Restoring State of Spinners and Their Adapters

I am having issues trying to restore state of Android Spinners in my application. Currently there are multiple Spinners in my Activity's ListView header that depend on one another, as the selection of one Spinner loads data for the subsequent Spinner.
The problem I am experiencing is, restoring state doesn't seem to work when I manually set selections on the Spinners. I have tried in both onRestoreInstanceState and onResume. It appears setting the selections is asynchronous when looking at the LogCat output. How can I reliably restore state of these Spinners when I have to wait for one to be selected before the other can populated and then set?
EDIT: Added code
Activity's onCreate():
mSecondSpinner = mMyListHeader.findViewById(R.id.second_spinner);
mSecondSpinnerArrayAdapter = new SecondArrayAdapter(MyActivity.this, R.layout.second_spinner_item, new ArrayList<MySecondDto>());
mSecondSpinner.setAdapter(mSecondSpinnerArrayAdapter);
mSecondSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
MySecondDto selectedMySecondDto = (MySecondDto) parent.getItemAtPosition(position);
List<MyThirdDto> myThirdDtos = selectedMySecondDto.getMyThirdDtos();
// Load third spinner with dtos....
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}}
);
mFirstSpinner = mMyListHeader.findViewById(R.id.first_spinner);
mFirstSpinnerAdapter= new FirstArrayAdapter(MyActivity.this, R.layout.first_spinner, mResponse.getAllDtos());
mFirstSpinner.setAdapter(mFirstSpinnerArrayAdapter);
mFirstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mSecondSpinner.setAdapter(null);
MyFirstDto selectedMyFirstDto = (MyFirstDto ) parent.getItemAtPosition(position);
List<MySecondDto> mySecondDtos = selectedMyFirstDto .getMySecondDtos();
mSecondSpinnerArrayAdapter.clearAndReplaceAll(mySecondDtos);
mSecondSpinner.setAdapter(mSecondSpinnerArrayAdapter);
// If there is only one second dto, disable the spinner
if (mySecondDtos== null || mySecondDtos.size() <= 1)
{
disableSpinner(mSecondSpinner);
}
else
{
// Enable second spinner, select the hint element
enableSpinner(mSecondSpinner);
mSecondSpinner.setSelection(mSecondSpinnerArrayAdapter .getHintIndex());
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});
Activity's onRestoreInstanceState():
mFirstSpinner.setSelection(mFirstAdapterPosition);
mFirstSpinnerArrayAdapter.notifyDataSetChanged();
mSecondSpinner.setSelection(mSecondAdapterPosition);
mSecondSpinnerArrayAdapter.notifyDataSetChanged();
Have u tried this
mySpinner.post(new Runnable() { #Override public void run() { mySpinner.setSelection(position); } });
This might work for you.
There could be a bug in it somewhere, so be careful.
I have a similar situation to you but I had 3 spinners and they get populated depending on the selection of the previous one.
The idea is to store the Indexes/Positions of the Spinners in IndexVariables.
Theses Variables have default value of -1.
Store current values in onSaveInstanceState,
Restore values in onActivityCreated.
In onItemSelected check if selected Item = null, check if the IndexVariable was set (i.e. !-= -1)
If so use it to set Spinner then set IndexVariable back to -1;
Here's the class
(I used NothingSelectedSpinnerAdapter from How to make an Android Spinner with initial text "Select One".
Not really important but just giving a shout out to the guy/girl where I got that code.)
public class SpinnerTestFragment extends Fragment {
private MainActivity activity;
private static final String SELECTED_THEME_IDX_STORAGE_KEY = "mSelectedTheme_IDX_StorageKey";
private static final String SELECTED_AIM_IDX_STORAGE_KEY = "mSelectedAim_IDX_StorageKey";
private static final String SELECTED_GOAL_IDX_STORAGE_KEY = "mSelectedGoal_IDX_StorageKey";
private static String TAG = "SpinnerTestFragment";
private Spinner spnrThemes;
private Spinner spnrAims;
private Spinner spnrGoals;
private String mSelectedTheme;
private String mSelectedAim;
private String mSelectedGoal;
private int mSelectedAimIdx = -1;
private int mSelectedThemeIdx = -1;
private int mSelectedGoalIdx = -1;
//----------------------------------------------------------------------------------------//
public SpinnerTestFragment() {
}//ctor
//----------------------------------------------------------------------------------------//
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
activity = (MainActivity) getActivity();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_photo, container, false);
spnrThemes = view.findViewById(R.id.spnrThemes);
spnrAims = view.findViewById(R.id.spnrAims);
spnrGoals = view.findViewById(R.id.spnrGoals);
setSpinner(spnrThemes, "Select Theme", ThemesAimsGoals.getThemes());
spnrThemes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedTheme = selectedItem.toString();
setSpinner(spnrAims, "Select Aim", ThemesAimsGoals.getAims(mSelectedTheme));
} else if(mSelectedThemeIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedThemeIdx);
mSelectedTheme = selectedItem.toString();
setSpinner(spnrAims, "Select Aim", ThemesAimsGoals.getAims(mSelectedTheme));
parent.setSelection(mSelectedThemeIdx);
mSelectedThemeIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spnrAims.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedAim = selectedItem.toString();
setSpinner(spnrGoals, "Select Goal", ThemesAimsGoals.getGoals(mSelectedTheme, mSelectedAim));
} else if(mSelectedAimIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedAimIdx);
mSelectedAim = selectedItem.toString();
setSpinner(spnrGoals, "Select Goal", ThemesAimsGoals.getGoals(mSelectedTheme, mSelectedAim));
parent.setSelection(mSelectedAimIdx);
mSelectedAimIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spnrGoals.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedGoal = selectedItem.toString();
}else if(mSelectedGoalIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedGoalIdx);
mSelectedGoal = selectedItem.toString();
parent.setSelection(mSelectedGoalIdx);
mSelectedGoalIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}//onCreateView
//----------------------------------------------------------------------------------------//
/**
* Populate Spinner
* #param spnr Spinner to populate
* #param prompt What to show at the start
* #param array Items in the spinner
*/
private void setSpinner(Spinner spnr, String prompt, String[] array) {
spnr.setPrompt(prompt);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnr.setAdapter(
new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
activity,
prompt));
}//setSpinner
//----------------------------------------------------------------------------------------//
/**
* Some lifecycle callbacks so that the image can survive orientation chang
*
* #param outState current state of fragment
*/
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_THEME_IDX_STORAGE_KEY, spnrThemes.getSelectedItemPosition());
outState.putInt(SELECTED_AIM_IDX_STORAGE_KEY, spnrAims.getSelectedItemPosition());
outState.putInt(SELECTED_GOAL_IDX_STORAGE_KEY, spnrGoals.getSelectedItemPosition());
}//onSaveInstanceState
//----------------------------------------------------------------------------------------//
/**
* Rebuilds the Activity/Fragment in the image of the last one.
*
* #param savedInstanceState Info from last session or rotation
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated");
if (savedInstanceState == null)
return;
mSelectedThemeIdx = savedInstanceState.getInt(SELECTED_THEME_IDX_STORAGE_KEY);
mSelectedAimIdx = savedInstanceState.getInt(SELECTED_AIM_IDX_STORAGE_KEY);
mSelectedGoalIdx = savedInstanceState.getInt(SELECTED_GOAL_IDX_STORAGE_KEY);
}//onActivityCreated
}//Cls

android, cant resolve getListAdapter and setOnItemLongClickListener inside fragment

In here I am trying to make OnItemLongClick, I tried doing it in ListActivity before and that's working.
Now I am trying to make one inside a Fragment, but I get an error here and there, I need some advice/suggestion/answer to solve the error, or the correct way to implement the method.
In the ListActivity (working):
public class ViewData extends ListActivity implements OnItemLongClickListener {
//init controller
private DBDataSource dataSource;
//init arraylist
private ArrayList<Barang> values;
private Button delButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewdata);
dataSource = new DBDataSource(this);
// open controller
dataSource.open();
// get values
values = dataSource.getAllBarang();
// insert data to array adapter
ArrayAdapter<Barang> adapter = new ArrayAdapter<Barang>(this,
android.R.layout.simple_list_item_1, values);
// set adapter in list
setListAdapter(adapter);
// listview for set onItemLongClickListener
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemLongClickListener(this);
}
//if user longclick
#Override
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
//tampilkan alert dialog
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_view);
dialog.setTitle("Pilih Aksi");
dialog.show();
final Barang b = (Barang) getListAdapter().getItem(pos);
delButton = (Button) dialog.findViewById(R.id.button_delete_data);
//apabila tombol delete di klik
delButton.setOnClickListener(
new OnClickListener()
{
#Override
public void onClick(View v) {
// Delete barang
dataSource.deleteBarang(b.getId());
dialog.dismiss();
finish();
startActivity(getIntent());
}
}
);
return true;
}
}
The Fragment version (still giving an error) :
public class Menu_Riwayat extends Fragment {
//init controller
private DBDataSource dataSource;
//init arraylist
private ArrayList<Investasi_DB> values;
static ListView lv;
private Button button_hapus;
static LinearLayout mLinear;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
mLinear = (LinearLayout) inflater.inflate(R.layout.viewdata, container, false);
lv = (ListView) mLinear.findViewById(R.id.list);
dataSource = new DBDataSource(getActivity());
// open controller
dataSource.open();
// get values
values = dataSource.getAllInvestasi_DB();
// insert data to array adapter
ArrayAdapter<Investasi_DB> adapter = new ArrayAdapter<Investasi_DB>(getActivity(),
android.R.layout.simple_list_item_1, values);
// set adapter in list
lv.setAdapter(adapter);
return mLinear;
// ERROR IN THIS PART BELOW, not sure what to change "this" with
lv.setOnItemClickListener(this);
}
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
//tampilkan alert dialog
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_view);
dialog.setTitle("Pilihan");
dialog.show();
// ERROR IN THIS PART BELOW, not sure how to implement "getListAdapter()" inside fragment
final Investasi_DB b = (Investasi_DB) getListAdapter().getItem(pos);
button_hapus = (Button) dialog.findViewById(R.id.button_hapus);
button_hapus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataSource.deleteInvestasi_DB(b.getId());
dialog.dismiss();
getActivity().finish();
// ERROR IN THIS PART BELOW, the "getIntent()" part
startActivity(getIntent());
}
});
return true;
}
}
I need help to solve the error (correct way to implement it):
getListAdapter(), getIntent(), and this in lv.setOnItemClickListener(this);
EDITED PART AFTER SOME SUGGESTION :
so now i make it like this
public class Menu_Riwayat extends Fragment {
//inisialisasi kontroller
private DBDataSource dataSource;
//inisialisasi arraylist
private ArrayList<Investasi_DB> values;
static ListView lv;
private Button button_hapus;
static LinearLayout mLinear;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
mLinear = (LinearLayout) inflater.inflate(R.layout.viewdata, container, false);
lv = (ListView) mLinear.findViewById(R.id.list);
dataSource = new DBDataSource(getActivity());
// buka kontroller
dataSource.open();
// ambil semua data barang
values = dataSource.getAllInvestasi_DB();
// masukkan data barang ke array adapter
ArrayAdapter<Investasi_DB> adapter = new ArrayAdapter<Investasi_DB>(getActivity(),
android.R.layout.simple_list_item_1, values);
// set adapter pada list
lv.setAdapter(adapter);
//lv.setOnItemLongClickListener(this);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_view);
dialog.setTitle("Pilihan");
dialog.show();
final Investasi_DB b = (Investasi_DB) lv.getItemAtPosition(position);
button_hapus = (Button) dialog.findViewById(R.id.button_hapus);
button_hapus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataSource.deleteInvestasi_DB(b.getId());
dialog.dismiss();
getActivity().finish();
}
});
}
});
return mLinear;
}
its working, but the apps close itself after i click the button (i think because of getActivity().finish();), any idea about that ?
I need help to solve the error (correct way to implement it):
getListAdapter(), getIntent(), and this in
lv.setOnItemClickListener(this);
if with this you want to access a Context, you can use getActivity(). Fragment is not a Context
In setOnItemClickListener(this);, this refers to the current instance. With that line you are implying that this is also implementing the OnItemClickListener interface. Which is not true. You need yo add implement OnItemClickListener to your Fragment class.
getListAdapter():
instead of getListAdapter() you can use the ListView to retrieve the item at position, since you are already keeping a reference as member. Change
final Investasi_DB b = (Investasi_DB) getListAdapter().getItem(pos);
with
final Investasi_DB b = (Investasi_DB) lv.getItemAtPosition(pos);
why do you need this line startActivity(getIntent());?

Using a spinner to open up a new activity and displaying downloaded html data

String[] songList = {
"1",
"2",
"3",
};
Spinner sp;
TextView selection;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection = (TextView) findViewById(R.id.selection);
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter<Object> aa = new ArrayAdapter<Object>(
this,
android.R.layout.simple_spinner_item,
songList);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
selection.setText(songList[position]);
String song = songList[position];
Intent intent = new Intent(this, Tabview.class);
Bundle b = new Bundle();
b.putString("song", song);
intent.putExtras(b);
startActivityForResult(intent, 0);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
{
I have this code written right now. Pretty much what I'm trying to do is use the spinner selection to open a new activity (which I have done) BUT, I am also trying to use httpget to download information based on a link.
So, for ex:
If I press "1", it will open up a new activity, then it will call an httpget method, then it will download the data based on what you pressed. and that data will change for each option you press (EX. "1"= google.com, "2"=facebook.com, etc.) and then that data will be displayed in the activity.
I also want to only use ONE activity to display the data for each selection.
Also in my "Tabview.class" I have:
Bundle b = new Bundle();
String song = b.getString("song");
Thanks for any help!
What exactly is the error you get? The code seems to work. If you wanted to choose something according to the selection, you can use a simple if condition on the bundled string. Or if the issue here is about http get, take a look at the documentation here. You can use an AyncTask to make an http request without blocking.
For a reference, I have attached my code which just an improved version of your code.
public class ActivityxActivity extends Activity {
String[] songList = {"ONE","TWO","THREE"};
Intent intent1;
Bundle strs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Spinner sp = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<Object> aa = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, songList);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(aa);
sp.setOnItemSelectedListener(new MyOnItemSelectedListener());
intent1 = new Intent(getApplicationContext(),AnotherActivity.class);
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
strs = new Bundle();
strs.putInt("item", pos);
strs.putString("song", parent.getItemAtPosition(pos).toString());
intent1.putExtras(strs);
startActivity(intent1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
}
}
And in the other activity,
public class AnotherActivity extends Activity {
Bundle data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
data = getIntent().getExtras();
Integer item = data.getInt("item");
//Use a switch(item) here to switch to different links based on selection
TextView tv = (TextView) findViewById(R.id.tv1);
tv.setText("Another Activity, Item is :" + item.toString());
}
}
Make sure you add your activity in the Android Manifest file.
Thanks

Categories

Resources