How to make Clickable ListView - android

I have a problem with the ListView ... I would like the application to go in a second activity at the click of every element contained within it. In the second activity there will be the update and delete functions. The elements present in the ListView are contained in a mysql database and recovered with json ... Can you help me understand how to program the click of the ListView elements?
public class LoggedActivity extends AppCompatActivity {
private RequestQueue mQueue;
private ListView list_view;
Button buttonParse;
Button aggingi_prodotto;
private ArrayList<String> lista;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged);
list_view = findViewById(R.id.list_view);
lista = new ArrayList<>();
buttonParse = findViewById(R.id.button_parse);
aggingi_prodotto = findViewById(R.id.aggiungi_prodotto);
//--------------------------
Bundle extras = getIntent().getExtras();
final String id_utente = extras.getString("id");
//--------------------------
mQueue = Volley.newRequestQueue(this);
aggingi_prodotto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),AggiungiActivity.class);
intent.putExtra("id",id_utente);
startActivity(intent);
}
});
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse(id_utente);
}
});
}
private void jsonParse(final String id_utente) {
String url = "http://192.168.1.5/progettoPHP/WebServices/webSrv.php?type=recuperaProdotti&idutente=" + id_utente;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
String id = dato.getString("id");
final String id_utente = dato.getString("id_utente");
String nome_prodotto = dato.getString("nome_prodotto");
//lista.add(id_utente + " - " + id + " - " + nome_prodotto + "\n\n");
lista.add(nome_prodotto);
}
adapter = new ArrayAdapter<String>(LoggedActivity.this, android.R.layout.simple_list_item_1, lista);
list_view.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mQueue.add(request);
}
}

If you want List Click you can simply use
list_view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// do whatever you want to click of the listview item
}
});
Instead of Listview, you can use ResyclerView
If you want to click on the specific item in the list and get the position of item you can make Listner in Adapter
In Adapter
Initialized
private OnItemClick onItemClick;
ClickListner
ItemView.setOnClickListener(v -> {
if (onItemClick != null) {
onItemClick.onItem(i);
}
});
Functions
public interface OnItemClick {
void onItem(int position);
}
public void setOnItem(OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
In MainActivity
adapter.setOnItem(new Adapter.OnItemClick() {
#Override
public void onItem(int i) {
}
});

Try like this
list_view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// do whatever you want to click of the listview item
}
});

Related

Listview custom filter gives wrong item on-clicked in filtered list

When I filter my list and click on an item in listview it gives the wrong item information.
Suppose my list contains X, Y, Z. And when I search the list for things starting with Y, I will get Y, but when I click Y, it returns me X or any random item data.
My main activity:
public class exit_Activity extends AppCompatActivity {
String Show_url = "https://retrieve.php";
ListView removeView;
MyAdapter adapter;
public static ArrayList<Employee> employeeArrayList = new ArrayList<>();
Employee employee;
ProgressBar progressBar;
private SwipeRefreshLayout mSwipeRefreshLayout;
public static ArrayList<Employee> filterList = new ArrayList<>();
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exit_);
retrieveData();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
///
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshlayout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.black, R.color.green, R.color.red);
mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.main_blue));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(true);
Toast.makeText(getApplicationContext(), "Updating..", Toast.LENGTH_SHORT).show();
retrieveData();
// do nothing
}
});
progressBar = (ProgressBar) findViewById(R.id.progressbar);
Sprite FoldingCube = new Wave();
progressBar.setIndeterminateDrawable(FoldingCube);
//time and date
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
exit_time();
removeView.requestLayout();
handler.postDelayed(this, 500);
}
}, 500);
//
//
//exit
removeView = findViewById(R.id.exit_entry);
adapter = new MyAdapter(this, employeeArrayList);
removeView.setAdapter(adapter);
//end
removeView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ProgressDialog progressDialog = new ProgressDialog(view.getContext());
startActivity(new Intent(getApplicationContext(), Edit_Activity.class)
.putExtra("id", id));
finish();
}
});
//searchView
search = findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filterList.clear();
if (s.toString().isEmpty()) {
removeView.setAdapter(new MyAdapter(getApplicationContext(), employeeArrayList));
adapter.notifyDataSetChanged();
} else {
Filter(s.toString());
}
}
});
//end
}
public void retrieveData() {
StringRequest request = new StringRequest(Request.Method.POST, Show_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
employeeArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
String sucess = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("veeta_vehicles");
if (sucess.equals("1")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String number = object.getString("number");
String name = object.getString("name");
String time = object.getString("surnam");
String date = object.getString("dob");
String time = object.getString("die");
String yes = object.getString("yes");
employee = new Employee(id, number, name, time, date, time, yes);
employeeArrayList.add(employee);
adapter.notifyDataSetChanged();
}
progressBar.setVisibility(View.GONE);
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(getApplicationContext(), "List Updated", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(exit_Activity.this, error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void Filter(String text) {
for (Employee post : employeeArrayList) {
String filterPattern = text.toLowerCase().trim();
if (post.getnumber().toLowerCase().contains(filterPattern)) {
filterList.add(post);
}
}
removeView.setAdapter(new MyAdapter(getApplicationContext(), filterList));
adapter.notifyDataSetChanged();
}
MyAdapter.class:
public class MyAdapter extends ArrayAdapter<Employee> implements Filterable{
Context context;
List<Employee> arrayListEmployee;
public MyAdapter(#NonNull Context context, List<Employee> arrayListEmployee) {
super(context, R.layout.custom_list_item,arrayListEmployee);
this.context = context;
this.arrayListEmployee = arrayListEmployee;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_list_item,null,true);
TextView tvID = view.findViewById(R.id.txt_id);
TextView tvName = view.findViewById(R.id.view_vehicle_number);
tvID.setText(arrayListEmployee.get(position).getId());
tvName.setText(arrayListEmployee.get(position).getnumber());
return view;
}
#Override
public int getCount() {
return super.getCount();
}
Pls explain in easy language and provide my solution. I'm new to android studio. thank you x1000 in Advance
I found problem in method (check comments):
private void Filter(String text) {
for (Employee post : employeeArrayList) {
String filterPattern = text.toLowerCase().trim();
if (post.getnumber().toLowerCase().contains(filterPattern)) {
filterList.add(post);
}
}
//below every time you create new instance of MyAdapter - try comment this line (below) and test it
removeView.setAdapter(new MyAdapter(getApplicationContext(), filterList));
//this is your first instance but you set new adapter for listView
adapter.notifyDataSetChanged();
}
and replace your method with this:
private void Filter(String text) {
for (Employee post : employeeArrayList) {
String filterPattern = text.toLowerCase().trim();
if (post.getnumber().toLowerCase().contains(filterPattern)) {
filterList.add(post);
}
}
adapter.clear()
adapter.addAll(filterList);
}
So you don't create a new instance of the adapter every time, just swap data of the existing adapter
I haven't tested it but it should work fine with OnItemClickListener...
EDITED
Also same problem...
#Override
public void afterTextChanged(Editable s) {
filterList.clear();
if (s.toString().isEmpty()) {
//you set new instance of adapter and notify old, try comment this line (below) and test it
//removeView.setAdapter(new MyAdapter(getApplicationContext(), employeeArrayList));
adapter.notifyDataSetChanged();
} else {
Filter(s.toString());
}
}
Change to this
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()) {
filterList.clear(); //TODO here is problem, move this to your filter method
Filter(s.toString());
} else {
//Do nothing, if the EditText field is empty the list will remain filled
}
}
There are other ways to solve this and improve but I don't want to confuse you, because android is new experience for you
EDITED
You are using an ArrayAdapter but I thought it is RecyclerView, forget swapData method and try new changes... Sorry
adapter.clear()
adapter.addAll(filterList);

Issue with RecyclerView item selection

I am designing a live quiz app that fetches data from server and question are displayed in a RecyclerView that contains a question and four options. Now when I select one option for a given question, it is selected properly but at the same time, the corresponding option for other question is selected automatically.
Screenshot of the item selection issue is the following.
I have designed Data Model Class and RecylerView Adapter (with the help of #Reaz Murshed) but have been stuck with the code
My Data Model Class is :
//DmLiveQuiz
public class DmLiveQuiz {
String testId;
int questionId;
String question;
String optA;
String optB;
String optC;
String optD;
String answer;
String explain;
...
}
My Adapter Class is //LiveTestAdapter
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder> {
private List<DmLiveQuiz> questionList;
private int[] answerList; // Get a list of your answers here.
private DmLiveQuiz questionsList;
private Context context;
public List<Integer> myResponse = new ArrayList<Integer>();
public int qno;
public LiveTestAdapter(List<DmLiveQuiz> questionList, Context context) {
this.questionList = questionList;
this.context = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.live_quiz_display_format, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
questionsList = questionList.get(holder.getAdapterPosition());
holder.tvQNo.setText(questionsList.getQuestionId() + "");
holder.tvquestion.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
holder.tvquestion.setText(questionsList.getQuestion());
holder.optA.setText(questionsList.getOptA());
holder.optB.setText(questionsList.getOptB());
holder.optC.setText(questionsList.getOptC());
holder.optD.setText(questionsList.getOptD());
// Now you need to modify the backgrounds of your option buttons like the following.
if (answerList[position] == 1) holder.optA.setBackgroundResource(R.drawable.button_border);
else holder.optA.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 2) holder.optB.setBackgroundResource(R.drawable.button_border);
else holder.optB.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 3) holder.optC.setBackgroundResource(R.drawable.button_border);
else holder.optC.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 4) holder.optD.setBackgroundResource(R.drawable.button_border);
else holder.optD.setBackgroundResource(R.drawable.button_question_style);
holder.optA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_border);
answerList[position] = 1; // Selected first option which is A
});
holder.optB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optB.setBackgroundResource(R.drawable.button_border);
answerList[position] = 2; // Selected second option which is B
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optC.setBackgroundResource(R.drawable.button_border);
answerList[position] = 3; // Selected third option which is C
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optD.setBackgroundResource(R.drawable.button_border);
answerList[position] = 4; // Selected fourth option which is D
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.tvClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
answerList[position] = 0; // Clear the value in the answerList
}
});
}
// Use this function to set the question list in the adapter
public void setQuestionList(List<DmLiveQuiz> questionList) {
this.questionList = questionList;
this.answerList = new int[questionList.size()]; // This initializes the answer list having the same size as the question list
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return questionList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
TextView tvquestion, tvClear, tvQNo;
Button optA, optB, optC, optD;
public CustomViewHolder(View itemView) {
super(itemView);
tvQNo = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestionNo);
tvquestion = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestion);
optA = (Button) itemView.findViewById(R.id.buttonOptionA);
...///
}
}
}
And The Activity where Recyclerview is implemented is
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewLiveTest);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
quizList = new ArrayList<>();
adapter = new LiveTestAdapter(quizList, getApplicationContext());
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
getData();
......
The method for fetching JSON data is getdata() as given below which fetches data from server correctly...
private void getData() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(quiz_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
DmLiveQuiz liveQuiz = new DmLiveQuiz();
...
...
quizList.add(liveQuiz);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
..........
}
Now When I run App, it shows index=0 i.e. ArrayOutOfIndexException is generated.. I am not able to call public void setQuestionList(List<DmLiveQuiz> questionList) method of LiveQuizAdapter class from my activity.. Please Help
Initially you are setting empty list in the adapter. After getting value from JsonArrayRequest then need to update adapter using new list.
Update onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
DmLiveQuiz dmLiveQuiz= questionList.get(position);
if(dmLiveQuiz!=null){
// do whatever you want. put all code here.}
}
Update your adapter:
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
// put all code here
quizList.add(liveQuiz);}
adapter.setQuestionList(quizList);
adapter.notifyDataSetChanged();
}
you have to add a boolean value in DmLiveQuiz model class :-
boolean isSelected ;
and then set a check in your adapter while your are showing the answer is selected or not :-
if(DmLiveQuiz.isSelectd){
// this is the selected answer
}else {
// in case don't selected
}
and change the boolean value on adapter item Click

how to use both Swipe List Adapter and Scroll List Adapter at the listview

I'm developing an android application that have the Swipe List function found Here and now i have add a fast scroll function to the list view that found here
Here is my code :
public class HomeList extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
private String TAG = HomeList.class.getSimpleName();
private String URL_TOP_250 = "http://api.androidhive.info/json/imdb_top_250.php?offset=";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Movie> movieList;
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.activity_home_list,
container, false);
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setFastScrollEnabled(true);
swipeRefreshLayout = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create As animation won't
* start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getActivity(), AddMain.class);
startActivity(i);
}
});
FrameLayout footerLayout = (FrameLayout) getActivity()
.getLayoutInflater().inflate(R.layout.footerview, null);
Button btnPostYourEnquiry = (Button) footerLayout
.findViewById(R.id.btnGetMoreResults);
btnPostYourEnquiry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), AddMain.class);
startActivity(i);
}
});
listView.addFooterView(footerLayout);
return rootView;
}
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
fetchMovies();
}
/**
* Fetching movies json by making http call
*/
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response
.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG,
"JSON Parsing error: "
+ e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity(), error.getMessage(),
Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
class MyListAdaptor extends ArrayAdapter<String> implements SectionIndexer {
HashMap<String, Integer> alphaIndexer;
String[] sections;
public MyListAdaptor(Context context, LinkedList<String> items) {
super(context, R.layout.scrol, items);
alphaIndexer = new HashMap<String, Integer>();
int size = items.size();
for (int x = 0; x < size; x++) {
String s = items.get(x);
// get the first letter of the store
String ch = s.substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted
// after upper A-Z
ch = ch.toUpperCase();
if (!alphaIndexer.containsKey(ch))
alphaIndexer.put(ch, x);
}
Set<String> sectionLetters = alphaIndexer.keySet();
// create a list from the set to sort
ArrayList<String> sectionList = new ArrayList<String>(
sectionLetters);
Collections.sort(sectionList);
sections = new String[sectionList.size()];
sectionList.toArray(sections);
}
public int getPositionForSection(int section) {
return alphaIndexer.get(sections[section]);
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
return sections;
}
}
}
I doesn't know how to combine both adapter, can someone help me?

EditText values in a RecyclerView gives same value after 5th position

I have a RecyclerView and each row has a EditText also. I am adding item to RecyclerView by searching them and then I type the quantity in the edit text. Then I send it to the server to store using json format. Item add is working perfectly. There is no edit text value swapping problem also when scrolling. I can display 5 rows in the screen.
Problem is when I send item to the server, edit text values in bottom rows get the same after 5th row.
These are the rows I am adding to the recyclerview.Printed List that send to the server.
Item : 7.50-15 10PR FM CEAT Quantity : 1
Item : 5.60-15 04PR K 511 CEAT Quantity : 2
Item : 2.75-18 04PR SECURA F85 CEAT (F) Quantity : 3
Item : 3.00-17 06PR SECURA ZOOM CEAT (R) Quantity : 4
Item : 6.50-14 10PR FM CEAT Quantity : 5
Item : 5.00-12 04PR GRIP MASTER CEAT Quantity : 5
Item : 4.00-08 06PR AUTO RAJA RPG Quantity : 5
Item : 9.00-20 14PR CEAT CLT LUG Quantity : 5
Item : 8.25-20 14PR TR PLUS SUNTRAC Quantity : 5
Item : 7.00-15 12PR FM CEAT Quantity : 5
After the 5th position Quantity is the same. My input value is not coming.
This is my SelectItem class -
public class SelectItem extends AppCompatActivity implements SelectItemAdapter.OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_item);
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
myRecyclerView = (RecyclerView) findViewById(R.id.selectedItemRecyclerView);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
spinner = (Spinner) findViewById(R.id.selectDistribChannel);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, YourDealerListFragment.disChannel);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
selectedDisChannel = spinner.getSelectedItem().toString();
sqLiteHandler = new SQLiteHandler(getApplicationContext());
myRecyclerViewAdapter = new SelectItemAdapter(this);
myRecyclerViewAdapter.setOnItemClickListener(this);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
myRecyclerViewAdapter.notifyDataSetChanged();
dealerName = DealerListAdapter.getDealerName();
dealerID = DealerListAdapter.getDealerID();
repID = DealerListAdapter.getRepID();
//order number
orderId = "70000001";
if (newOrderId == null) {
newOrderId = orderId;
}
bAdd = (Button) findViewById(R.id.bAdd);
bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (myRecyclerViewAdapter.getItemCount() != 0) {
new AlertDialog.Builder(SelectItem.this)
.setTitle("Confirmation")
.setMessage("Do you want to send?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
checkOrderNo();
}
})
.setNegativeButton(android.R.string.no, null).show();
} else {
Toast.makeText(getApplicationContext(), "Empty List", Toast.LENGTH_SHORT).show();
}
}
});
//textView.setText(dealerName);
getSupportActionBar().setTitle(dealerName);
final AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
adapter = new MaterialSuggestionAdapter(getApplicationContext());
acTextView.setAdapter(adapter);
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product result = adapter.getItem(position);
String newName = result.getMatName().toString();
String newQty = String.valueOf(result.getMatQuantity());
String newPCode = result.getMatNo().toString();
String newPlant = result.getMatPlant().toString();
if (!newName.equals("")) {
if (myRecyclerViewAdapter.getItemCount() > 0) {
if (!isPresent(newPlant, newPCode, myRecyclerViewAdapter)) {
myRecyclerViewAdapter.add(1, newName, newQty, newPCode, newPlant);
} else {
Toast.makeText(getApplicationContext(), "Product Already in the List", Toast.LENGTH_SHORT).show();
}
} else {
myRecyclerViewAdapter.add(0, newName, newQty, newPCode, newPlant);
}
} else {
Toast.makeText(getApplicationContext(), "Invalied Item!", Toast.LENGTH_SHORT).show();
}
acTextView.setText("");
}
});
}
private boolean isPresent(String newPlant, String newPCode, SelectItemAdapter myRecyclerViewAdapter) {
boolean isPresent = false;
for (int i = 0; i < myRecyclerViewAdapter.getItemCount(); i++) {
if (newPCode.equalsIgnoreCase(myRecyclerViewAdapter.getItemPCode(i).toString()) && newPlant.equalsIgnoreCase(myRecyclerViewAdapter.getItemPlant(i).toString())) {
isPresent = true;
break;
}
}
return isPresent;
}
//send items for one order
private class SendItemAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... arg0) {
//Create JSON string start
json_string = "{\"sending_items\":[";
for (int i = 0; i < myRecyclerViewAdapter.getItemCount(); i++) {
/* if (myRecyclerView.findViewHolderForLayoutPosition(i) instanceof SelectItemAdapter.ItemHolder) {
SelectItemAdapter.ItemHolder childHolder = (SelectItemAdapter.ItemHolder) myRecyclerView.findViewHolderForLayoutPosition(i);
numberPickerNumber = childHolder.getQtyNumber();
}*/
getNumPicNumber(i);
//Repeat and loop this until all objects are added (and add try+catch)
try {
JSONObject obj_new = new JSONObject();
obj_new.put("order_no", orderIdForItemTable);
obj_new.put("items", myRecyclerViewAdapter.getItemName(i).toString());
obj_new.put("items_no", myRecyclerViewAdapter.getItemPCode(i).toString());
obj_new.put("plant", myRecyclerViewAdapter.getItemPlant(i).toString());
obj_new.put("quantity", numberPickerNumber);
json_string = json_string + obj_new.toString() + ",";
} catch (JSONException e) {
e.printStackTrace();
}
}
//Close JSON string
json_string = json_string.substring(0, json_string.length() - 1);
json_string += "]}";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3500);
HttpConnectionParams.setSoTimeout(httpParams, 1000);
HttpClient client = new DefaultHttpClient(httpParams);
String url = AppConfig.URL_ITEMS_SEND;
HttpPost request = new HttpPost(url);
try {
request.setEntity(new ByteArrayEntity(json_string.getBytes("UTF8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.setHeader("json", json_string);
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
Log.i("", "excuting request");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("HTTP Response", response.getStatusLine().toString());
try {
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("Server Response", responseBody);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
finish();
Bundle basket = new Bundle();
basket.putString("dealerName", dealerName);
basket.putString("orderNo", newOrderId);
basket.putString("jsonString", json_string);
Intent intent = new Intent(SelectItem.this, ItemCart.class);
intent.putExtras(basket);
startActivity(intent);
finish();
//Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
}
}
private String getNumPicNumber(int i) {
if (myRecyclerView.findViewHolderForLayoutPosition(i) instanceof SelectItemAdapter.ItemHolder) {
SelectItemAdapter.ItemHolder childHolder = (SelectItemAdapter.ItemHolder) myRecyclerView.findViewHolderForLayoutPosition(i);
numberPickerNumber = childHolder.getQtyNumber();
}
return numberPickerNumber;
}
#Override
public void onItemClick(SelectItemAdapter.ItemHolder item, int position) {
Toast.makeText(this,
"Remove " + position + " : " + item.getItemName(),
Toast.LENGTH_SHORT).show();
myRecyclerViewAdapter.remove(position);
}
private void checkOrderNo() {
showDialog();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
final String nowDate = df.format(new Date());
//final day of the month
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
final String lastDate = sdf.format(lastDayOfMonth);
Log.d("Last day ", sdf.format(lastDayOfMonth) + " // Today" + nowDate);
// Tag used to cancel the insert
String tag_string_req = "req_insert";
final StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_ITEM_DETAILS_SEND, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
if (jObj.names().get(0).equals("found")) {
newOrderId = jObj.getString("found").toString();
orderIdForItemTable = newOrderId;
new SendItemAsync().execute();
Log.d(TAG, "newOrderId: " + newOrderId);
Log.d(TAG, "New repID 2 inserted into sqlite: " + newOrderId + " " + nowDate);
sqLiteHandler.addItemDetails(newOrderId, repID, dealerID, nowDate, lastDate, selectedDisChannel);
} else {
Toast.makeText(getApplicationContext(), "Invalied Request", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Inserting Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("order_no", orderId);
params.put("repID", repID);
params.put("dealerID", dealerID);
params.put("nowDate", nowDate);
params.put("lastDate", lastDate);
params.put("disChannel", selectedDisChannel);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(6000, 1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
My Adapter class.
public class SelectItemAdapter extends RecyclerView.Adapter<SelectItemAdapter.ItemHolder> {
private List<String> itemsName, itemsQty, itemsPCode, itemPlant;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
private RecyclerView myRecyclerview;
public SelectItemAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
itemsName = new ArrayList<String>();
itemsQty = new ArrayList<String>();
itemsPCode = new ArrayList<String>();
itemPlant = new ArrayList<String>();
}
#Override
public SelectItemAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.custom_row_selected_item, parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(SelectItemAdapter.ItemHolder holder, int position) {
holder.setItemName(itemsName.get(position));
holder.setItemQty(itemsQty.get(position));
holder.setItemPCode(itemsPCode.get(position));
holder.setItemPlant(itemPlant.get(position));
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return itemsName.size();
}
public Object getItemName(int position) {
return itemsName.get(position);
}
public Object getItemPCode(int position) {
return itemsPCode.get(position);
}
public Object getItemPlant(int position) {
return itemPlant.get(position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public interface OnItemClickListener {
public void onItemClick(ItemHolder item, int position);
}
public void add(int location, String iName, String iQty, String iPCode, String iPlant) {
itemsName.add(location, iName);
itemsQty.add(location, iQty);
itemsPCode.add(location, iPCode);
itemPlant.add(location, iPlant);
notifyItemInserted(location);
}
public void remove(int location) {
if (location >= itemsName.size())
return;
itemsName.remove(location);
notifyItemRemoved(location);
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private SelectItemAdapter parent;
TextView textItemName, txtPCode, txtAvailableQty, txtTempQty, txtPlant;
Button bRemove;
EditText numPicker;
public ItemHolder(View itemView, SelectItemAdapter parent) {
super(itemView);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.txtProductName);
txtAvailableQty = (TextView) itemView.findViewById(R.id.txtAvailbleQty);
txtPCode = (TextView) itemView.findViewById(R.id.txtPCode);
txtPlant = (TextView) itemView.findViewById(R.id.txtPlant);
bRemove = (Button) itemView.findViewById(R.id.bRemove);
numPicker = (EditText) itemView.findViewById(R.id.numberPicker);
bRemove.setOnClickListener(this);
}
public void setItemName(CharSequence name) {
textItemName.setText(name);
}
public void setItemQty(CharSequence name) {
txtAvailableQty.setText(name);
}
public void setItemPCode(CharSequence name) {
txtPCode.setText(name);
}
public void setItemPlant(CharSequence name) {
txtPlant.setText(name);
}
public String getQtyNumber() {
return numPicker.getText().toString();
}
public CharSequence getItemName() {
return textItemName.getText();
}
public CharSequence getItemPCode() {
return txtPCode.getText();
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if (listener != null) {
listener.onItemClick(this, getPosition());
}
}
}
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
holder.setIsRecyclable(false);// set this in your adapter class as like it is
}
Override getItemViewType method
override fun getItemViewType(position: Int): Int {
return position
}
RecyclerView creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra. As the user scrolls through the list, the RecyclerView takes the off-screen views and rebinds them to the data which is scrolling onto the screen
// Items for recycler View
//binding data
private ArrayList<Data> Items;
//HashMap to store editText text afterTextChanged
//each editext in RecyclerView contains Unique Key And Value
private HashMap<String,String> sourceData=new HashMap<>();
Refer This RecyclerView Program
public class DataRecyclerView extends RecyclerView.Adapter<DataRecyclerView.DataViewHolder> {
private Context context;
// Items for recycler View
//binding data
private ArrayList<Data> Items;
private LayoutInflater layoutInflater;
//HashMap to store editText text afterTextChanged
//each editext in RecyclerView contains Unique Key And Value
private HashMap<String,String> sourceData=new HashMap<>();
DataRecyclerView(Context context,ArrayList<Data> Items)
{
this.Items=Items;
this.context=context;
layoutInflater=LayoutInflater.from(context);
}
#NonNull
#Override
public DataViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//DataBinding is used to bind Data
DataViewHolderBinding binding= DataBindingUtil.inflate(layoutInflater, R.layout.template,parent,false);
return new DataViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull DataViewHolder holder, int position) {
//Pass Data pojo to Holder
holder.bindData(Items.get(position));
}
#Override
public int getItemCount() {
return Items.size();
}
class DataViewHolder extends RecyclerView.ViewHolder {
private EditText amount;
DataViewHolder(DataViewHolderBinding itemView) {
super(itemView.getRoot());
binding=itemView;
amount=binding.PayAmount;
}
void bindData(Data data)//Data pojo for DataBinding
{
if(binding!=null) {
// data will automatically set to textViews In DataBinding
binding.setData(data);
//every time data binds to views
//get text of respective edittext and assign to that current edittext
if (sourceData.containsKey((String.valueOf(getAdapterPosition())))) {// checks current editText key is availible or not
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
amount.setText(sourceData.get((String.valueOf(getAdapterPosition()))).getAmount());
}else
{
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
amount.setText(null);
}
amount.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
//when user enter text into edittext
//editetext key already availible in sourceData
// then update the value to hashmap sourceData
if (sourceData.containsKey(String.valueOf(getAdapterPosition()))) {
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
if (!s.toString().trim().isEmpty()) {
if (!s.toString().trim().equals("0")) {
sourceData.put(String.valueOf(getAdapterPosition()),s.toString().trim());
} else {
sourceData.put(String.valueOf(getAdapterPosition()), s.toString().trim();
}
} else {
sourceData.put(String.valueOf(getAdapterPosition()),null );
}
}
}
else {
//when user enter text into edittext for the first time
//check for current Data pojo IDNumber with getAdapterPosition Items Data pojo IDNumber
//if it equal
//then we store text into hashmap for specific edittext by using adapterPosition as key
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
if (!s.toString().trim().isEmpty()) {
if (!s.toString().trim().equals("0")) {
sourceData.put(String.valueOf(getAdapterPosition()),s.toString().trim());
} else {
sourceData.put(String.valueOf(getAdapterPosition()), s.toString().trim();
}
} else {
sourceData.put(String.valueOf(getAdapterPosition()),null );
}
}
}
}
});
}
}
}
}
### Image Reference I can't show proper Image but Its Look Like this
The rows in RecyclerView is reusing while scrolling. So you need to create an array for save each EditText value
Then addTextChangedListener to your EditText to save the EditText value while you input
public void onBindViewHolder(SelectItemAdapter.ItemHolder holder, int position) {
...
holder.numPicker.setText(arrayForSaveEditTextValue[position]);
holder.numPicker.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
arrayForSaveEditTextValue[position] = arg0.toString();
}
});
...
}

how to get associated other json value in spinner when an item selected

I am trying a simple app where I populating a spinner with the values (json value) I got from network call. But I am not getting how to get the associated json value, when an item selected from the spinner. Can any one provide me a article/reference on how to do this?
this is my json response
{
item: {
name: "xyz",
brands: [
{
id: 123,
name: "abc"
}
]
}
}
This is how I parsed the json.
public class user_activity extends ActionBarActivity {
RequestQueue queue;
ArrayList<String> brand_list = new ArrayList<String>();
Spinner spinner;
String brand_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_activity);
this.spinner= (Spinner) findViewById(R.id.spinner);
loadUser();
}
public void loadUser() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Please Wait..");
pDialog.show();
queue = Volley.newRequestQueue(this);
String url = "http://myApiUrl";
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
pDialog.hide();
try {
JSONArray array = response.getJSONObject("item").getJSONArray("brands");
for (int i=0; i< array.length();i++) {
String b = array.getJSONObject(i).getString("name");
brand_list.add(b);
}
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(user_activity.this,android.R.layout.simple_dropdown_item_1line,brand_list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getBaseContext(),spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} catch (JSONException e) {
e.printStackTrace();
pDialog.hide();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", String.valueOf(error));
}
}
);
queue.add(postRequest);
}
I want to send the associated id values i,e "123" to next activity through a button intent.
EDIT:
Modified code as follows
But function set spinner always returns empty
public class user_activity extends ActionBarActivity {
String phone_number;
String access_token;
Button enterButton;
String brand_id;
TextView uName;
RequestQueue queue;
ArrayList<String> brand_list = new ArrayList<String>();
ArrayList<String> _ids = new ArrayList<String>();
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_activity);
this.phone_number = getIntent().getStringExtra("phone");
this.access_token = getIntent().getStringExtra("token");
enterButton = (Button)findViewById(R.id.buttonEnter);
uName = (TextView) findViewById(R.id.tvName);
this.spinner= (Spinner) findViewById(R.id.spinner);
loadUser(phone_number, access_token);
// nextActivity(b[0]);
}
public void loadUser(String phone, String token) {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Please Wait..");
pDialog.show();
queue = Volley.newRequestQueue(this);
final String[] message = new String[1];
final String[] my_id = new String[1];
String url = "http://api_url";
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
pDialog.hide();
try {
message[0] = response.getJSONObject("item").getString("name");
uName.setText(message[0]);
JSONArray array = response.getJSONObject("item").getJSONArray("brands");
for (int i=0; i< array.length();i++) {
String b = array.getJSONObject(i).getString("name");
String id = array.getJSONObject(i).getString("id");
_ids.add(id);
brand_list.add(b);
}
String id = setSpinner();
} catch (JSONException e) {
e.printStackTrace();
pDialog.hide();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", String.valueOf(error));
}
}
);
queue.add(postRequest);
}
public String setSpinner(){
ArrayAdapter<String> adapter;
final String[] id = new String[1];
adapter = new ArrayAdapter<String>(user_activity.this,android.R.layout.simple_dropdown_item_1line,brand_list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
id[0] = _ids.get(i);
// Toast.makeText(getBaseContext(), id[0] + ":" + spinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Toast.makeText(getBaseContext(), id[0].toString() , Toast.LENGTH_SHORT).show();
return id[0];
}
There are many ways.
One way is create id arrayList
ArrayList<String> _ids = new ArrayList<String>();
add values from JSON to this arryList
String id = array.getJSONObject(i).getString("id");
_ids.add(id);
and then used it in your spinner.setOnItemSelectedListener(....)
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String id=_ids.get(position);//Used this id to pass to another Activity
}
....
});
I think you need to store the data first in an array list like below..
JSONArray array = response.getJSONObject("item").getJSONArray("brands");
for (int i=0; i< array.length();i++) {
JSONObject mItemObject = array.getJSONObject(i);
String b = mItemObject.getString("name");
brand_list.add(b);
JSONArray mBrandsArray = mItemObject.getJSONArray("brands");
JSONObject mBrandsObject = mBrandsArray.getJSONObject(0);
String brandsId = mBrandsObject.getString("id");
String brandsName = mBrandsObject.getString("name");
brand_id.add(brandId); //make this array list likebrand_list
brand_name.add(brandName); //make this array list like ..
}
And then in your spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getBaseContext(),spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
Intent mIntent = new Intent(this, NewActivity.class);
// load data using putExtra
mIntent.putExtra("id", brand_id.get(i));
...
...
startActivity(mIntent);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Create a Class called Brand as below
class Brand {
int id;
String name;
#Override
public String toString() {
return name;
}
}
Now change your parsing code and make the Brand object in place of just getting name and add it to brand_list. Once user select anything you can get the selected index find the brand object and send the id from object to the other activity.
You need to create your own omplementation of OnItemSelectedListener interface and place it to spinner by spinner.setOnItemSelectedListener(listener). Your listener object should look like
listener = new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
JSONObject selectedObject = globalItemsObject.optJSONObject(position);
//make some actions with "selectedObject"
}
public void onNothingSelected(AdapterView<?> parent) {
}
};

Categories

Resources