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()
Related
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());
}
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
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.
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§ion=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.
i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());