Android Spinner value does not change in new Activity - java

I use a spinner in my App to open the same Activity but with different values to download Json files and show them. The first problem was, that the spinner don´t work, when i don´t add a spinner value at the 0 position and query it with if-statement (if(position >0)) in the onItemSelected method before open a new activity. Its a solution but not a very good.
The next problem is, that the value of the spinner shows every time the 0 position of the spinner list. Its same when i make a Array to fill the spinner or different Strings. Open the same Activity with different json files works fine but the spinner is all the time on position 0 value.
public class FragmentResult extends Fragment implements
GestureOverlayView.OnGesturePerformedListener, AdapterView.OnItemSelectedListener {
private ArrayList<ResultModel> arrayListResult = new ArrayList<>();
public static int dayOfMatch = 34;
private GestureLibrary gestureLibrary;
Spinner spinnerDay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//matchDayCheck();
ServerResult serverResult = new ServerResult(getActivity().getApplicationContext(),
"https://www.dein-weg-in-die-cloud.de/tomcat7/RestSoccer/fussball/spieltag/" + dayOfMatch);
serverResult.execute();
String downResult = null;
try {
downResult = serverResult.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
JsonParser jsonParser = new JsonParser();
arrayListResult = jsonParser.parseJSONResult(downResult);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
GestureOverlayView gestureOverlayView = new GestureOverlayView(getActivity());
View view = inflater.inflate(R.layout.layout_result, container, false);
ListView result_list = (ListView)view.findViewById(R.id.result_list);
AdapterResult adapterResult = new AdapterResult(getActivity().getApplicationContext(), arrayListResult);
result_list.setAdapter(adapterResult);
gestureOverlayView.addView(view);
gestureOverlayView.setFadeEnabled(false);
gestureOverlayView.addOnGesturePerformedListener(this);
gestureOverlayView.setGestureColor(Color.TRANSPARENT);
gestureOverlayView.setUncertainGestureColor(Color.TRANSPARENT);
gestureOverlayView.setFadeOffset(0);
gestureOverlayView.setHapticFeedbackEnabled(true);
gestureLibrary = GestureLibraries.fromRawResource(getActivity().getApplicationContext(), R.raw.gestures); //!!
if (!gestureLibrary.load()) {
getActivity().finish();
}
// Spinner element
Spinner spinnerYear = (Spinner)view.findViewById(R.id.spinnerResultYear);
spinnerDay = (Spinner)view.findViewById(R.id.spinnerResultDay);
// Spinner click listener
spinnerYear.setOnItemSelectedListener(this);
spinnerDay.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> spinnerListYear = new ArrayList<String>();
spinnerListYear.add("2013/2014");
List<String> spinnerListDay = new ArrayList<String>();
spinnerListDay.add("");
for(int i = 1; i<=34; i++){
spinnerListDay.add(i + ".Spieltag");
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerYearAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, spinnerListYear);
ArrayAdapter<String> spinnerDayAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, spinnerListDay);
// Drop down layout style - list view with radio button
spinnerYearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerYear.setAdapter(spinnerYearAdapter);
spinnerDay.setAdapter(spinnerDayAdapter);
/*result_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ResultModel resultModel = (ResultModel) parent.getItemAtPosition(position);
int matchId = resultModel.getMatchId();
Intent matchIntent = new Intent(getActivity(), MatchActivity.class);
matchIntent.putExtra("MatchId", matchId);
matchIntent.putExtra("Matchday", dayOfMatch);
startActivity(matchIntent);
}
});*/
return gestureOverlayView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
if(position >0) {
final Intent intent;
intent = new Intent(getActivity().getApplicationContext(), ResultActivity.class);
dayOfMatch = position;
intent.putExtra("dayOfMatch", dayOfMatch);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
.
.
.
}

Related

How to get the child nodes from the data I inserted into Listview?

I've created a Listview and inserted data from my SQLite databse into it. The OnItemClick on the Listview opens up another fragment, but I can only access the name displayed on the listItem. How do I get the rest of the data?
Using getItemAtPosition(position).toString(); works for the item clicked, but not for the rest of the data. getChildAt(position).toString(); doesn't work either. I've also tried with a StringBuffer, but couldn't make it work (I might not have done it right). Can anyone help me here?
public class FoodFragment extends Fragment {
ImageButton addFood;
ListView listView;
FoodDatabaseHelper mFoodDatabaseHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container, false);
addFood = view.findViewById(R.id.addFood);
listView = view.findViewById(R.id.caloriesEaten);
mFoodDatabaseHelper = new FoodDatabaseHelper(getActivity());
populateListview();
return view;
}
private void populateListview(){
//populate an ArrayList<String> from the database and then view it
ArrayList<String> list = new ArrayList<>();
Cursor data = mFoodDatabaseHelper.getData();
if(data.getCount() == 0){
Toast.makeText(getActivity(), "There are no contents in this list!",Toast.LENGTH_LONG).show();
}else{
while(data.moveToNext()){
list.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,list);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get data from Listview
String food = parent.getItemAtPosition(position).toString();
String protein = listView.getChildAt(position).toString();
String fats = listView.getChildAt(position).toString();
String carbo = listView.getChildAt(position).toString();
Cursor data = mFoodDatabaseHelper.getFood(food);
int itemID = -1;
while (data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
FoodDetailFragment frt = new FoodDetailFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//Send the relevant data to the FoodDetailFragment
Bundle bundle = new Bundle();
bundle.putString("foods", food);
bundle.putString("protein", protein);
bundle.putString("fats", fats);
bundle.putString("carbo", carbo);
frt.setArguments(bundle);
transaction.replace(R.id.fragment_container, frt);
transaction.addToBackStack(null).commit();
}else{
Toast.makeText(getActivity(), "No such ID ", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
}
The next fragment should show the name of the food and the macros, for example:
Bacon
1
0
18
Instead it displays:
Bacon
android.support.v7.widget.AppcompatTextView{82d2539V.ED..... ..... 0
0-974,123£1020014android:id/text1}
android.support.v7.widget.AppcompatTextView{82d2539V.ED..... ..... 0
0-974,123£1020014android:id/text1}
android.support.v7.widget.AppcompatTextView{82d2539V.ED..... ..... 0
0-974,123£1020014android:id/text1}
I can't figure out how to point at the value. Any help would be greatly appreaciated.
EDIT: I have now changed the code trying to follow the link provided. This had lead me to be able to get the childnodes. I ended up with this. It's not pretty, but it works.
public class FoodFragment extends Fragment {
String food, proteins, fats, carbohydrates;
ImageButton addFood;
FoodDatabaseHelper foodDatabaseHelper;
ListView listView;
SQLiteDatabase sqLiteDatabase;
ArrayList<HashMap<String, String>> foodlist;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container, false);
addFood = view.findViewById(R.id.addFood);
listView = view.findViewById(R.id.caloriesEaten);
foodDatabaseHelper = new FoodDatabaseHelper(getActivity());
sqLiteDatabase = foodDatabaseHelper.getWritableDatabase();
addFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TrackingFragment frt = new TrackingFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, frt);
transaction.addToBackStack(null).commit();
}
});
foodlist = new ArrayList<>();
populateListview();
return view;
}
private void populateListview() {
Cursor cursor = foodDatabaseHelper.getData();
foodlist.clear();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
food = cursor.getString(1);
proteins = cursor.getString(2);
fats = cursor.getString(3);
carbohydrates = cursor.getString(4);
HashMap<String, String> foods = new HashMap<>();
foods.put("foods", food);
foods.put("proteins", proteins);
foods.put("fats", fats);
foods.put("carbohydrates", carbohydrates);
foodlist.add(foods);
cursor.moveToNext();
}
ListAdapter adapter = new SimpleAdapter(getActivity(), foodlist, R.layout.fragment_food_items, new String[]{"foods", "proteins", "fats", "carbohydrates"}, new int[]{R.id.food, R.id.proteins, R.id.fats, R.id.carbs});
listView.setAdapter(adapter);
}
}
There are some major problems with your code :
Don't initialise listview adapter and onItemClickListener() inside a while loop. These should be outside the loop.
If you want to fetch all the data at a position when you click on a listitem, then you should create a class and store objects of that class in your List instead of just a string.
This link has some code that will help you to correct yours https://www.dev2qa.com/how-to-show-data-from-sqlite-database-in-android-listview/

How update ListView from my Custom Adapter

I just wanna update my ListView, but I cant. I dont know what. What did I do Wrong? I guess that the Adapter that I created is missing something to return the real adapter that I can handle.
Home.java (MainActivity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
MenuItem item = navigation.getMenu().findItem(R.id.navigation_home);
item.setCheckable(true);
item.setChecked(true);
BoxStore boxStore = AppMain.getBoxStore();
equipamentoBox = boxStore.boxFor(Equipamento.class);
lancamentoBox = boxStore.boxFor(Lancamento.class);
loadObjects();
////FOCUS HERE/////------------------------------
List<Equipamento> equipamentos = new ArrayList<>();
EquipamentoAdapter adapter;adapter = new EquipamentoAdapter(this, equipamentos);
listEquipamentos = (ListView) findViewById(R.id.listEquipamentos);
listEquipamentos.setAdapter(adapter);
registerForContextMenu(listEquipamentos);
}
EquipamentoAdapter.JAVA
public class EquipamentoAdapter extends ArrayAdapter<Equipamento> {
private final Activity context;
private final List<String> idArray = new ArrayList<String>();
private final List<String> qtdArray = new ArrayList<String>();
private final ArrayList<String> nomeArray = new ArrayList<String>();
private List<Equipamento> equipamentos = new ArrayList<>();
public EquipamentoAdapter(Activity context, List<Equipamento> equipamentos) {
super(context, R.layout.listview_row, equipamentos);
for (Iterator iterator = equipamentos.iterator(); iterator.hasNext(); ) {
Equipamento equipamento = (Equipamento) iterator.next();
this.idArray.add(Integer.toString((int)equipamento.getId()));
this.qtdArray.add(Integer.toString(equipamento.getQuantidade()));
this.nomeArray.add(equipamento.getNome());
}
this.context = context;
this.equipamentos = equipamentos;
}
public void callDialogTransaction(Equipamento equipamento) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View mView = inflater.inflate(R.layout.dialog_lancamento,null);
TextView title = (TextView) mView.findViewById(R.id.txtTitle);
final EditText quantidade = (EditText) mView.findViewById(R.id.edtQtd);
final EditText Observacao = (EditText) mView.findViewById(R.id.edtObs);
Button addTransaction = (Button) mView.findViewById(R.id.btnAddTranD);
title.setText(equipamento.getNome());
addTransaction.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(!quantidade.getText().toString().isEmpty()){
Toast.makeText(getContext(), "Success!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Erro. Fill everything.", Toast.LENGTH_SHORT).show();
}
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listview_row,null,true);
//this code gets references to objects in the listview_row.xml file
TextView txtQtd,txtName;
txtQtd = (TextView) rowView.findViewById(R.id.txtQtd);
txtName = (TextView) rowView.findViewById(R.id.txtName);
final ImageButton btnAddTransaction = (ImageButton) rowView.findViewById(R.id.btnAddTransaction);
//this code sets the values of the objects to values from the arrays
txtQtd.setText(qtdArray.get(position));
txtName.setText(nomeArray.get(position));
btnAddTransaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Equipamento equipamento = equipamentos.get(position);
callDialogTransaction(equipamento);
Animation animation = new AlphaAnimation(1.0f,0.8f);
animation.setDuration(100);
btnAddTransaction.startAnimation(animation);
}
});
return rowView;
}
}
I read that I could try to use adapter.notifyDataSetChanged(); but its not working. Also I tryed to add this on EquipamentoAdapter.java and call from my MainActivity when I needed to refresh, but it didn work as well. I dont know why. Everything seems right.
public void refreshData(){
this.equipamentos.clear();
for(Equipamento equipamento : equipamentoBox.getAll()){
this.equipamentos.add(equipamento);
}
notifyDataSetChanged();
}
I'll suggest the following changes:
Reference the equipamento object directly from List inside the getView the so that the getView function becomes
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listview_row,null,true);
//this code gets references to objects in the listview_row.xml file
TextView txtQtd,txtName;
txtQtd = (TextView) rowView.findViewById(R.id.txtQtd);
txtName = (TextView) rowView.findViewById(R.id.txtName);
final ImageButton btnAddTransaction = (ImageButton) rowView.findViewById(R.id.btnAddTransaction);
//this code sets the values of the objects to values from the arrays
Equipamento equipamento = equipamentos.get(position);
txtQtd.setText(String.valueOf(equipamento.getId()));
txtName.setText(String.valueOf(equipamento.getQuantidade()));
btnAddTransaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Equipamento equipamento = equipamentos.get(position);
callDialogTransaction(equipamento);
Animation animation = new AlphaAnimation(1.0f,0.8f);
animation.setDuration(100);
btnAddTransaction.startAnimation(animation);
}
});
return rowView;
}
Set the Items count with the getCount method
public int getCount(){
return equipamentos.size();
}
with these, calling notifyDataSetChanged(); should update the list without need to reinitialize the adapter.
One thing that you can do is reinflaiting the adapter, try this
public void refreshData(){
this.equipamentos.clear();
for(Equipamento equipamento : equipamentoBox.getAll()){
this.equipamentos.add(equipamento);
}
EquipamentoAdapter adapter;adapter = new EquipamentoAdapter(this, equipamentos);
listEquipamentos.setAdapter(adapter);
}
GUYS, I've noticed that if I use:
equipamentos.clear(); //Clear List
for(Equipamento equipamento : equipamentoBox.getAll()){
equipamentos.add(equipamento); //Populate List
}
adapter = null;
adapter = new EquipamentoAdapter((Activity) Home.this, equipamentos);
listEquipamentos.setAdapter(adapter);
adapter.notifyDataSetChanged();
Its gonna work. But this seems VERY wrong in terms of performance. My application is small but I dont want to make bad practices.
Create a method to replace the data and check the size of your adapter after you add new elements.
Add something like this to the adapter:
public void replaceData(List<Equipamento> equipamentos) {
this.equipamentos = equipamentos;
notifyDataSetChanged();
}
#Override
public int getCount() {
return equipamentos.size();
}
Then check the size from the Activity:
adapter.getCount();
As your following logic is in constructor of adapter-
enter code here
for (Iterator iterator = equipamentos.iterator(); iterator.hasNext(); ) {
Equipamento equipamento = (Equipamento) iterator.next();
this.idArray.add(Integer.toString((int)equipamento.getId()));
this.qtdArray.add(Integer.toString(equipamento.getQuantidade()));
this.nomeArray.add(equipamento.getNome());
}
after notifyDataSetChange, adapter is not called so you can do 2 things -
1) Initialize the Adapter as #Gastón Saillén answered.
2) Put that in some method and call it before you call notifydatasetchange.

How do I stop SimpleDateFormat from updating the time

I saw that this was asked once at How to get current timestamp in Android without it updating like a clock, but it wasn't marked as answered and I don't understand the few suggestions that were given.
Anyway, I'm beyond new to Java and was following a tutorial on making a simple todo app (https://guides.codepath.com/android/Basic-Todo-App-Tutorial) and I decided to try to add a timestamp to each list item. I got as far as that it adds the current time, but its not static. The time keeps updating anytime I try and add a new item or if I close and reopen the app. I can't figure out/find the answer anywhere.
This is what I'm getting:
This is what I want:
Here's the code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> TodoAdapter;
private ListView lvItems;
private void readItems() {
File filesDir = getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new ArrayList<String>();
readItems();
TodoAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, android.R.id.text1, items);
lvItems = (ListView) findViewById(R.id.lvItems);
lvItems.setAdapter(TodoAdapter);
// Setup remove listener method call
setupListViewListener();
}
// Attaches a long click listener to the listview
// Removes item on long press
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
TodoAdapter.notifyDataSetChanged();
writeItems();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void onAddItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
TodoAdapter.add(itemText); // Add items to new Adapter type
etNewItem.setText("");
writeItems();
}
}
TodoAdapter.java
public class TodoAdapter extends ArrayAdapter<Todo> {
public TodoAdapter(Context context, ArrayList<Todo> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Todo item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
}
TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
text1.setText(item.itemText);
text2.setText(item.getCreationTimeString());
text2.setTextSize(10);
return convertView;
}
}
Todo.java
public class Todo {
String itemText;
private Date creationTime;
public Todo(String text) {
this.itemText = text;
this.creationTime = new Date();
}
public String getCreationTimeString() {
return new SimpleDateFormat("h:mm a").format(creationTime);
}
}
Any help provided would be extremely appreciated. Also please keep in mind that I have literally almost no understanding of what I'm doing. :)
The time keeps updating anytime I try and add a new item
Right, that is because the Adapter is recalling new Date(), which will always get the current time that the View is created for an Adapter item.
It would appear that you want items to be associated with a time at which they are created. If that is the case, then you can make a class
public class Todo {
String itemText;
private Date creationTime;
public Todo(String text) {
this.itemText = text;
this.creationTime = new Date();
}
public String getCreationTimeString() {
return new SimpleDateFormat("h:mm a").format(creationTime);
}
}
Then, you should probably make an ArrayAdapter<Todo> to display these items and display something like this
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Todo item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
}
TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
text1.setText(item.itemText);
text2.setText(item.getCreationTimeString());
text2.setTextSize(10);
return convertView;
}
And update the add method
public void onAddItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
itemsAdapter.add(new Todo(itemText)); // Add items to new Adapter type
etNewItem.setText("");
writeItems();
}

Parsing a ListView item onclick to another activity and match a specific data from JSON

Can anyone help me parse the ListView item on click to another activity preferably one that will get and match the parsed id with some JSON data. Am working on a volley library and will definitely want to get the related data of the specific item clicked.
// Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinkedList<String> mLinked = new LinkedList<String>();
for (int i = 0; i < DRUGS.length; i++) {
mLinked.add(DRUGS[i]);
}
setListAdapter(new MyListAdaptor(this, mLinked));
ListView lv = getListView();
lv.setFastScrollEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
// Start new intent by passing value
// End intent
}
});
}
I needed my value to be seen on another activity as
public class Activity2_view extends Activity {
// Collecting the values from MainActivity class
TextView tvView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
tvView = (TextView) findViewById(R.id.tvView);
Intent intent = getIntent();
String ItemName = intent.getStringExtra("jsonId");
tvView.setText("Your drug name is: " + ItemName);
}
}
In your adapter, in your getView() method, you can set a tag to match the id of the JSON data you need to link up with. For example:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int jsonId; // Set the view's tag to the ID of the JSON data
// you want to link it to.
convertView.setTag(jsonId);
}
Then, in your OnItemClickListener:
ListView lv = getListView();
lv.setFastScrollEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
// Get the id from the view.
int jsonId = (int) view.getTag();
// Start new intent by passing value
Intent newActivityIntent = new Intent(YourActivity.this, YourNewActivity.class);
newActivityIntent.putExtra("jsonId", jsonId);
// Start it.
startActivity(newActivityIntent);
}
});
If you're using a ViewHolder in your getView() method for optimization purposes, the ViewHolder will be the tag of your view. You will need to add a member property to the ViewHolder object that you can save the id with.
public class ViewHolder {
private int mJsonId;
private TextView mTextView;
public void setId(int id) {
mJsonId = id;
}
public int getJsonId() {
return mJsonId;
}
}
then
ViewHolder viewHolder = (ViewHolder) view.getTag();
int jsonId = viewHolder.getJsonId();
Hope this helps.
from what i understand of your code...
String stringId = mLinked.get(position);
Intent mIntent = new Intent(this,Activity2.class);
mIntent.putExtra(KEY,stringId)
startActivity(mIntent);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
// Start a new intent - get the id from the view and send to another activity for JSON
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), DrugIndexing_view.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
// End intent
}
});

How to swap spinner value while clicking image

Im very new for android, I want swap spinner value when user click the image. Please anyone help me.
Here my code:
public class SearchFragment extends Fragment {
ImageView swap;
Spinner source, destination;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.search, container,
false);
swap = (ImageView)getActivity().findViewById(R.id.imgSwap);
source = (Spinner)getActivity().findViewById(R.id.from);
destination = (Spinner)getActivity().findViewById(R.id.to);
swap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
-----> \\Here want to code
}
});
return view;
}
}
If you want to swap the contents of two Spinners you can use this
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
list1.add("A");
list1.add("B");
list1.add("C");
list2.add("1");
list2.add("2");
list2.add("3");
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list1);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list2);
spinner1.setAdapter(adapter1);
spinner2.setAdapter(adapter2);
yourImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayAdapter<String> a1 = (ArrayAdapter) spinner1.getAdapter();
ArrayAdapter<String> a2 = (ArrayAdapter) spinner2.getAdapter();
spinner1.setAdapter(a2);
spinner2.setAdapter(a1);
}
});
Or if you just want to swap the selected values across the spinner you can use this in your button click
yourImagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position1 = spinner1.getSelectedItemPosition();
int position2 = spinner2.getSelectedItemPosition();
String item1 = list1.get(position1);
String item2 = list2.get(position2);
list1.remove(position1);
list1.add(position1, item2);
list2.remove(position2);
list2.add(position2, item1);
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
});

Categories

Resources