How to add an id to an inflated view? - java

I am dynamically adding views to my layout by using layout inflater, but I am trying to add an id to every new view that gets added so I can use a getter to extract the information.
I am also trying to change the array data in the new spinner that gets added in each view as it is currently showing the default string array and not the array that I read from my database
public void onAddField(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
getdata2();
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
Log.d(String.valueOf(rowView.getId()), "onAddField: ");
getdata2();
}
private void getdata2() {
StringRequest stringRequest = new StringRequest("http://.../getDataCategories.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
catdetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void catdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList2.add(json.getString(CategoryType_idArray));
} catch (JSONException e) {
e.printStackTrace();
}
}
type2_workout_mySpinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, arrayList2));
}

You can add id as tag inside view object
View rowView = inflater.inflate(R.layout.field, null);
rowView.setTag(1);
consider number as your view id and get this id as getTag().
You can also update the array data and spinner update using above.
Like get a child from parentLinearLayout using parentLinearLayout.getchildAt() and then get the spinner from view and the again set adapter into the spinner.

Related

ScrollView should scroll to a particular TextView While selecting the same name in Spinner

In my app I want to scroll my ScrollView when I am selecting a text in Spinner upto one particular TextView which contains the text same as selected Spinner text in Android Studio using Java. (you can check image also). Here my spinner is dynamic and my textviews are also dynamic.
My Code - For Spinner
private void spinnerbind() {
JSONObject request = new JSONObject();
try {
request.put("action", "get_spinner");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, url,request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("data");
if(response.optString("status").equals("1")){
goodModelArrayList = new ArrayList<>();
//JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PlayerModel playerModel = new PlayerModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setid(dataobj.getString("id"));
playerModel.setTitle(dataobj.getString("specialist"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size(); i++){
names.add(goodModelArrayList.get(i).getTitle().toString());
}
spinnerArrayAdapter = new ArrayAdapter<String>(DoctorsActivity.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
mySpinner.setAdapter(spinnerArrayAdapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
PlayerModel playerModel = goodModelArrayList.get(position);
myid=playerModel.getId();
scrollView.scrollTo(0, 200);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
My Code - For Text Binding
public void detailsbind(){
JSONObject docrequest = new JSONObject();
try {
myrequest.put("action", "get_doctors");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, url,myrequest, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.optString("status").equals("1")){
// Toast.makeText(getApplicationContext(),response.getString("data"), Toast.LENGTH_SHORT).show();
JSONArray dataSpecArray = response.getJSONArray("data");
LayoutInflater inflater = getLayoutInflater();
for (int k = 0; k < dataSpecArray.length(); k++) {
PlayerModel Specialist = new PlayerModel();
JSONObject specJSONobj = dataSpecArray.getJSONObject(k);
TextView text1 = new TextView(MyActivity.this);
text1.setText(specJSONobj.getString("specialist"));
mainlayout.addView(text1);
}
}else{
Toast.makeText(DoctorsActivity.this, response.optString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
scrollview.scrollTo(0, getRelativeTop(textView))
private int getRelativeTop(View textView) {
if (textView.getParent() == textView.getRootView())
return textView.getTop();
else
return textView.getTop() + getRelativeTop((View) textView.getParent());
}

Is there a major difference between an id and a tag? Which one will be more appropriate?

I am using a LayoutInflater to add dynamic views every time I press the button function. I am trying to add a tag/id to the view so that I can identify each element.
I have tried setTag as well as setId but always seem to end up not being able to find the element
public void onAddField(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
rowView.setTag(a);
//rowView.setId(a);
getdata2();
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
Log.d(String.valueOf(parentLinearLayout.getChildAt(a).getId()), "onAddField: " + type2_workout_mySpinner.findViewWithTag(a).);
getdata2();
a = a +1;
}
private void getdata2() {
StringRequest stringRequest = new StringRequest("http://.../getDataCategories.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
catdetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void catdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList2.add(json.getString(CategoryType_idArray));
} catch (JSONException e) {
e.printStackTrace();
}
}
type2_workout_mySpinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, arrayList2));
}
I would like to be able to use a getter class to get the values of each element that I have added for example the value of multiple spinner values selected

No adapter attached; skipping layout - beginner issue

Im using volley to download the JSON data from a server, setting the Adapter within the function that reads and parses the data. However, the adapter is not being recognized. The problem is, I have successfully implemented the adapter in another activity with the same method without errors. The following is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras!=null) {
user_id = getIntent().getStringExtra("user_id");
} else {
Intent logIn = new Intent(JoinedActivity.this, LoginActivity.class);
startActivity(logIn);
}
setContentView(R.layout.activity_joined);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
GetJoinedEvents();
}
public void GetJoinedEvents(){
String tag_string_req = "req_getJoinedEvents";
StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.URL_USER_lIST_EVENTS+user_id, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
// progressDialog.dismiss();
Log.i("responseTest",response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
int length = result.length();
HashMap<String, String> events;
for (int i = 0; i < length; i++) {
JSONObject jo = result.getJSONObject(i);
String event_id = jo.getString(Config.TAG_EVENT_ID);
String name = jo.getString(Config.TAG_EVENT_NAME);
String date = jo.getString(Config.TAG_EVENT_START_DT);
String weekday = jo.getString(Config.TAG_EVENT_WEEKDAY);
String event_type = jo.getString(Config.TAG_EVENT_TYPE);
events = new HashMap<>();
events.put(Config.TAG_EVENT_ID, event_id);
events.put(Config.TAG_EVENT_NAME, name);
events.put(Config.TAG_EVENT_START_DT, date);
events.put(Config.TAG_EVENT_WEEKDAY, weekday);
events.put(Config.TAG_EVENT_TYPE, event_type);
eventList.add(events);
}
listAdapter = new RecyclerViewAdapter(JoinedActivity.this,eventList, user_id);
recyclerView.setAdapter(listAdapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Bad internet connection");
}
}) {};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
Log.i("URL", stringRequest.toString());
}
}
A better approach to this is just to initialize the Recycler view and adapter on the onCreate. Then later on when you have the data you could create a swapItems method just for the purpose of changing the data within the recyclerview through the adapter, but in a way that both the RecyclerView and its adapter is instantiated as the activity starts.
on your swapItems you could do something like below:
public void swapItems(List<Events> eventList) {
if (eventList != null) {
this.items = eventList;
notifyDataSetChanged();// should call this to let the recyclerview know that our data set has changed
}
}
Then you could just call it via the activity by
listAdapter.swapItems(eventList);// this is done the moment you already got your list of events

Everytime I fetch pdf file, my ArrayAdapter stacks

I need help about how to refresh my ArrayAdapter whenever I click the button to fetch files. It keeps on stacking the new list without clearing the last. Please help, also don't mind my English.
This is my Array adapter
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
PdfHolder holder = null;
if(row == null)
{
LayoutInflater inflater=LayoutInflater.from(activity);
row = inflater.inflate(layoutResourceId,parent,false);
holder = new PdfHolder();
holder.textViewName = (TextView) row.findViewById(R.id.textViewName);
holder.textViewUrl = (TextView) row.findViewById(R.id.textViewUrl);
row.setTag(holder);
}
else
{
holder= (PdfHolder) row.getTag();
}
pdf = data.get(position);
holder.textViewName.setText(pdf.getName());
holder.textViewUrl.setText(pdf.getUrl());
return row;
}
class PdfHolder
{
TextView textViewName,textViewUrl;
}
This is my code where I fetch file from my live server
private void getPdfs() {
progressDialog.setMessage("Fetching pdfs from server...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, PDF_FETCH_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
Toast.makeText (Files.this,obj.getString("message"), Toast.LENGTH_SHORT).show();
JSONArray jsonArray = obj.getJSONArray("pdfs");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Pdf pdf = new Pdf();
String pdfName = jsonObject.getString("name");
String pdfUrl = jsonObject.getString("url");
pdf.setName(pdfName);
pdf.setUrl(pdfUrl);
pdfList.add(pdf);
}
pdfAdapter = new PdfAdapter(Files.this, R.layout.list_layout, pdfList);
listView.setAdapter(pdfAdapter);
pdfAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
RequestQueue request = Volley.newRequestQueue(this);
request.add(stringRequest);
}
Can you suggest what should I do? or a code snippet to add or change?
You are adding new pdfs to the same list every time you load new data.
To fix this, before
for(int i=0;i<jsonArray.length();i++){
do
pdfList.clear()

Get all values of listview after header button click

In my activity I am adding a header button to save the values of a listview, with an EditText and post them to a php/mysql web app.
I am able to get the values of the listview if I use setOnItemClickListener but when I use setOnClickListener on the header save button, I am not able to iterate through the listview.
I am using a custom array adaptor :-
public class CustomOrderAdaptor extends ArrayAdapter{
int groupid;
ArrayList<OneOrder> records;
Context context;
public CustomOrderAdaptor(Context context, int vg, int id, ArrayList<OneOrder>records) {
super(context, vg, id, records);
this.context = context;
groupid = vg;
this.records = records;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(groupid, parent, false);
TextView textName = (TextView) itemView.findViewById(R.id.product_name);
textName.setText(records.get(position).getproduct_name());
EditText new_quantity = (EditText) itemView.findViewById(R.id.new_quantity);
new_quantity.setText(records.get(position).getnew_quantity());
TextView textOrderitemid = (TextView) itemView.findViewById(R.id.order_item_id);
textOrderitemid.setText(records.get(position).getorder_item_id());
TextView textQuantity = (TextView) itemView.findViewById(R.id.quantity);
textQuantity.setText(records.get(position).getquantity());
return itemView;
}
}
data model :-
public class OneOrder {
private String quantity;
private String new_quantity;
private String product_name;
private String order_item_id;
public void setquantity(String quantity){this.quantity=quantity;}
public void setnew_quantity(String new_quantity){this.new_quantity=new_quantity;}
public void setproduct_name(String product_name){this.product_name=product_name;}
public void setorder_item_id(String order_item_id){this.order_item_id=order_item_id;}
public String getquantity(){return quantity;}
public String getnew_quantity(){return new_quantity;}
public String getproduct_name(){return product_name;}
public String getorder_item_id(){return order_item_id;}
}
My activity is :-
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_order);
context = this;
records = new ArrayList<OneOrder>();
listOrder = (ListView) findViewById(R.id.order_item_list);
LayoutInflater inflater = LayoutInflater.from(this);
View nTop = inflater.inflate(R.layout.activity_get_order_footer, null);
listOrder.addHeaderView(nTop);
adapter = new CustomOrderAdaptor(context, R.layout.list_order, R.id.product_name,
records);
listOrder.setAdapter(adapter);
Button mButton = (Button) nTop.findViewById(R.id.button_save);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONObject order_items = new JSONObject();
JSONObject sendObject = new JSONObject();
for (int i=0;i<adapter.getCount();i++){
JSONObject order_item = new JSONObject();
OneOrder current_order = (OneOrder) listOrder.getAdapter().getItem(i);
//OneOrder current_order = (OneOrder) getListView().getItemAtPosition(i);
try {
order_item.put("quantity", current_order.getquantity().toString());
order_item.put("new_quantity", current_order.getnew_quantity().toString());
order_item.put("order_item_id", current_order.getorder_item_id().toString());
order_items.put(String.valueOf(i),order_item);
} catch (JSONException e) {
e.printStackTrace();
}
}
HttpURLConnection conn = null;
try {
Intent i = getIntent(); // gets the previously created intent
String order_id = i.getStringExtra("order_id");
sendObject.put("items", order_items.toString());
sendObject.put("order_id", order_id);
try {
URL url = new URL("http://192.168.0.70/steam_dos/index.php?option=com_steam&section=linen&task=save_order_out");
String message = sendObject.toString();
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 10000 /*milliseconds*/ );
conn.setConnectTimeout( 15000 /* milliseconds */ );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();
//do something with response
InputStream is = conn.getInputStream();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
the error is here :-
order_item.put("quantity", current_order.getquantity().toString());
the error is simple :-
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String au.com.southportsteamlaundry.rfid.steamscanadditions.OneOrder.getquantity()' on a null object reference
The view looks like this :-
Layout view
I am trying to save all of the values of the listview after the save button is clicked but I am not getting the listview items with that code, could you please explain the best way to achieve that ? Thanks.
Normally it's not recommended to use Edit text with adapter, the reason is edit text saving cannot be handled when it scroll out.
There are two kinds solution.
Replace the listview with scrollview
2 create a variable and add a TextWatcher on the edittext. Whenever the edittext get modified, the text watcher detect the change and override the variable whener you done something on it.
code would be like
Implementing Text Watcher for EditText
my answer may not be the best one, but this is what I implemented to get the EditText values of the list view :
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONObject order_item = new JSONObject();
order_items_edited = new JSONObject();
for (int i = 0; i < listOrder.getCount(); i++) {
EditText et = (EditText) listOrder.getChildAt(i).findViewById(R.id.new_quantity);
if (et!=null) {
TextView oi = (TextView) listOrder.getChildAt(i).findViewById(R.id.order_item_id);
Log.i("dtag", "et is " + String.valueOf(et.getText()));
Log.i("dtag", "oi is " + String.valueOf(oi.getText()));
try {
order_item.put("new_quantity", String.valueOf(et.getText()));
order_item.put("order_item_id", String.valueOf(oi.getText()));
order_items_edited.put(String.valueOf(i),order_item);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
the main issue I was having was a null object for et, which is valid, but I wasn't testing for it.
Now its working, I will look at implementing a cleaner solution.

Categories