android volley JsonArrayRequest return nothing - android-volley

in the below code my arrayList will be empty after JsonArrayRequest block.
I set break point at this line: "int size = arrayList.size();"
every thing is OK until "while" loop finishes. after that allayList is empty.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,(String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count=0;
int responseLength = response.length();
responseLength--;
while (count<responseLength)
{
try {
JSONObject jsonObject = response.getJSONObject(count);
Contact contact = new Contact(jsonObject.getString("title"),
jsonObject.getString("email"),
jsonObject.getString("description"),
jsonObject.getString("date"),
jsonObject.getBoolean("status"));
arrayList.add(contact);
int size = arrayList.size();
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
int size = arrayList.size();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error....",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
);
int size = arrayList.size();
VolleySingleton.getmInstance(context).addToRequestQueue(jsonArrayRequest);
return arrayList;

I will show what i did using CallBack interface:
in onCreate() method:
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.getContacts(new BackgroundTask.arrayListCallBack() {
#Override
public void onSuccess(ArrayList<Contact> contacts) {
RecyclerView.Adapter adapter = new RecyclerAdapter(MainActivity.this, contacts);
recyclerView.setAdapter(adapter);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_LONG).show();
}
});
and in the BackgroundTask class:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, server_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
Contact contact = new Contact(jsonObject.getString("name"), jsonObject.getString("section"));
contacts.add(contact);
Log.d("process request", "....."+jsonObject.getString("name"));
count++;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage()+"\nError in Response", Toast.LENGTH_LONG).show();
}
callBack.onSuccess(contacts);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(context, error.getMessage()+"\nError in Connection", Toast.LENGTH_LONG).show();
callBack.onFail("There's error ...");
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}
public interface arrayListCallBack {
void onSuccess(ArrayList<Contact> contacts);
void onFail(String error);
}

Related

JSON Array With Volley Showing Only One data

I am trying to display array data using JSON Volley in PostsBasedOnCategory.java. Array data that I want to display are, Title post, and excerpt based on specific category from https://www.kisahmuslim.com/wp-json/wp/v2/categories. But unfortunately, it only showing one result.
Below you can check my code
DaftarCategories.java
public class CallingPage extends AsyncTask<String, String, String> {
HttpURLConnection conn;
java.net.URL url = null;
private int page = 1;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFav(false);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("https://www.kisahmuslim.com/wp-json/wp/v2/categories");
}
catch(MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
protected void onPostExecute(String result)
{
JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, SumberPosts.HOST_URL+"wp/v2/categories/", null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d(TAG, response.toString() + "Size: "+response.length());
// agar setiap kali direfresh data tidak redundant
typeForPosts.clear();
for(int i=0; i<response.length(); i++) { //ambil semua objek yang ada
final CategoriesModel post = new CategoriesModel();
try {
Log.d(TAG, "Object at " + i + response.get(i));
JSONObject obj = response.getJSONObject(i);
post.setId(obj.getInt("id"));
post.setPostURL(obj.getString("link"));
//Get category name
post.setCategory(obj.getString("name"));
//////////////////////////////////////////////////////////////////////////////////////
// getting article konten
JSONObject postCategoryParent = obj.getJSONObject("_links");
JSONArray postCategoryObj = postCategoryParent.getJSONArray("wp:post_type");
JSONObject postCategoryIndex = postCategoryObj.getJSONObject(0); //ambil satu objek saja
String postCategoryUrl = postCategoryIndex.getString("href"); //satu objek yang dimaksud adalah href
if(postCategoryUrl != null) {
Log.d(TAG, postCategoryIndex.getString("href"));
JsonArrayRequest getKonten = new JsonArrayRequest(Request.Method.GET, postCategoryUrl, null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray respon) {
Log.d(TAG, respon.toString() + "Size: "+respon.length());
for(int d=0; d<respon.length(); d++) {
try {
//Log.d(TAG, "Object at " + i + respon.get());
JSONObject objek = respon.getJSONObject(d); //ambil semua artikel yang tersedia di postCategoryUrl
post.setId(objek.getInt("id"));
post.setCreatedAt(objek.getString("date"));
post.setPostURL(objek.getString("link"));
//Get category title
JSONObject titleObj = objek.getJSONObject("title");
post.setJudul(titleObj.getString("rendered"));
//Get excerpt
JSONObject exerptObj = objek.getJSONObject("excerpt");
post.setExcerpt(exerptObj.getString("rendered"));
// Get content
JSONObject contentObj = objek.getJSONObject("content");
post.setContent(contentObj.getString("rendered"));
}
catch (JSONException e) {
e.printStackTrace();
}
}// for category
} //onResponse2
}, new Response.ErrorListener() { //getKonten
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getKonten);
} //if postCategoryUrl
//////////////////////////////////////////////////////////////////////////////////////
typeForPosts.add(post);
} //try 1
catch (JSONException e) {
e.printStackTrace();
}
} //for 1
pb.setVisibility(View.GONE);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} //onResponse1
}, new Response.ErrorListener() { //stringRequest
#Override
public void onErrorResponse(VolleyError error) {
showNoFav(true);
pb.setVisibility(View.GONE);
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} //onPostExecute
} //CallingPage
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
excerpt = click.getExcerpt();
//gambar = click.getPostImg();
judul = click.getJudul();
//url = click.getPostURL();
content = click.getContent();
Bundle bundle = new Bundle();
bundle.putString("judul", judul);
//bundle.putString("gambar", gambar);
//bundle.putString("url", url);
bundle.putString("content", content);
bundle.putString("excerpt", excerpt);
PostsBasedOnCategory bookFragment = new PostsBasedOnCategory();
bookFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContainerFragment, bookFragment).addToBackStack(null).commit();
}
PostsBasedOnCategory.java
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_wordpress, container,false);
ButterKnife.bind(this,view);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
swipeRefreshLayout =(SwipeRefreshLayout) getActivity().findViewById(R.id.swipeRefreshLayout);
recycleViewWordPress =(RecyclerView) getActivity().findViewById(R.id.recycleViewWordPress);
pb = (ProgressBar) getActivity().findViewById(R.id.loadingPanel);
noFavtsTV = getActivity().findViewById(R.id.no_favt_text);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
pb.setVisibility(View.VISIBLE);
recycleViewWordPress.setAdapter(mAdapter);
}
});
typeForPosts = new ArrayList<CategoriesModel>();
recycleViewWordPress.setHasFixedSize(true);
recycleViewWordPress.setLayoutManager(new LinearLayoutManager(getContext()));
recycleViewWordPress.setNestedScrollingEnabled(false);
mAdapter = new AdapterCategoryPosts(getContext(), typeForPosts, this);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
loadData();
}
public void loadData() {
Bundle bundel = this.getArguments();
long id = bundel.getLong("id");
String kategori = bundel.getString("kategori");
String title = bundel.getString("judul");
String excerpt = bundel.getString("excerpt");
String pict = bundel.getString("gambar");
String url = bundel.getString("url");
String konten = bundel.getString("konten");
CategoriesModel list = new CategoriesModel();
list.setId(id);
list.setCategory(kategori);
list.setJudul(title);
list.setExcerpt(excerpt);
list.setPostImg(pict);
list.setPostURL(url);
list.setContent(konten);
typeForPosts.add(list);
}
Logcat
2019-09-07 12:01:27.941 11246-11246/com.kursusarabic.arabicforfun D/postFrag: [{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":26,"count":8,"description":"","link":"https:\/\/kisahmuslim.com\/category\/download","name":"Download","slug":"download","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/26"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=26"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":1812,"count":9,"description":"","link":"https:\/\/kisahmuslim.com\/category\/info","name":"Info","slug":"info","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/1812"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1812"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":17,"count":3,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-birrul-walidain","name":"Kisah Birrul Walidain","slug":"kisah-birrul-walidain","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/17"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=17"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":25,"count":31,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-hidayah-islam","name":"Kisah Hidayah Islam","slug":"kisah-hidayah-islam","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/25"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":16,"count":49,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-kaum-durhaka","name":"Kisah Kaum Durhaka","slug":"kisah-kaum-durhaka","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/16"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: Object at 0{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=12
You cannot call network requests in loop, Use async processing or
Retrofit & RxJava multiple requests complete
and after updating typeForPosts, there is no need to setAdapter on recyclerview just call adapter.notifyDataSetChanged()

why volley didnt read my url string completely

I have been calling this API long enough. But now, volley cannot read my URL string completely using the same code as before, except that I put sendmsgnow() function in my adapter. It's working when I put that URL in my browser.
P.s:-I have changed the password as it's a paid sms gateway.
The error:
//Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.Viewholder> {
String contactdonor;
private static final String URL = "http://Lifetimesms.com/plain?username=opvg&password=mypassword&to=03365297078&from=ComapnyName&message=uyy kugtyf rtd ydrtjyty tku.";
private ArrayList<UserInformation> list;
private Context ctx;
public Adapter(ArrayList<UserInformation> list, Context ctx) {
this.list = list;
this.ctx = ctx;
}
#Override
public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user_layout, parent, false);
Viewholder myHolder = new Viewholder(view);
return myHolder;
}
#Override
public void onBindViewHolder(Viewholder holder, int position) {
final UserInformation val = list.get(position);
holder.edt_contact_no.setText(val.getContact_no());
holder.edt_blood_group.setText(val.getBlood_group());
holder.btn_approve.setText("approve");
holder.btn_decline.setText("decline");
holder.btn_approve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(ctx, "bloodgrp got= " + val.getBlood_group(), Toast.LENGTH_SHORT).show();
sendmsg(val);
}
});
holder.btn_decline.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//code to delete data
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("Patients");
reference.child(val.getContact_no()).removeValue();
}
});
}
public void sendmsg(final UserInformation val) {
//Toast.makeText(ctx, "sendmsg called", Toast.LENGTH_SHORT).show();
//Toast.makeText(ctx, "blood group received" + val.getBlood_group(), Toast.LENGTH_SHORT).show();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("Donors");
Query query = reference.orderByChild("blood_group_donor").equalTo(val.getBlood_group());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DonorInformation donor = null;
for (DataSnapshot data : dataSnapshot.getChildren()) {
donor = data.getValue(DonorInformation.class);
contactdonor = donor.getContact_no_donor();
Toast.makeText(ctx, "contactno is " + contactdonor, Toast.LENGTH_SHORT).show();
nowsendtxt();
}
// Toast.makeText(ctx, "contactno selected 0is= " + contact, Toast.LENGTH_SHORT).show();
}
private void nowsendtxt() {
//Toast.makeText(ctx, "contactno received" + contactdonor, Toast.LENGTH_SHORT).show();
StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(ctx, "successful", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ctx, "error", Toast.LENGTH_SHORT).show();
}
}//
);
RequestQueue requestQueue = Volley.newRequestQueue(ctx);
requestQueue.add(request);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
/*public void nowsendtxt(String contactdonor,UserInformation p )
{
Toast.makeText(ctx, "contactno received" + contactdonor, Toast.LENGTH_SHORT).show();
UserInformation patient=p;
String patient_name,bloodgrp_common;
patient_name=patient.getPatient_name();
bloodgrp_common=patient.getBlood_group();
StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(ctx, "successful", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ctx, "error", Toast.LENGTH_SHORT).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(ctx);
requestQueue.add(request);
}*/
#Override
public int getItemCount() {
return list.size();
}
public static class Viewholder extends RecyclerView.ViewHolder {
EditText edt_blood_group;
EditText edt_contact_no;
Button btn_approve, btn_decline;
public Viewholder(View itemView) {
super(itemView);
edt_blood_group = (EditText) itemView.findViewById(R.id.edt_blood_group);
edt_contact_no = (EditText) itemView.findViewById(R.id.edt_contact_no);
btn_approve = (Button) itemView.findViewById(R.id.btn_approve);
btn_decline = (Button) itemView.findViewById(R.id.btn_decline);
}
}
}

How to use Netty's channel pool map as a ConnectorProvider for a Jax RS client

I have wasted several hours trying to solve a issue with the use of netty's channel pool map and a jax rs client.
I have used jersey's own netty connector as an inspiration but exchanged netty's channel with netty's channel pool map.
https://jersey.github.io/apidocs/2.27/jersey/org/glassfish/jersey/netty/connector/NettyConnectorProvider.html
My problem is that I have references that I need inside my custom SimpleChannelInboundHandler. However by the design of netty's way to create a channel pool map, I can not pass the references through my custom ChannelPoolHandler, because as soon as the pool map has created a pool the constructor of the channel pool handler never runs again.
This is the method where it makes acquires a pool and check out a channel to make a HTTP request.
#Override
public Future<?> apply(ClientRequest request, AsyncConnectorCallback callback) {
final CompletableFuture<Object> completableFuture = new CompletableFuture<>();
try{
HttpRequest httpRequest = buildHttpRequest(request);
// guard against prematurely closed channel
final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener =
future -> {
if (!completableFuture.isDone()) {
completableFuture.completeExceptionally(new IOException("Channel closed."));
}
};
try {
ClientRequestDTO clientRequestDTO = new ClientRequestDTO(NettyChannelPoolConnector.this, request, completableFuture, callback);
dtoMap.putIfAbsent(request.getUri(), clientRequestDTO);
// Retrieves a channel pool for the given host
FixedChannelPool pool = this.poolMap.get(clientRequestDTO);
// Acquire a new channel from the pool
io.netty.util.concurrent.Future<Channel> f = pool.acquire();
f.addListener((FutureListener<Channel>) futureWrite -> {
//Succeeded with acquiring a channel
if (futureWrite.isSuccess()) {
Channel channel = futureWrite.getNow();
channel.closeFuture().addListener(closeListener);
try {
if(request.hasEntity()) {
channel.writeAndFlush(httpRequest);
final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(channel);
request.setStreamProvider(contentLength -> jerseyChunkedInput);
if(HttpUtil.isTransferEncodingChunked(httpRequest)) {
channel.write(jerseyChunkedInput);
} else {
channel.write(jerseyChunkedInput);
}
executorService.execute(() -> {
channel.closeFuture().removeListener(closeListener);
try {
request.writeEntity();
} catch (IOException ex) {
callback.failure(ex);
completableFuture.completeExceptionally(ex);
}
});
channel.flush();
} else {
channel.closeFuture().removeListener(closeListener);
channel.writeAndFlush(httpRequest);
}
} catch (Exception ex) {
System.err.println("Failed to sync and flush http request" + ex.getLocalizedMessage());
}
pool.release(channel);
}
});
} catch (NullPointerException ex) {
System.err.println("Failed to acquire socket from pool " + ex.getLocalizedMessage());
}
} catch (Exception ex) {
completableFuture.completeExceptionally(ex);
return completableFuture;
}
return completableFuture;
}
This is my ChannelPoolHandler
public class SimpleChannelPoolHandler implements ChannelPoolHandler {
private ClientRequestDTO clientRequestDTO;
private boolean ssl;
private URI uri;
private int port;
SimpleChannelPoolHandler(URI uri) {
this.uri = uri;
if(uri != null) {
this.port = uri.getPort() != -1 ? uri.getPort() : "https".equals(uri.getScheme()) ? 443 : 80;
ssl = "https".equalsIgnoreCase(uri.getScheme());
}
}
#Override
public void channelReleased(Channel ch) throws Exception {
System.out.println("Channel released: " + ch.toString());
}
#Override
public void channelAcquired(Channel ch) throws Exception {
System.out.println("Channel acquired: " + ch.toString());
}
#Override
public void channelCreated(Channel ch) throws Exception {
System.out.println("Channel created: " + ch.toString());
int readTimeout = Integer.parseInt(ApplicationEnvironment.getInstance().get("READ_TIMEOUT"));
SocketChannelConfig channelConfig = (SocketChannelConfig) ch.config();
channelConfig.setConnectTimeoutMillis(2000);
ChannelPipeline channelPipeline = ch.pipeline();
if(ssl) {
SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
channelPipeline.addLast("ssl", sslContext.newHandler(ch.alloc(), uri.getHost(), this.port));
}
channelPipeline.addLast("client codec", new HttpClientCodec());
channelPipeline.addLast("chunked content writer",new ChunkedWriteHandler());
channelPipeline.addLast("content decompressor", new HttpContentDecompressor());
channelPipeline.addLast("read timeout", new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
channelPipeline.addLast("business logic", new JerseyNettyClientHandler(this.uri));
}
}
And this is my SimpleInboundHandler
public class JerseyNettyClientHandler extends SimpleChannelInboundHandler<HttpObject> {
private final NettyChannelPoolConnector nettyChannelPoolConnector;
private final LinkedBlockingDeque<InputStream> isList = new LinkedBlockingDeque<>();
private final AsyncConnectorCallback asyncConnectorCallback;
private final ClientRequest jerseyRequest;
private final CompletableFuture future;
public JerseyNettyClientHandler(ClientRequestDto clientRequestDTO) {
this.nettyChannelPoolConnector = clientRequestDTO.getNettyChannelPoolConnector();
ClientRequestDTO cdto = clientRequestDTO.getNettyChannelPoolConnector().getDtoMap().get(clientRequestDTO.getClientRequest());
this.asyncConnectorCallback = cdto.getCallback();
this.jerseyRequest = cdto.getClientRequest();
this.future = cdto.getFuture();
}
#Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if(msg instanceof HttpResponse) {
final HttpResponse httpResponse = (HttpResponse) msg;
final ClientResponse response = new ClientResponse(new Response.StatusType() {
#Override
public int getStatusCode() {
return httpResponse.status().code();
}
#Override
public Response.Status.Family getFamily() {
return Response.Status.Family.familyOf(httpResponse.status().code());
}
#Override
public String getReasonPhrase() {
return httpResponse.status().reasonPhrase();
}
}, jerseyRequest);
for (Map.Entry<String, String> entry : httpResponse.headers().entries()) {
response.getHeaders().add(entry.getKey(), entry.getValue());
}
if((httpResponse.headers().contains(HttpHeaderNames.CONTENT_LENGTH) && HttpUtil.getContentLength(httpResponse) > 0) || HttpUtil.isTransferEncodingChunked(httpResponse)) {
ctx.channel().closeFuture().addListener(future -> isList.add(NettyInputStream.END_OF_INPUT_ERROR));
response.setEntityStream(new NettyInputStream(isList));
} else {
response.setEntityStream(new InputStream() {
#Override
public int read() {
return -1;
}
});
}
if(asyncConnectorCallback != null) {
nettyChannelPoolConnector.executorService.execute(() -> {
asyncConnectorCallback.response(response);
future.complete(response);
});
}
}
if(msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
ByteBuf byteContent = content.content();
if(byteContent.isReadable()) {
byte[] bytes = new byte[byteContent.readableBytes()];
byteContent.getBytes(byteContent.readerIndex(), bytes);
isList.add(new ByteArrayInputStream(bytes));
}
}
if(msg instanceof LastHttpContent) {
isList.add(NettyInputStream.END_OF_INPUT);
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if(asyncConnectorCallback != null) {
nettyChannelPoolConnector.executorService.execute(() -> asyncConnectorCallback.failure(cause));
}
future.completeExceptionally(cause);
isList.add(NettyInputStream.END_OF_INPUT_ERROR);
}
The references needed to be passed to the SimpleChannelInboundHandler is what is packed into the ClientRequestDTO as seen in the first code block.
I am not sure as it is not a tested code. But it could be achieved by the following code.
SimpleChannelPool sPool = poolMap.get(Req.getAddress());
Future<Channel> f = sPool.acquire();
f.get().pipeline().addLast("inbound", new NettyClientInBoundHandler(Req, jbContext, ReportData));
f.addListener(new NettyClientFutureListener(this.Req, sPool));
where Req, jbContext, ReportData could be input data for InboundHandler().

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.

Callbacks are not been called

I'm writing an app with Tango and getting a strange bug.
My program successfully connected to the tango service,and i have setup a callback with "mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {...});",but i can not get any tango datas because the callback have never been called.
here is my main code
private void bindTangoService() {
Log.d(TAG, "正在绑定Tango 服务");
if (mIsConnected) {
return;
}
mTango = new Tango(mContext, new Runnable() {
#Override
public void run() {
synchronized (TangoAR.this) {
try {
mConfig = setupTangoConfig(mTango, false, false);
mTango.connect(mConfig);
startupTango();
TangoSupport.initialize(mTango);
mIsConnected = true;
onRotationUpdated(Util.getDisplayRotation(mContext));
makeToast("tango 连接成功");
Log.d(TAG, "tango 连接成功");
} catch (TangoOutOfDateException e) {
makeToast("TangoOutOfDateException");
} catch (Throwable e) {
makeToast(e.getMessage());
}
}
}
});
}
private TangoConfig setupTangoConfig(Tango tango, boolean isLearningMode, boolean isLoadAdf) {
Log.d(TAG, "setupTangoConfig");
TangoConfig config = tango.getConfig(TangoConfig.CONFIG_TYPE_DEFAULT);
//在tango连接后使用相机必须使用true
config.putBoolean(TangoConfig.KEY_BOOLEAN_COLORCAMERA, false);
//motion
config.putBoolean(TangoConfig.KEY_BOOLEAN_MOTIONTRACKING, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_AUTORECOVERY, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_DRIFT_CORRECTION, true);
//depth
config.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_LOWLATENCYIMUINTEGRATION, true);
config.putInt(TangoConfig.KEY_INT_DEPTH_MODE, TangoConfig.TANGO_DEPTH_MODE_POINT_CLOUD);//使用点云,不使用老版本的TANGO_DEPTH_MODE_XYZ_IJ
//area learning
if (isLearningMode) {
//区域学习需要权限授权
if (checkAndRequestTangoPermissions(Tango.PERMISSIONTYPE_ADF_LOAD_SAVE)) {
Log.d(TAG, "PERMISSIONTYPE_ADF_LOAD_SAVE 开启");
config.putBoolean(TangoConfig.KEY_BOOLEAN_LEARNINGMODE, true);
}
}
if (isLoadAdf) {
//加载ADF
ArrayList<String> fullUuidList;
fullUuidList = tango.listAreaDescriptions();
if (fullUuidList.size() > 0) {
config.putString(TangoConfig.KEY_STRING_AREADESCRIPTION,
fullUuidList.get(fullUuidList.size() - 1));
}
}
return config;
}
private void startupTango() {
Log.d(TAG, "startupTango");
ArrayList<TangoCoordinateFramePair> framePairs = new ArrayList<>();
//设置参考系,0,0,0点为tango服务启动时设备的位置,测量目标为设备的位置
Log.d(TAG, "startup");
framePairs.add(new TangoCoordinateFramePair(
TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
TangoPoseData.COORDINATE_FRAME_DEVICE));
Log.d(TAG, "startup-listener");
mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {
#Override
public void onPoseAvailable(final TangoPoseData pose) {
//motion
Log.d(TAG, "onPoseAvailable");
//获取手机新的状态
mTangoTime = pose.timestamp;
TangoPoseData poseData = TangoSupport.getPoseAtTime(
mTangoTime,
TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
TangoPoseData.COORDINATE_FRAME_CAMERA_COLOR,
TangoSupport.ENGINE_OPENGL,
TangoSupport.ENGINE_OPENGL,
mDisplayRotation);
if (poseData.statusCode == TangoPoseData.POSE_VALID) {
mTangoPoseData = poseData;
}
}
#Override
public void onPointCloudAvailable(TangoPointCloudData pointCloud) {
//记录当扫描到到的深度信息
mPointCloudManager.updatePointCloud(pointCloud);
Log.d(TAG, "depth size:" + pointCloud.numPoints);
}
#Override
public void onXyzIjAvailable(TangoXyzIjData xyzIj) {
Log.d(TAG, "onXyzIjAvailable");
}
#Override
public void onFrameAvailable(int cameraId) {
Log.d(TAG, "onFrameAvailable");
}
#Override
public void onTangoEvent(TangoEvent event) {
Log.d(TAG, event.eventValue);
}
});
Log.d(TAG, "startup-listener-end");
}
mTango.connect(mConfig); execute successfully and without any exception.
I have been plagued by this problem for three days.I need a hero.Thanks everyone.
Notes:The rear camera is not be used for tango because i use it elsewhere.
I had the same problem. For me the solution was to request permissions:
startActivityForResult(
Tango.getRequestPermissionIntent(Tango.PERMISSIONTYPE_MOTION_TRACKING),
Tango.TANGO_INTENT_ACTIVITYCODE);

Resources