Spring Controller Method :
#RequestMapping(value="/checklist/{id}",method=RequestMethod.PUT, consumes=MediaType.APPLICATION_JSON_VALUE , produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public Checklist update(#RequestBody Checklist checklist, #PathVariable("id") int id)
{
checklist.setId(id);
return service.update(checklist);
}
JavaScript AJAX code:
var checklist={name:$('#newName').val(), details:$('#newDetails').val()};
$.ajax({ //send updated item values to
method:'put',
url:'/tracker/checklist/'+$(editingItem).attr('id'),
contentType:'application/json',
dataType:'json',
data:checklist,
success:function(data)
{
console.log(data);
$('#myModal').modal('hide');
}
});
Checklist Model:
package com.tracker.web.models;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
#Entity
#Table(name="checklists")
public class Checklist {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private int item_order;
private String name;
private String details;
private String phase;
private String completed;
private String skipped_note;
private Date completed_on;
private int completed_by;
#Temporal(TemporalType.TIMESTAMP)
#CreationTimestamp
private Date created_at;
#Temporal(TemporalType.TIMESTAMP)
#UpdateTimestamp
private Date updated_at;
#ManyToOne
private Event event;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getItem_order() {
return item_order;
}
public void setItem_order(int item_order) {
this.item_order = item_order;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getPhase() {
return phase;
}
public void setPhase(String phase) {
this.phase = phase;
}
public String getCompleted() {
return completed;
}
public void setCompleted(String completed) {
this.completed = completed;
}
public String getSkipped_note() {
return skipped_note;
}
public void setSkipped_note(String skipped_note) {
this.skipped_note = skipped_note;
}
public Date getCompleted_on() {
return completed_on;
}
public void setCompleted_on(Date completed_on) {
this.completed_on = completed_on;
}
public int getCompleted_by() {
return completed_by;
}
public void setCompleted_by(int completed_by) {
this.completed_by = completed_by;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at() {
this.created_at = new Date();
}
public Date getUpdated_at() {
return updated_at;
}
public void setUpdated_at() {
this.updated_at = new Date();
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
}
I am using Jquery 1.11. when i use with 'GET' instead of 'PUT' 'method' on client side and 'consumes' on server side, it works. even i tried with JSON.stringify while sending sending. i am using jackson on server side to convert data into json
Which version of jquery you are using?
If you are using jquery prior to 1.9.0 than try type: 'PUT' instead of method:'put' in your ajax call and it should work. Otherwise it should be of with method:'put' .
Check documentation for more reference http://api.jquery.com/jquery.ajax/
Related
I would like convert string to JSON while receiving the value from API. I am sending value from postman but I am unable to convert it to the JSON object in the model class ,I have decorated model class with the custom decorator. Thanks in Advance.
This is the Model Class and I wrote custom JSON convertor.
namespace WebApplication2.Models
{
[Serializable]
public class Test
{
[JsonConverter(typeof(UserConverter))]
public AS_AscContext AscParcelContext { get; set; }
}
public class AS_AscContext
{
public string ShellType { get; set; }
public string LayoutName { get; set; }
}
public class UserConverter : JsonConverter
{
private readonly Type[] _types;
public UserConverter(params Type[] types)
{
_types = types;
}
public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();
o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));
o.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return _types.Any(t => t == objectType);
}
}
This is the controller receiving value
[HttpPost]
public IActionResult Privacy([FromBody]Test aS_AggregatorRequest)
{
return View();
}
This is the postman collection
Try to change your postman JSON like this,
{
"ascParcelContext": {
"shellType": "ceme-sales-wallaby",
"layoutName": "value"
}
}
Don't escape any of the JSON data.
your json has another json inside. So it is better to fix the api but if you don't have an access try this
[HttpPost]
public IActionResult Privacy([FromBody]JObject jsonObject)
{
jsonObject["ascParcelContext"]= JObject.Parse( (string) jsonObject["ascParcelContext"]);
Test test = jsonObject.ToObject<Test>();
.....
}
public class Test
{
[JsonProperty("ascParcelContext")]
public AS_AscContext AscParcelContext { get; set; }
}
public class AS_AscContext
{
[JsonProperty("shellType")]
public string ShellType { get; set; }
[JsonProperty("layoutName")]
public string LayoutName { get; set; }
}
I have java springboot as backend and angular as front for CRUD operations. Only delete operation is not working at all. I get the error in eclipse log javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:295 and the postman shows status 405, Method not allowed error.
Here are my codes: Service
#Service
public class EmployeeService {
private final EmployeeRepo employeeRepo;
#Autowired
public EmployeeService (EmployeeRepo employeeRepo) {
this.employeeRepo = employeeRepo;
}
public Employee addEmployee(Employee employee) {
employee.setEmployeeCode(UUID.randomUUID().toString());
return employeeRepo.save(employee);
}
public List<Employee> findAllEmployees() {
return employeeRepo.findAll();
}
public Employee updateEmployee(Employee employee) {
return employeeRepo.save(employee);
}
public Employee findEmployeeById(Long id) {
return employeeRepo.findEmployeeById(id)
.orElseThrow(() -> new UserNotFoundException("User by id " + id + "was not found"));
}
public void deleteEmployee(Long id) {
employeeRepo.deleteEmployeeById(id);
}
}
Controller:
#RestController
#RequestMapping("/employee")
public class EmployeeResource {
private final EmployeeService employeeService;
public EmployeeResource(EmployeeService employeeService) {
this.employeeService = employeeService;
}
#GetMapping("/all")
public ResponseEntity<List<Employee>> getAllEmployees() {
List<Employee> employees = employeeService.findAllEmployees();
return new ResponseEntity<>(employees, HttpStatus.OK);
}
#GetMapping("/find/{id}")
public ResponseEntity<Employee> getEmployeeById(#PathVariable("id") Long id) {
Employee employee = employeeService.findEmployeeById(id);
return new ResponseEntity<>(employee, HttpStatus.OK);
}
#PostMapping("/add")
public ResponseEntity<Employee> addEmployee(#RequestBody Employee employee) {
Employee newEmployee = employeeService.addEmployee(employee);
return new ResponseEntity<>(newEmployee, HttpStatus.CREATED);
}
#PutMapping("/update")
public ResponseEntity<Employee> updateEmployee(#RequestBody Employee employee) {
Employee updateEmployee = employeeService.updateEmployee(employee);
return new ResponseEntity<>(updateEmployee, HttpStatus.OK);
}
#DeleteMapping("/delete/{id}")
public ResponseEntity<?> deleteEmployee(#PathVariable("id") Long id) {
employeeService.deleteEmployee(id);
return new ResponseEntity<>( HttpStatus.OK);
}
}
Springboot Application:
#SpringBootApplication
public class EmployeemanagerApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeemanagerApplication.class, args);
}
#Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Access", "Authorization", "Origin, Accept", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type","Accept", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Request-Method", "Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
application properties:
spring.datasource.url=jdbc\:mysql\://localhost\:3306/employeemanager?useSSL\=false
server.port=8060
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.username=root
spring.datasource.password=root
Finally I followed suggestions from other posts to use annotation Transactional at
public interface EmployeeRepo extends JpaRepository<Employee, Long> {
#Transactional
void deleteEmployeeById(Long id);
and that works!
I would like to pass the To Mailbox Address as a parameter with multiple addresses using MimeKit to send a message.
If I edit the controller action to include a string with 2 email addresses:
var message = new Message(new string[] { "address1#gmail.com","address2#gmail.com" }, eMailSubject, eMailContent, null);
the message will be sent to both recipients address1#gmail.com and address2#gmail.com.
However If I try to pass the parameter string eMailTo from the function email_valueChanged(e), I get the errors:
$exception {“Invalid addr-spec token at offset 0”}
x "\"address1#gmail.com\",\"address2#gmail.com\""
Is there a way to pass the eMailTo parameter for the IActionResult SendMessage within the javascript? Note that to is an IEnumerable string:
public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
I have also tried to pass the eMailTo parameter as an array with no luck.
Below are the details:
Function to send email from popup:
function showInfo(data) { location.href = '#Url.Action("SendMessage", "EMail")?eMailTo=' + eMailToAddress +'&eMailSubject=' + eMailSubject + '&eMailContent=' + eMailContent;}
<script>
let eMailToAddress = -1;
let eMailSubject = -1;
let eMailContent = -1;
function email_valueChanged(e) {
eMailToAddress = '"address1#gmail.com","address2#gmail.com"';
console.log("eMailToAddress = " + eMailToAddress);
}
</script>
EMailController.cs
using EmailService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CPSPMO.Controllers
{
public class EmailController : Controller
{
private readonly IEmailSender _emailSender;
public EmailController(IEmailSender emailSender)
{
_emailSender = emailSender;
}
public IActionResult SendMessage(string eMailTo, string eMailSubject, string eMailContent)
{
var message = new Message(new string[] { eMailTo }, eMailSubject, eMailContent, null);
_emailSender.SendEmailAsync(message);
return NoContent();
}
}
}
EMailConfiguration.cs
namespace EmailService
{
public class EmailConfiguration
{
public string From { get; set; }
public string SmtpServer { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
EMailSender.cs
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EmailService
{
public class EmailSender : IEmailSender
{
private readonly EmailConfiguration _emailConfig;
public EmailSender(EmailConfiguration emailConfig)
{
_emailConfig = emailConfig;
}
public void SendEmail(Message message)
{
var emailMessage = CreateEmailMessage(message);
Send(emailMessage);
}
public async Task SendEmailAsync(Message message)
{
var mailMessage = CreateEmailMessage(message);
await SendAsync(mailMessage);
}
private MimeMessage CreateEmailMessage(Message message)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(_emailConfig.From));
emailMessage.To.AddRange(message.To);
emailMessage.Subject = message.Subject;
var bodyBuilder = new BodyBuilder { HtmlBody = String.Format("<h2 style='color:red'>{0}<h2>",message.Content) };
if(message.Attachments != null && message.Attachments.Any())
{
byte[] fileBytes;
foreach (var attachment in message.Attachments)
{
using (var ms = new MemoryStream())
{
attachment.CopyTo(ms);
fileBytes = ms.ToArray();
}
bodyBuilder.Attachments.Add(attachment.FileName, fileBytes, ContentType.Parse(attachment.ContentType));
}
}
emailMessage.Body = bodyBuilder.ToMessageBody();
return emailMessage;
}
private async Task SendAsync(MimeMessage mailMessage)
{
using (var client = new SmtpClient())
{
try
{
await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, true);
await client.AuthenticateAsync(_emailConfig.Username, _emailConfig.Password);
await client.SendAsync(mailMessage);
}
catch
{
throw;
}
finally
{
await client.DisconnectAsync(true);
client.Dispose();
}
}
}
}
}
IMailSender.cs
using System.Threading.Tasks;
namespace EmailService
{
public interface IEmailSender
{
void SendEmail(Message message);
Task SendEmailAsync(Message message);
}
}
Message.cs
using Microsoft.AspNetCore.Http;
using MimeKit;
using System.Collections.Generic;
using System.Linq;
namespace EmailService
{
public class Message
{
public List<MailboxAddress> To { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
public IFormFileCollection Attachments { get; set; }
public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
{
To = new List<MailboxAddress>();
To.AddRange(to.Select(x => new MailboxAddress(x)));
Subject = subject;
Content = content;
Attachments = attachments;
}
}
}
Please try to use string[] eMailTo, it should be useful to you.
public string TestArray(string[] eMailTo,string eMailSubject)
{
StringBuilder msg = new StringBuilder();
for (int i = 0; i < eMailTo.Length; i++)
{
msg.Append(eMailTo[i]);
msg.Append(",");
}
return msg.Append(eMailSubject).ToString();
}
Test Link:
https://localhost:44374/home/TestArray?eMailTo=address1#gmail.com&eMailTo=address2#gmail.com&eMailTo=address3#gmail.com&eMailSubject=testdata
Test Result:
I have a fragment in which reside a RecyclerView. I parsed JSON data from a webpage and showed it in this RecyclerView using tutorial: https://www.learn2crack.com/2016/02/recyclerview-json-parsing.html
Now I wish to add an onClick to the RecyclerView items. I know how to do so for static RecyclerView items but don't know to setOnClickListener in this case. For static recyclerview items, I'm using this class for onClick events.
package com.parassidhu.cdlumaths;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class ItemClickSupport {
private final RecyclerView mRecyclerView;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
mOnItemClickListener.onItemClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
}
};
private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mOnItemLongClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
return mOnItemLongClickListener.onItemLongClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
return false;
}
};
private RecyclerView.OnChildAttachStateChangeListener mAttachListener
= new RecyclerView.OnChildAttachStateChangeListener() {
#Override
public void onChildViewAttachedToWindow(View view) {
if (mOnItemClickListener != null) {
view.setOnClickListener(mOnClickListener);
}
if (mOnItemLongClickListener != null) {
view.setOnLongClickListener(mOnLongClickListener);
}
}
#Override
public void onChildViewDetachedFromWindow(View view) {
}
};
private ItemClickSupport(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
mRecyclerView.setTag(R.id.item_click_support, this);
mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener);
}
public static ItemClickSupport addTo(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support == null) {
support = new ItemClickSupport(view);
}
return support;
}
public static ItemClickSupport removeFrom(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support != null) {
support.detach(view);
}
return support;
}
public ItemClickSupport setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
return this;
}
public ItemClickSupport setOnItemLongClickListener(OnItemLongClickListener listener) {
mOnItemLongClickListener = listener;
return this;
}
private void detach(RecyclerView view) {
view.removeOnChildAttachStateChangeListener(mAttachListener);
view.setTag(R.id.item_click_support, null);
}
public interface OnItemClickListener {
void onItemClicked(RecyclerView recyclerView, int position, View v);
}
public interface OnItemLongClickListener {
boolean onItemLongClicked(RecyclerView recyclerView, int position, View v);
}
}
My Adapter Class is:
package com.parassidhu.cdlumaths;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.parassidhu.cdlumaths.R;
import com.parassidhu.cdlumaths.Android;
import java.util.ArrayList;
public class NoticesData extends RecyclerView.Adapter<NoticesData.ViewHolder> {
private ArrayList<Android> mAndroidList;
private RecyclerView recyclerView;
public NoticesData(ArrayList<Android> androidList, RecyclerView rcl) {
mAndroidList = androidList;
recyclerView=rcl;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notices_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mTvName.setText(mAndroidList.get(position).getName());
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
//I can't call Toast or startIntent here
}
});
}
#Override
public int getItemCount() {
return mAndroidList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView mTvName;
public ViewHolder(View view) {
super(view);
mTvName = (TextView)view.findViewById(R.id.tv_name);
}
}
}
In your Activity or Fragment class create a method like below
public void showToast(int position) {
Toast.makeText(getActivity(), "Clicked position is " + position, Toast.LENGTH_SHORT).show();
}
(I think you're using Fragment so I used getActivity())
Now update your Adapter constructor like this
...
...
private YourFragment frag;
public NoticesData(ArrayList<Android> androidList, RecyclerView rcl, YourFragment fragment) {
mAndroidList = androidList;
recyclerView = rcl;
frag = fragment;
}
In your Fragment update Adapter initialization like this
NoticesData notice = NoticesData(androidList, rcl, YourFragment.this);
Now call the showToast() method like below in Adapter
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
frag.showToast(position); // it's like callback method
}
});
Note: here YourFragment means the Fragment which hosts your RecyclerView.
you must set click listener for each of the items in your recycler view from the adapter for that recycler view. when you set the data for each if the items (views) in the recycler view you can add the onClickListener for that view too.
I am trying to create this Volley project as my second activity which fetches a JSON feed from Yahoo Pipe and display in a ListView from here. The code works perfectly fine. However, I have encountered these problems:
When I have not turned the Internet on, the activity displays the loading ProgressDialog. However, pressing the Back button on my emulator or actual device does not dismiss the ProgressDialog. The activity did not respond to the Back action.
I tried this code, but it does not work or maybe I'm not doing it right:
#Override
public void onDestroy() {
super.onDestroy();
dismissPd();
}
private void dismissPd() {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
In case of an Internet connection error, how do I display the error message in this activity as a toast?
The following is my code:
public class Trending extends ActionBarActivity {
private String TAG = this.getClass().getSimpleName();
private ListView lstView;
private RequestQueue mRequestQueue;
private ArrayList<NewsModel> arrNews ;
private LayoutInflater lf;
private VolleyAdapter va;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trending);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent newActivity3=new Intent();
setResult(RESULT_OK, newActivity3);
lf = LayoutInflater.from(this);
arrNews = new ArrayList<NewsModel>();
va = new VolleyAdapter();
lstView = (ListView) findViewById(R.id.listView);
lstView.setAdapter(va);
mRequestQueue = Volley.newRequestQueue(this);
String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json";
pd = ProgressDialog.show(this,"Loading...","Please Wait...");
try {
Thread.sleep(2000);
} catch(Exception e) {
}
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
parseJSON(response);
va.notifyDataSetChanged();
pd.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.getMessage());
}
});
mRequestQueue.add(jr);
}
#Override
public void onDestroy() {
super.onDestroy();
dismissPd();
}
private void dismissPd() {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
private void parseJSON(JSONObject json){
try {
JSONObject value = json.getJSONObject("value");
JSONArray items = value.getJSONArray("items");
for (int i=0; i<items.length(); i++) {
JSONObject item = items.getJSONObject(i);
NewsModel nm = new NewsModel();
nm.setTitle(item.optString("title"));
nm.setDescription(item.optString("description"));
nm.setLink(item.optString("link"));
nm.setPubDate(item.optString("pubDate"));
arrNews.add(nm);
}
}
catch(Exception e){
e.printStackTrace();
}
}
class NewsModel {
private String title;
private String link;
private String description;
private String pubDate;
void setTitle(String title) {
this.title = title;
}
void setLink(String link) {
this.link = link;
}
void setDescription(String description) {
this.description = description;
}
void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
String getLink() {
return link;
}
String getDescription() {
return description;
}
String getPubDate() {
return pubDate;
}
String getTitle() {
return title;
}
}
class VolleyAdapter extends BaseAdapter {
#Override
public int getCount() {
return arrNews.size();
}
#Override
public Object getItem(int i) {
return arrNews.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh;
if (view == null) {
vh = new ViewHolder();
view = lf.inflate(R.layout.row_listview,null);
vh.tvTitle = (TextView) view.findViewById(R.id.txtTitle);
vh.tvDesc = (TextView) view.findViewById(R.id.txtDesc);
vh.tvDate = (TextView) view.findViewById(R.id.txtDate);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
NewsModel nm = arrNews.get(i);
vh.tvTitle.setText(nm.getTitle());
vh.tvDesc.setText(nm.getDescription());
vh.tvDate.setText(nm.getPubDate());
return view;
}
class ViewHolder {
TextView tvTitle;
TextView tvDesc;
TextView tvDate;
}
}
}
try this one then back button is working while dialog is running
pd = ProgressDialog.show(this,"Loading...","Please Wait...");
pd.setCancelable(true);
By use asynctask you write code like this way
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(ctx, null, "fetching ...");
pd.setCancelable(true);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
//fetch response from internet and process here
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pd.cancel();
//do next action here
super.onPostExecute(result);
}
You have to execute the JSON part of the code in AsyncTask.
Define doInBackground to return a String type. From doInBackground, handle the errors, like internet error or json error and accordingly return a suitable error message "internet error" or "json error".
This error will be available as input to onPostExecute (results). In onPostExecute, you can run a Switch Statement to handle each of the conditions. If "internet error", then pd.dismiss() and do a toast.
For a working version of the code, you can refer here...