remove json object specfic values - spring

JSON representation
fruit: {
"type": "sweet",
"value": "Apple"
}
I want to perform concise representations like this.
fruit: "Apple"

You need to parse the string to JsonNode and then iterate over nodes and replace its value also check not a null child to avoid replacing a single node with a null value.
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String data =
"{ \"id\": \"123\", \"type\": \"fruit\", \"veritey1\": { \"type\": \"Property\", \"value\": \"moresweetappler\" }, \"quantity\": { \"type\": \"Property\", \"value\":10 } }";
ObjectMapper mapper = new ObjectMapper();
JsonNode nodes = mapper.readTree(data);
Iterator<Entry<String, JsonNode>> iterator = nodes.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> node = iterator.next();
if (node.getValue().hasNonNull("value")) {
((ObjectNode) nodes).set(node.getKey(), node.getValue().get("value"));
}
}
System.out.println(nodes.toString());
}
Output:
{"id":"123","type":"fruit","veritey1":"moresweetappler","quantity":10}
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String data =
"{ \"tank\": { \"type\": \"Relationship\", \"object\": \"id007\", \"time\": \"2017-07-29T12:00:04Z\", \"providedBy\": { \"type\": \"Relationship\", \"object\": \"id009\" } } }";
ObjectMapper mapper = new ObjectMapper();
JsonNode nodes = mapper.readTree(data);
Iterator<Entry<String, JsonNode>> iterator = nodes.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> node = iterator.next();
reduceJson(node.getValue());
}
System.out.println(nodes.toString());
}
public static void reduceJson(JsonNode node) {
if (node.hasNonNull("type")) {
((ObjectNode) node).remove("type");
}
Iterator<Entry<String, JsonNode>> iterator = node.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> childnode = iterator.next();
if (childnode.getValue().isObject()) {
reduceJson(node.get(childnode.getKey()));
}
}
}
Output:
{"tank":{"object":"id007","time":"2017-07-29T12:00:04Z","providedBy":{"object":"id009"}}}

const data = '{ "fruit": { "type": "sweet", "value": "Apple" }}';
const obj = JSON.parse(data);
for (let key in obj) {
console.log(key, obj[key].value); // "fruit", "Apple"
}

Related

date fields are transformed to different format when a java object stored to the elastic search?

Hi I am having a spring boot java application and I am trying to integrate elastic search capabilities into it .I have written a junit test where i start an embedded elastic search , then i read a json file containing an array of json objects and then trying to insert these object into the elastic search as document under an index.
However the problem is when i insert a java object containing an Instant field i am loosing the format.
MessageHistoryReportingResourceIntTest
#RunWith(SpringRunner.class)
#SpringBootTest(classes = PrimecastApp.class)
public class MessageHistoryReportingResourceIntTest {
#Autowired
private MessageHistoryReportingService messageHistoryReportingService;
#Autowired
private HttpMessageConverter[] httpMessageConverters;
#Autowired
private ExceptionTranslator exceptionTranslator;
#Value("${elasticsearch.configuration.host}")
private String host;
#Value("${elasticsearch.configuration.port}")
private int port;
private MockMvc restMvc;
private EmbeddedElastic embeddedElastic;
private RestHighLevelClient client;
#Before
public void startElasticServer() {
try {
embeddedElastic = EmbeddedElastic.builder().withElasticVersion("6.6.1")
.withSetting(PopularProperties.HTTP_PORT, port)
.withSetting(PopularProperties.CLUSTER_NAME, "my_cluster").withStartTimeout(5, TimeUnit.MINUTES)
.build()
// .withIndex("mep-report-today",
// IndexSettings.builder().withType("mep-report-mapping.json",
// getJsonResourceAsStream1()).build()).build()
.start();
client = new RestHighLevelClient(RestClient.builder(new HttpHost(host, port, "http")));
ObjectMapper objMapper = new ObjectMapper();
objMapper.registerModule(new JavaTimeModule());
List<MessageHistory> messageHistories = objMapper.readValue(getMessageHistoryResourceAsStream(),
objMapper.getTypeFactory().constructCollectionType(List.class, MessageHistory.class));
BulkRequest request = new BulkRequest();
for (int i = 0; i < messageHistories.size(); i++) {
request.add(new IndexRequest("mep-report-today", "doc", String.valueOf(i))
.source(objMapper.writeValueAsString(messageHistories.get(i)), XContentType.JSON));
}
request.timeout(TimeValue.timeValueMinutes(5));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
MockitoAnnotations.initMocks(this);
MessageHistoryReportingResource messageHistoryReportingResource = new MessageHistoryReportingResource(
messageHistoryReportingService);
this.restMvc = MockMvcBuilders.standaloneSetup(messageHistoryReportingResource)
.setMessageConverters(httpMessageConverters).setControllerAdvice(exceptionTranslator).build();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static InputStream getMessageHistoryResourceAsStream() throws FileNotFoundException {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("files/messageHistories.json");
return is;
}
#Test
public void test() {
GetRequest getRequest = new GetRequest("mep-report-today", "doc", "1");
try {
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
System.out.print(response.getSourceAsString());
SearchRequest searchRequest = new SearchRequest("mep-report-today");
searchRequest.types("doc");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.timeout(TimeValue.timeValueMinutes(3));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
System.out.println("********");
for (SearchHit hit : hits) {
System.out.println(hit.getId() + " -----" + hit.getSourceAsString());
}
System.out.println("********");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
messageHistories.json
[
{
"inventory": "MMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-14T07:59:42.000Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": 420736408283,
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": 8800111,
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1
},
{
"inventory": "SMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-08T08:47:02.000Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": 420736408283,
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": 8800111,
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1
}]
MessageHistory.java
package com.openmind.primecast.domain.elasticsearch;
import java.time.Instant;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonProperty;
public class MessageHistory {
#JsonProperty("inventory")
private String inventory;
#JsonProperty("msg_text")
private String messageText;
#JsonProperty("status")
private String status;
#JsonProperty("#timestamp")
private Instant timeStamp;
#JsonProperty("o_error")
private String error;
#JsonProperty("flight_id")
private UUID flightId;
#JsonProperty("recipient")
private String recipient;
#JsonProperty("account_id")
private UUID accountId;
#JsonProperty("sender")
private String sender;
#JsonProperty("campaign_id")
private UUID campaignId;
#JsonProperty("nof_segments")
private Integer segmentCount;
#JsonProperty("#version")
private Integer version;
public String getInventory() {
return inventory;
}
public void setInventory(String inventory) {
this.inventory = inventory;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Instant getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Instant timeStamp) {
this.timeStamp = timeStamp;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public UUID getFlightId() {
return flightId;
}
public void setFlightId(UUID flightId) {
this.flightId = flightId;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public UUID getAccountId() {
return accountId;
}
public void setAccountId(UUID accountId) {
this.accountId = accountId;
}
public UUID getCampaignId() {
return campaignId;
}
public void setCampaignId(UUID campaignId) {
this.campaignId = campaignId;
}
public Integer getSegmentCount() {
return segmentCount;
}
public void setSegmentCount(Integer segmentCount) {
this.segmentCount = segmentCount;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
#Override
public String toString() {
return "MessageHistory [inventory=" + inventory + ", messageText=" + messageText + ", status=" + status
+ ", timeStamp=" + timeStamp + ", error=" + error + ", flightId=" + flightId + ", recipient="
+ recipient + ", accountId=" + accountId + ", sender=" + sender + ", campaignId=" + campaignId
+ ", segmentCount=" + segmentCount + ", version=" + version + "]";
}
}
so in the messageHistories.json file each object there is a field named #timestamp, so when i map these array to java objects and i store these objects as documents under an index i am loosing the formatting . In other words when i run the integration test I get this output. in other words the #timestamp is stored in elastic search like this "#timestamp":1.568447982E9 . what i want is the like this in the elastic search "#timestamp":"2019-09-08T08:47:02.000Z"
********
0 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568447982E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
14 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.56851715E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
19 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.56767748E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
22 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568710029E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
24 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568629248E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
25 -----{"inventory":"SMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.569413823E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
26 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568528127E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
29 -----{"inventory":"MMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.569124502E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408283","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
40 -----{"inventory":"SMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568546145E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
41 -----{"inventory":"SMS","msg_text":"This is random text","status":"ENROUTE","#timestamp":1.568088436E9,"o_error":"","flight_id":"92348fa1-ca6c-456a-b3b2-85fba2d2deed","recipient":"420736408281","account_id":"a56f7e14-20f9-40e6-90c6-10604140ac5f","sender":"8800111","campaign_id":"6f2abca3-b46d-43f3-91be-3278a8dd7dc0","nof_segments":1,"#version":1}
********
any idea how can i achieve it ?
After i set my ObjectMapper with SerializationFeature.WRITE_DATES_AS_TIMESTAMPS it is good .
ObjectMapper objMapper = new ObjectMapper();
objMapper.registerModule(new JavaTimeModule());
objMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

Parse JSON array data in android using Volley

JSON data format:
I am trying to fetch this array json data but not getting it.
[{"Items":"Chicken Burger","Price":"250","Quantity":"2"},
{"Items":"Hamburger","Price":"230","Quantity":"3"}]
MyCartActivity class:
I tried using Volley and I am now getting that JSONArray cannot be converted to JSONObject error. Can you mention where to change so that I can get my data?
final JsonObjectRequest request = new JsonObjectRequest (Request.Method.POST, fetchurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i=0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String Price = object.getString("Price");
String Name = object.getString("Items");
String Quantity = object.getString("Quantity");
adapter = new CartAdapter(MyCartActivity.this, list);
list.add(new CartPojo(Price, Name, Quantity));
adapter.notifyDataSetChanged();
progressbar.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
Adapter class:
public CartAdapter(Activity activity, List datalist) {
this.activity = activity;
this.datalist = datalist;
}
#Override
public int getCount() {
return datalist.size();
}
#Override
public Object getItem(int position) {
return datalist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.cart_item_layout, null);
TextView ItemName = convertView.findViewById(R.id.item_name);
TextView Price = convertView.findViewById(R.id.item_price);
TextView Quantity = convertView.findViewById(R.id.items_quantity);
CartPojo pojo = datalist.get(position);
ItemName.setText(String.valueOf(pojo.getName()));
Price.setText(String.valueOf(pojo.getPrice()));
Quantity.setText(String.valueOf(pojo.getQuantity()));
return convertView;
}
Please provide me some solutions....
The response can't be parsed into JSONObject, because its not that, but a JSONArray. You can send a simple StringRequest and then parse the response string into an JSONArray using JSONArray(response) constructor.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray arr = new JSONArray(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Or use the JsonArrayRequest. Here's an example.

How to import data from csv to elasticsearch in java without using logstash?

I want to import data from a csv file to elasticsearch. But I don't want to use logstatsh. So, what are the ways I can do this ?
Any blogs ? Docs ?
I came across TransportClient, but I'm not getting the point from where to start .
Thanks in advance.
very late answer, however :) ….This is for elasticsearch 7.6.0
//this class for keeping csv each row values
public class Document {
private String id;
private String documentName;
private String name;
private String title;
private String dob;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public String getName() {
return name1;
}
public void setName(String name1) {
this.name1 = name1;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
public void bulkInsert() {
long starttime = System.currentTimeMillis();
logger.debug("ElasticSearchServiceImpl => bulkInsert Service Started");
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
BulkRequest request;
Document document;
//elastic Search Index Name
String esIndex = "post";
try {
br = new BufferedReader(new FileReader(<path to CSV>));
request = new BulkRequest();
while ((line = br.readLine()) != null) {
// use comma as separator
String[] row = line.split(cvsSplitBy);
if(row.length >= 1) {
//filling Document object using csv columns array
document = getDocEntity(row);
//adding each filled obect into BulkRequest
request.add(getIndexRequest(document, esIndex));
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : null row ="+row.toString());
}
}
br.close();
if(request.numberOfActions()>0) {
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
if(bulkResponse.hasFailures()) {
logger.error("ElasticSearchServiceImpl => bulkInsert : Some of the record has failed.Please reinitiate the process");
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : Success");
}
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : No request for BulkInsert ="+request.numberOfActions());
}
} catch (Exception e) {
logger.error("ElasticSearchServiceImpl => bulkInsert : Exception =" + e.getMessage());
}
long endTime = System.currentTimeMillis();
logger.info("ElasticSearchServiceImpl => bulkInsert End" + Util.DB_AVG_RESP_LOG + "" + (endTime - starttime));
}
public static Document getDocEntity(String[] row)throws Exception {
Document document = new Document();
document.setId(UUID.randomUUID().toString());
for(int i=0;i<row.length;i++) {
switch (i) {
case 0:
document.setDocumentName(row[i]);
break;
case 1:
document.setName(row[i]);
break;
case 7:
document.setTitle(row[i]);
break;
case 8:
document.setDob(row[i]);
break;
}
return document;
}
public static IndexRequest getIndexRequest(Document document,String index)throws Exception {
IndexRequest indexRequest = null;
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("doc_name",document.getDocumentName());
jsonMap.put("title",document.getTitle());
jsonMap.put("dob",document.getDob());
indexRequest = new IndexRequest(index).id(document.getId()).source(jsonMap);
return indexRequest;
}
If you need to show each response, you can use the following code for responses
for (BulkItemResponse bulkItemResponse : bulkResponse) {
DocWriteResponse itemResponse = bulkItemResponse.getResponse();
switch (bulkItemResponse.getOpType()) {
case INDEX:
case CREATE:
IndexResponse indexResponse = (IndexResponse) itemResponse;
break;
}
}
For more information please read official link

How to update/refresh list items of list view in oracle maf?

I have list of tasks. When I delete my one of the task my list still shows that task in the list but on server side i have updated list I am not able to refresh my list. I am getting new task array from server but not able to show it. When I launched my app again then it is showing the updated list. How can I get updated list without killing the app? Both the times I have updated array but not able to show it on the view.
public class ModelClass {
private String message;
private String statusCode;
private Response[] res = null;
protected transient PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
public ModelClass() {
super();
clickEvent(new ActionEvent());
}
public static String taskId;
public void setTaskId(String taskId) {
System.out.print(taskId);
this.taskId = taskId;
}
public String getTaskId() {
return taskId;
}
public PropertyChangeSupport getPropertyChangeSupport() {
return _propertyChangeSupport;
}
public void setMessage(String message) {
String oldMessage = this.message;
this.message = message;
_propertyChangeSupport.firePropertyChange("message", oldMessage, message);
}
public String getMessage() {
return message;
}
public void setStatusCode(String statusCode) {
String oldStatusCode = this.statusCode;
this.statusCode = statusCode;
_propertyChangeSupport.firePropertyChange("statusCode", oldStatusCode, statusCode);
}
public String getStatusCode() {
return statusCode;
}
public void setRes(Response[] res) {
Response[] oldRes = this.res;
this.res = res;
System.out.println(res);
_propertyChangeSupport.firePropertyChange("res", oldRes, res);
System.out.println("refreshing here ");
}
public Response[] getRes() {
return res;
}
#Override
public String toString() {
return "ClassPojo [response = " + res + ", message = " + message + ", statusCode = " + statusCode + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
public class Response {
private String taskId;
private String taskType;
private Integer taskTime;
private String taskName;
private PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
Response(String taskId, String taskType, String taskName) {
super();
this.taskId = taskId;
this.taskType = taskType;
this.taskName = taskName;
}
public void setTaskId(String taskId) {
String oldTaskId = this.taskId;
this.taskId = taskId;
_propertyChangeSupport.firePropertyChange("taskId", oldTaskId, taskId);
}
public String getTaskId() {
return taskId;
}
public void setTaskType(String taskType) {
String oldTaskType = this.taskType;
this.taskType = taskType;
_propertyChangeSupport.firePropertyChange("taskType", oldTaskType, taskType);
}
public String getTaskType() {
return taskType;
}
public void setTaskTime(Integer taskTime) {
Integer oldTaskTime = this.taskTime;
this.taskTime = taskTime;
_propertyChangeSupport.firePropertyChange("taskTime", oldTaskTime, taskTime);
}
public Integer getTaskTime() {
return taskTime;
}
public void setTaskName(String taskName) {
String oldTaskName = this.taskName;
this.taskName = taskName;
_propertyChangeSupport.firePropertyChange("taskName", oldTaskName, taskName);
}
public String getTaskName() {
return taskName;
}
#Override
public String toString() {
return "ClassPojo [taskId = " + taskId + ", taskType = " + taskType + ", taskTime = " + taskTime +
", taskName = " + taskName + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
}
protected transient ProviderChangeSupport providerChangeSupport = new ProviderChangeSupport(this);
public void addProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.addProviderChangeListener(l);
}
public void removeProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.removeProviderChangeListener(l);
}
public void clickEvent(ActionEvent actionEvent) {
try {
JSONObject paramsMap = new JSONObject();
paramsMap.put("userId", "1");
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/#########");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(120000);
httpURLConnection.setConnectTimeout(120000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
os.write(paramsMap.toString().getBytes());
bufferedWriter.flush();
bufferedWriter.close();
os.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line + "\n");
line = bufferedReader.readLine();
}
is.close();
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println(builder.toString());
JSONObject json = new JSONObject(builder.toString());
String status = json.optString("statusCode");
String message = json.optString("message");
String response = json.optString("response");
System.out.println(status);
System.out.println(message);
// System.out.println(response);
JSONArray objarr = json.optJSONArray("response");
Response[] temp_res = new Response[objarr.length()];
for (int i = 0; i < objarr.length(); i++) {
System.out.println(objarr.getJSONObject(i));
JSONObject obj = objarr.getJSONObject(i);
String task = obj.optString("taskName");
taskId = obj.optString("taskId");
String taskType = obj.optString("taskType");
System.out.println(task);
System.out.println(taskId);
System.out.println(taskType);
temp_res[i] = new Response(taskId, taskType, task);
}
setRes(temp_res);
} else {
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println("Invalid response from the server");
}
} catch (Exception e) {
e.printStackTrace();
if (httpURLConnection != null)
httpURLConnection.disconnect();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think you need to add providerChangeSupport.fireProviderRefresh("res");
and you have to make public method for providerChangeSupport.
Here is the link : https://community.oracle.com/message/13203364#13203364
Other than the fix suggested by Rashi Verma, there is one more change required.
The code snippet:
res = (Response[]) res_new.toArray(new Response[res_new.size()]);
setRes(res);
needs to be changed to:
Response[] temp_res;
temp_res = (Response[]) res_new.toArray(new
Response[res_new.size()]);
setRes(temp_res);
Currently, because the value of res is changed before invoking setRes, the propertyChangeEvent is not fired inside setRes. Both this propertyChangeEvent and the providerRefresh are needed for the changes you are making to start reflecting on the UI.

Using one progressDialog in two or more android stringRequest Volley

In my code I have to stringRequest Volley that works just fine, but now I want to use a progressDialog. I have create 1 method to put the progressDialog like this
private void showProgress(String message) {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
and I have these 2 stringRequest like this:
private void fetchDataPoMurni(final String tipe, final String user_id, final String last_date) {
showProgress("Murni");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA MURNI: ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoMurni(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
and the other request:
private void fetchDataPoDapat(final String tipe, final String user_id, final String last_date) {
showProgress("Dapat");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA DAPAT : ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoDapat(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
I execute the 2 request through a method like this:
private void exeRequest() {
fetchDataPoMurni(valuea,value2,value3);
fetchDataPoDapat(valueb,value2,value3);
}
the progressDialog is showing, and the message is changing, but the problem is when reach the second request the progressDialog doesn't want to dismiss.
Whats wrong with my code above, and how to achieve what I want?
private void showProgress(String message) {
progressDialog=null;// Initialize to null
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
Try this .. Initialize all instances of the progressDialog to null as soon as you create a new progress dialog

Resources