How try call (recconnect) Json? - java

pDialog = new ProgressDialog(NewItemList.this);
pDialog.setMessage("Connect...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
jsoncall();
}
public void jsoncall() {
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
String temp;
pDialog.dismiss();
Loading_items.Load_list(NewItemList.this,response.length());
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
BaseItems items_info = new BaseItems();
items_info.setName(jsonObject.getString("name"));
CheckList.add(items_info);
Loading_items.AddItemOne();
}
catch (JSONException e) {
e.printStackTrace();
}
}
setRvadapter(CheckList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(NewItemList.this);
requestQueue.add(ArrayRequest);
}
If the Internet stable - json works = everything well;
If to start without the Internet - pDialog isn't switched off = everything well;
If to start without the Internet, to cause jsoncall (); and to include the Internet - onResponse isn't carried out and I don't receive json = BAD :(;
How can I try to reconnect json?
enter image description here

I have solved so:
1) I have created a class of check of the Internet
2) I cause jsoncall () here so:
Thread myThready = new Thread(new Runnable()
{
public void run()
{
while (!TryConnectionInternet.TryConnectionInternet(NewItemList.this)){}
jsoncall();
}
});
myThready.start();

Related

How to get String response from post request volley

I am trying to get a string response from post request. Here, I am sending a post request. where I am sending this data. I have a Model of BillReceipt. Which I pass on the request body.
public void UserTransactionReceiptReport(TransactionTypeListener<String> listener, BillReceipt billReceiptReport){
final UserSettings userSettings = getMUserSettings();
final StringBuilder url = new StringBuilder(AppConfigsManager.getTouchServerUrl());
url.append("/api/User/UserData");
JSONObject params = new JSONObject();
try{
params.put("iB_CUST_ID",billReceiptReport.getiB_CUST_ID());
params.put("transactioN_DATE",billReceiptReport.getTransactioN_DATE());
params.put("transactioN_DATE_NM",billReceiptReport.getTransactioN_DATE_NM());
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url.toString(), params
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson mapper = new GsonBuilder().create();
try{
Type type = new TypeToken<APIResponse<String>>() {
}.getType();
APIResponse<String> responseObject = mapper.fromJson(response.toString(), type);
if(responseObject.Status == APIStatus.OK){
listener.didFetch(responseObject.Result, responseObject.Message);
}else {
listener.didError(responseObject.Message);
}
}catch (Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.didError(error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() {
return getAuthorizationTokenHashMap(getMUserSettings());
}
};
addVolleyRequest(request);
}
and I call this api from recycler download button.Here , I globally declared the manager where i write the api code. and also declare a the model name.
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager.UserTransactionReceiptReport(listener,billReceiptReport);
}
});
}
private final TransactionTypeListener<String> listener = new TransactionTypeListener<String>() {
#Override
public void didFetch(String response, String message) {
str = response;
}
#Override
public void didError(String message) {
}
};
any one help me to solve the problem i am facing.
Try this code
<code>
JSONObject jsonObject = new JSONObject(response);
System.out.println("jsonWallet----" + jsonObject);
int status_ = jsonObject.getInt("status");
if(status_ == 1){
String incomeWalletBal = jsonObject.getString("income_wallet");
String refundWalletBal = jsonObject.getString("refund_wallet");
}else {
}
</code>

why response eror listener is but response listener is in the json array request?

my app it has to take data from server
and put it in the array list with recycler view
Listener dosent working and when i run the app and it just open Response.ErrorListener
i cant find what is wrong with tHAT
AND I HAVE TRIED IN SO MANY DEVICES
private void gitems()
{
String url="http://novindevelopers.ir/jsonarrayrequest.json";
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("در حال دریافت اطلاعات");
progressDialog.setCancelable(false);
progressDialog.show();
Response.Listener<JSONArray> arrayListener = new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response)
{
try {
//JSONObject jsonObject = null;
for (int j = 0; j < response.length(); j++) {
JSONObject jsonObject = response.getJSONObject(j);
String name = jsonObject.getString("name");
String email = jsonObject.getString("email");
String phone = jsonObject.getString("phone");
items.add(new modellitems(name,email,phone));
}
}catch (JSONException e)
{
e.printStackTrace();
}
progressDialog.dismiss();
adaptorr.notifyDataSetChanged();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "this", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
};
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET ,url , null , arrayListener,errorListener );
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}

Android Async Tsk not Executing Properly

I just want to wait in a splash screen until my JSON is processing, but that is not happening. TheonPostExecute() method is executed just after doinbackground(). There is no time to load the whole JSON.
Here is my code. I am getting List size zero first then JSON will start to load.
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
datalist = new ArrayList<>();
Log.e("entering","Enter Inside");
try{
JsonArrayRequest billionaireReq =
new JsonArrayRequest(new ApiURLs().getAll_movies_url()
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", "Response" + response);
//Initialize Gson obj to process jason response
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
// assigning data in model class, we initializing this class as a array type
// because the response is in array format
HomeModel[] getResult = gson.fromJson(response.toString(), HomeModel[].class);
// this loop help us in fetching all the records of model class
for (int i = 0; i < getResult.length; i++) {
Log.e("response", "Model Values" + getResult[i].toString());
//datalist.add(getResult[i]);
datalist.add(getResult[i]);
}
//GlobalData.setGlobal_movie_list(datalist);
Log.e("DataLoded","Record Added");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Request","Error" + error);
}
});
//This is a queue which is used by Volley to lineup requests
AppController.getInstance().addToRequestQueue(billionaireReq);
}
catch (Exception e){
Log.e("Error","Error"+e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("Data","DataSize"+datalist.size());
}
}

How Do I instantly refresh a component of a recyclerview in android studio?

I have a button and when the button is clicked, I would like it to automatically update the text, the catch is that the text is coming from a server and I am parsing it via JSON. My question is how can I automatically update the text when the button is clicked without a complete refresh?
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
String selectedId = currentQuestions.getString("selected");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
blogs.setSelected(selectedId);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
The only thing I have tried it recalling the jsonarray in my listener
public void OnDown(View view) {
CharSequence IdDownVote = ((TextView) ((RelativeLayout) view.getParent()).getChildAt(1)).getText();
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_DOWN = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
public void ClickCardAnswer(View view) {
System.out.println("YOU CLICKED THE CARD");
}
}
Your question is a little ambiguous, but I'll try to answer the two possible problems you might have:
You have updated the item in the adapter but it won't display the new content: use notifyItemChanged(int position) of the adapter class
You want to update the item in the adapter. Apart from the setBloglist() of the adapter class you need to make a method to update a certain item in the dataset (either by position in list or looking it up via id - I usually use the ID version). After update, see point 1 above.

android update custom view in asynctask

Ok, I have a custom view which plays gifs from the internet. Therefor I need to add an url to my view to download the gif. But I can't seem to update my custom view inside my asynctask. I need to add an url string to my custom view gifView.setUrl(). It works in the onCreate Class but it gives me null in asynctask.
Oncreate class
GifView gifView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
id = extras.getInt("id");
String idStr = String.valueOf(id);
String extension = extras.getString("extension");
if(extension.equals(".gif")){
setContentView(R.layout.activity_post_gif);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gifView = (GifView)findViewById(R.id.gifview);
titleStr = (TextView)findViewById(R.id.titleTXT);
postInfo = (TextView)findViewById(R.id.infoTXT);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//the url
new getJsonInfoGif().execute("http://www.website.com/jsonApi");
}else{
Asynctask
public class getJsonInfoGif extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("loading post...");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
return GET(strings[0]);
}
#Override
protected void onPostExecute(String res) {
try {
JSONObject jsonObject = new JSONObject("{'postinfo':[" + res + "]}");
JSONArray jsonArray = jsonObject.getJSONArray("postinfo");
JSONObject obj = jsonArray.getJSONObject(0);
//post title
titleStr.setText(obj.getString("name"));
//category and maker full name
//large image
JSONObject imgObj = obj.getJSONObject("thumbnails");
gifView.setUrl("http://www.website.com/my.gif");
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
GifView.java
public void setUrl(String urlStr){
this.urlStr = urlStr;
invalidate();
requestLayout();
}
public String getUrl(){
return this.urlStr;
}
public void init(final Context context)throws IOException{
setFocusable(true);
movie = null;
movieWidth = 0;
movieHeight = 0;
movieDuration = 0;
final Thread thread = new Thread(new Runnable() {
#Override
public void run(){
try{
Log.d("DEBUG", "URL" + urlStr);
URL url = new URL(urlStr);
try {
HttpURLConnection http = (HttpURLConnection) url.openConnection();
inputStream = http.getInputStream();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
movie = Movie.decodeStream(inputStream);
movieWidth = movie.width();
movieHeight = movie.height();
movieDuration = movie.duration();
((PostActivity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
invalidate();
requestLayout();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
thread.start();
}
Here is the Log from the url, it gives me null if I add the url inside my asynctask in Activity.
11-07 14:41:58.821 5674-6076/svenmobile.tools.showcase D/DEBUG﹕ URLnull
What I want to know is what the problem is and how to solve it if possible.
Thanks in advance, Sven
Maybe you called init() before setUrl().
You can pass it the url in the contructor, or public void init(final Context context, String urlStr)throws IOException{
I also suggest you to move all that network code to doInBackground

Categories