Progress Bar is not showing with android picasso callbacks - android

I am using Picasso library for image caching in my app and while these images are loading I want to show a progressbar. I have added a callback for picasso but the progressar isnt showing. Here is my code
public class ShowProduct extends AsyncTask<String,String,ArrayList> {
#SuppressLint("StaticFieldLeak")
private static Context context;
private int width,height;
private JSONObject parsed;
static ArrayList<Data> returno=new ArrayList<>();
private String title,name,id,desc,regular_price,sale_price,code,size_guide_img,fabric,disclaimer,ref_id,ref_type;
static String[] image_info,image_gallery,color_array,size_array;
ShowProduct(Context ctx) {context = ctx;}
#Override
protected ArrayList doInBackground(String... strings) {
String url = strings[0];
getProduct(url);
return returno;
}
private void getProduct(String url) {
JsonObjectRequest mJsonArrayRequest = new JsonObjectRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Log.d("response", response.toString());
parsed = response;
try {
returno = parseJson(parsed);
} catch (ParseException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse errorResponse = error.networkResponse;
if (errorResponse != null && errorResponse.data != null) {
String statusCode = String.valueOf(errorResponse.statusCode);
Log.d("l", "Status code is " + statusCode);
String fullMessage = new String(errorResponse.data);
Log.w("k", "Error message is " + fullMessage);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(mJsonArrayRequest);
}
private ArrayList<Data> parseJson(JSONObject jsonMessage) throws ParseException, JSONException {
if(context.getResources().getConfiguration().orientation==1){
width= getScreenWidth(context); height=getScreenHeight(context)/2-50;
}
else if(context.getResources().getConfiguration().orientation==2) {
width = getScreenWidth(context);
height = getScreenHeight(context) - 200;
}
JSONObject product;
JSONObject attributes;
JSONArray image_array;
JSONArray gallery_array;
JSONArray pa_color_array;
JSONArray pa_size_array;
JSONArray featured_products;
JSONObject similar_products;
ArrayList<Data> images=new ArrayList<>();
ArrayList<Data> similar=new ArrayList<>();
DatabaseOperations DB = new DatabaseOperations(context);
if (jsonMessage != null) {
try {
//Products
product = jsonMessage.getJSONObject("product");
if(product!=null){
id=product.getString("id");
name=product.getString("name");
name=name.replace("&","&");
desc=product.getString("desc");
desc=desc.replace("&","&");
image_array=product.getJSONArray("image_url");
image_info=new String[image_array.length()];
for(int b=0; b<image_array.length();b++) {
image_info[b] = image_array.get(b).toString();
}
gallery_array=product.getJSONArray("gallery");
image_gallery=new String[gallery_array.length()];
for(int b=0; b<gallery_array.length();b++) {
image_gallery[b] = gallery_array.get(b).toString();
}
regular_price=product.getString("regular_price");
sale_price=product.getString("sale_price");
code=product.getString("code");
size_guide_img=product.getString("size_guide_img");
fabric=product.getString("fabric");
disclaimer=product.getString("disclaimer");
attributes = product.getJSONObject("attributes");
pa_color_array=attributes.getJSONArray("pa_color");
color_array=new String[pa_color_array.length()];
for(int b=0; b<pa_color_array.length();b++) {
color_array[b] = pa_color_array.get(b).toString();
}
pa_size_array=attributes.getJSONArray("pa_size");
size_array=new String[pa_size_array.length()];
for(int b=0; b<pa_size_array.length();b++) {
size_array[b] = pa_size_array.get(b).toString().toUpperCase();
}
DB.deletebeforeSaving("Products",id);
DB.put_ProductActivity_Data(DB,"Products",id,name,desc,image_info[0], Arrays.toString(image_gallery),regular_price,sale_price,code,size_guide_img,fabric,disclaimer,Arrays.toString(color_array),Arrays.toString(size_array));
ProductActivity.prod_name.setText(name);
Picasso.with(context)
.load(image_info[0])
//.placeholder(R.drawable.loading)
.error(R.mipmap.ic_launcher)
.resize(width,height)
.centerInside()
.onlyScaleDown()
.into(ProductActivity.prod_img, new Callback() {
#Override
public void onSuccess() {
ProductActivity.prod_img.setVisibility(View.VISIBLE);
ProductActivity.progressBar.setVisibility(View.GONE);
}
#Override
public void onError() {
}
})
;
ProductActivity.prod_img.setContentDescription(image_info[0]);
for (int a=0; a<image_gallery.length;a++){
images.add(new Data(image_gallery[a]));
}
recycleSetHorizonatal(images,context,ProductActivity.horizontal_recycle,R.layout.product_images_scrollview,1);
if (sale_price.equals("null")){
ProductActivity.sale_price.setText(sale_price);
ProductActivity.prod_price.setText(regular_price);
}
else {
ProductActivity.prod_price.setText(regular_price);
ProductActivity.prod_price.setPaintFlags(ProductActivity.prod_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
ProductActivity.sale_price.setVisibility(View.VISIBLE);
ProductActivity.sale_price.setText(sale_price);
}
ProductActivity.prod_desc.setText(desc);
ProductActivity.prod_code.setText(code);
ProductActivity.prod_add_info.setText(fabric);
ProductActivity.prod_col_name.setText(color_array[0]);
ProductActivity.spiner.setPrompt("Select Size");
ArrayAdapter<String> size= new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, size_array);
size.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ProductActivity.spiner.setAdapter(size);
}
//Featured Products
featured_products = jsonMessage.getJSONArray("featured_products");
if(featured_products!=null){
for (int i=0; i<featured_products.length();i++){
similar_products=featured_products.getJSONObject(i);
if(similar_products!=null){
title=similar_products.getString("title");
title=title.replace("&","&");
image_array=similar_products.getJSONArray("image");
image_info=new String[image_array.length()];
for(int b=0; b<image_array.length();b++) {
image_info[b] = image_array.get(b).toString();
}
regular_price=similar_products.getString("regular_price");
int reg_price=Integer.valueOf(regular_price);
sale_price=similar_products.getString("sale_price");
ref_id=similar_products.getString("ref_id");
ref_type=similar_products.getString("ref_type");
DB.deletebeforeSaving("Similar_Products",ref_id);
DB.put_Similar_reference(DB,"Reference",ref_id,id);
DB.put_Similar_products
(DB,"Similar_Products",title,reg_price
,sale_price,image_info[0],ref_id,ref_type);
similar.add(new
Data(ref_id,image_info[0],title,regular_price
,sale_price,ref_type));
}
}
recycleSetHorizonatal(similar,context,ProductActivity.horizontal_recycler_view_feature,R.layout.products,4);
ProductActivity.swipe.setRefreshing(false);
}
DB.close();
} catch (final JSONException e) {
Log.e("parse error", "Json parsing error: " + e.getMessage());
}
}
return null;
}
static void recycleSetHorizonatal(ArrayList<Data> data_to_be_shown, Context context,RecyclerView view, int layout,int values) {
ProductActivity.HorizontalAdapter horizontalAdapter = new ProductActivity.HorizontalAdapter(data_to_be_shown, context,layout, values);
LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
view.setLayoutManager(horizontalLayoutManager);
view.setAdapter(horizontalAdapter);
horizontalAdapter.notifyDataSetChanged();
}
}
XML is here
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/logo_img">
<TextView
android:id="#+id/product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp"
android:layout_marginTop="20dp"
android:textColor="#color/black"
android:text="Product name"
android:gravity="center"
/>
<ImageView
android:id="#+id/prod_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:visibility="gone"
android:layout_below="#id/product_name"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_centerHorizontal="true"
android:visibility="visible"
android:backgroundTint="#color/brumanoGolden"
android:layout_below="#id/product_name"/>
Dependencies
compile 'com.android.volley:volley:1.0.0'
compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
I have updated the code with full asynctask class.

Try to set the visibllity in onPreExecute, maybe there is some problem with accessing the UI thread that is not thrown.
#Override
protected void onPreExecute() {
super.onPreExecute();
ProductActivity.progressBar.setVisibility(View.VISIBLE);
}
Then when you want to make progress invisible, set it this way:
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ProductActivity.progressBar.setVisibility(View.GONE);
}

try below code :
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress(getContext().getString(R.string.uploading), getContext(), false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
cancelProgress();
}
public static void showProgress(String message, Context context, boolean cancellable) {
if (context == null)
return;
if (checkProgressOpen())
return;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage(message == null ? "Please wait..." : (message));
dialog.setCancelable(cancellable);
try {
dialog.show();
} catch (Exception e) {
// catch exception for activity paused and dialog is going to be
// show.
}
}
public static boolean checkProgressOpen() {
if (dialog != null && dialog.isShowing())
return true;
else
return false;
}
public static void cancelProgress() {
if (checkProgressOpen()) {
try {
dialog.dismiss();
} catch (Exception e) {
}
dialog = null;
}
}

Related

Android Asynctask arraylist always returns 0

I have an activity where I have a URL and with the Volley Library , I am fetching the JSON data in an ArrayList of Objects of Model Class DmIncomingTest. Now, I pas URL to the checkLiveQuiz() method, even after getting data from server and adding it to the ArrayList, the size of ArrayList is always 0. I am sharing the code here:
private List<DmInComingTest> inComingTestList;
setContentView(R.layout.activity_no_live_quiz);
......
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private Context context;
#Override
protected void onPreExecute() {
inComingTestList= new ArrayList<DmInComingTest>();
// dialog = ProgressDialog.show(NoLiveQuiz.this, "Please wait..", "Doing stuff..", true);
}
#Override
protected Void doInBackground(Void... voids) {
checkLiveQuiz();
return null;
}
#Override
protected void onPostExecute(Void result) {
// Toast.makeText(NoLiveQuiz.this,"Size of inComingTestList :"+inComingTestList.size(),Toast.LENGTH_LONG).show();
if(inComingTestList.size()==0)
{
Toast.makeText(NoLiveQuiz.this,"Size of inComingTestList :"+inComingTestList.size(),Toast.LENGTH_LONG).show();
}
else
{
startActivity(new Intent(NoLiveQuiz.this,LiveQuiz.class));
}
// dialog.dismiss();
}
}
public void checkLiveQuiz()
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url_live_quiz, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
DmInComingTest inComingTest = new DmInComingTest();
inComingTest.setTitle(jsonObject.getString("title"));
inComingTest.setTotal_questions(jsonObject.getString("qcount"));
inComingTest.setDated(jsonObject.getString("date_format(dated,'%d.%m.%Y')"));
inComingTest.setStartTime(jsonObject.getString("starttime"));
inComingTest.setEndTime(jsonObject.getString("endtime"));
inComingTest.setDuration(jsonObject.getInt("duration"));
inComingTest.setMaxMarks(jsonObject.getInt("maxmarks"));
if(validateTest(jsonObject.getString("date_format(dated,'%d.%m.%Y')"),jsonObject.getString("starttime"),jsonObject.getString("endtime"),jsonObject.getInt("duration")))
{
inComingTestList.add(inComingTest);
Toast.makeText(NoLiveQuiz.this,"Test Added: "+ inComingTestList.size(),Toast.LENGTH_LONG).show();
// flag=1;
// Toast.makeText(MainActivity.this,"Flag Inner="+flag,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
// adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
// progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private boolean validateTest(String testDate, String startTime, String endTime, int duration)
{
Date oldDate, newDate,newDate1;
String oldTime,newTime,newTime1;
long diff=0;
long oldLong=0;
long newLong=0;
long newLong1=0;
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
formatter.setLenient(false);
Calendar c = Calendar.getInstance();
oldTime=formatter.format(c.getTime());
// Toast.makeText(MainActivity.this, ""+oldTime, Toast.LENGTH_SHORT).show();
newTime=testDate +", "+startTime+":00";
newTime1=testDate +", "+endTime+":00";
// Toast.makeText(MainActivity.this, ""+newTime, Toast.LENGTH_SHORT).show();
try {
oldDate = formatter.parse(oldTime);
newDate = formatter.parse(newTime);
newDate1=formatter.parse(newTime1);
oldLong = oldDate.getTime();
newLong = newDate.getTime();
newLong1=newDate1.getTime();
diff = newLong - oldLong;
} catch (ParseException e) {
e.printStackTrace();
}
//long timer= (long) Long.parseLong(String.valueOf(diff));
//Toast.makeText(IncomingActivity.this, ""+timer, Toast.LENGTH_SHORT).show();
if(oldLong>newLong && oldLong<newLong1)
{
return true;
}
else
return false;
}

sorting a ListView by number

sort ListView Android by float number ...
I have a listview price type float display of a mysql database ,,
I want to sort it (by order) but I have not found a solution ..
how can I do it please !!!
it's the code of my listView with prices done !!
private class GetHttpResponse extends AsyncTask<Void, Void, Void>{
public Context context;
String ResultHolder;
List<subjects> subjectsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServiceObject = new
HttpServicesClass(ServerURL);
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
subjectsList = new ArrayList<subjects>();
for(int i=0; i<jsonArray.length(); i++)
{ subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
subjects.SubjectName = jsonObject.getString("tarif");
subjectsList.add(subjects);
} }
catch (JSONException e) {
e.printStackTrace();
} } } else
{
Toast.makeText(context, httpServiceObject.getErrorMessage(),
Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{ progressBarSubject.setVisibility(View.GONE);
SubjectListView.setVisibility(View.VISIBLE);
if(subjectsList != null)
{
ListAdapterClass adapter = new ListAdapterClass(subjectsList,
context);
SubjectListView.setAdapter(adapter);
SubjectListView.setOnItemClickListener(new
AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int pos, long id) {
String selectedItem =
parent.getItemAtPosition(pos).toString();
Toast.makeText(TechnicienActivity.this,selectedItem,
Toast.LENGTH_SHORT).show();
Intent intent = new
Intent(getApplicationContext(),Main2Activity.class);
intent.putExtra("Position" , String.valueOf(id));
startActivity(intent);
} }); } } }
You can sort the list by using
Collections.sort(list);
and then set this to the listview.
Example;
subjectsList.add(subjects);
Collections.sort(subjectsList);

Material spinner can't support v4 device. How can I fix it?

I am using material spinner library com.github.ganfra:material-spinner:1.1.0. This spinner working fine all device. But not working with version 4. How can I fix this issue?
Here is my XML Code:
<fr.ganfra.materialspinner.MaterialSpinner
android:id="#+id/Mobile_money_spinner_network"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerVertical="true"
android:clickable="false"
android:focusableInTouchMode="false"
android:background="#drawable/edittext_background"
android:popupBackground="#ffffff"
android:spinnerMode="dropdown"
android:textAlignment="textStart"
android:textColor="#color/black"
android:textSize="15sp"
android:textStyle="bold"
app:ms_alignLabels="false"
app:ms_arrowColor="#color/black"
app:ms_arrowSize="15dp"
app:ms_floatingLabelColor="#color/spinner_floatlabel_color"
app:ms_highlightColor="#android:integer/config_shortAnimTime"
app:ms_hint="#string/Mobile_lable_network_textview"
app:ms_multiline="false"
app:ms_thickness="0dp"
app:ms_baseColor="#color/spinner_hint_color"
style="#style/Animation.AppCompat.DropDownUp"/>
Java file code::
Spinner_network.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner_network.setFloatingLabelText(getResources().getString(R.string.Mobile_lable_network_selected_textview));
if (!Spinner_network.getSelectedItem().toString().equalsIgnoreCase(getString(R.string.Mobile_lable_network_textview))) {
if (Spinner_network.getSelectedItem().toString().equalsIgnoreCase("vodafone")){
System.out.println("*****venki****network_type*****url_inside***"+Spinner_network);
Rl_token.setVisibility(View.VISIBLE);
}
else{
Rl_token.setVisibility(View.GONE);
}
isNetworkSelected = true;
Mobile_njetwork_selected = Spinner_network.getSelectedItem().toString();
} else {
isNetworkSelected = false;
Mobile_njetwork_selected = getResources().getString(R.string.Mobile_lable_network_textview);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//-----------------------Mobile Network----------------
private void postRequest_mobile_network(String Url) {
dialog = new Dialog(MobileMoneyPay.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loading);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
TextView dialog_title = (TextView) dialog.findViewById(R.id.custom_loading_textview);
dialog_title.setText(getResources().getString(R.string.action_processing));
System.out.println("-------------mobile network Url----------------" + Url);
HashMap<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("user_id", SuserId_intent);
jsonParams.put("ride_id", SrideId_intent);
System.out.println("-------------------mobile_payment_rideId" + SrideId_intent);
mRequest = new ServiceRequest(MobileMoneyPay.this);
mRequest.makeServiceRequest(Url, Request.Method.POST, jsonParams, new ServiceRequest.ServiceListener() {
#Override
public void onCompleteListener(String response) {
System.out.println("-------------mobile network Response----------------" + response);
String Sstatus = "";
try {
JSONObject object = new JSONObject(response);
Sstatus = object.getString("status");
if (Sstatus.equalsIgnoreCase("1")) {
JSONObject response_object = object.getJSONObject("response");
if (response_object.length() > 0) {
Object check_network_object = response_object.get("network_type");
if (check_network_object instanceof JSONArray) {
JSONArray network_array = response_object.getJSONArray("network_type");
if (network_array.length() > 0) {
Mobilenwtwork_array.clear();
for (int i = 0; i < network_array.length(); i++) {
MobileNetworkPojo network_pojo = new MobileNetworkPojo();
network_pojo.setNetworkType(network_array.getString(i));
Mobilenwtwork_array.add(network_array.getString(i));
}
if (Spinner_network.getSelectedItem().toString().equalsIgnoreCase("vodafone")){
System.out.println("*****venki****network_type*****url_inside***"+Spinner_network);
Rl_token.setVisibility(View.VISIBLE);
}
else{
Rl_token.setVisibility(View.GONE);
}
isNetworkAvailable = true;
} else {
isNetworkAvailable = false;
}
}
} else {
isNetworkAvailable = false;
}
} else {
isNetworkAvailable = false;
}
if (Sstatus.equalsIgnoreCase("1") && isNetworkAvailable) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MobileMoneyPay.this,
R.layout.mobile_network_spinner_dropdown, Mobilenwtwork_array);
Spinner_network.setAdapter(adapter);
// Spinner_network.setItems(Mobilenwtwork_array);
} else {
String Sresponse = object.getString("response");
Alert(getResources().getString(R.string.alert_label_title), Sresponse);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
#Override
public void onErrorListener() {
dialog.dismiss();
}
});
}

interface between fragment and activity not working

I want pass my String json from fragment to another activity so make interface between fragment and activity but when lunch app get null exception from this line from my fragment :adapterCalljson.MethodCallbackjson(jsonStr);
this is my try so far :
interface class :
public interface AdapterCalljson {
void MethodCallbackjson(String jsonn);
}
fragment :
public class maghalat extends Fragment {
private View myFragmentView;
private RecyclerView recyclerView;
private DataAdapter adapter;
private String TAG = MainActivity.class.getSimpleName();
public ProgressDialog pDialog;
List<jsonContent> listcontent=new ArrayList<>();
public int dog=1;
public String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
public int id;
AdapterCalljson adapterCalljson;
public String json;
public String jsonStr;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
adapterCalljson.MethodCallbackjson(json);
asyncRun();
return myFragmentView;
}
public void asyncRun(){
if(isNetworkConnected()) {
new GetContacts().execute();
} else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
jsonContent.content=c.getString("content");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
jsonContent.curpage=dog;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(), listcontent, new AdapterCallback() {
#Override
public void MethodCallbackgo(String data) {
Integer s=null;
try {
s= Integer.valueOf(data);
}catch (NumberFormatException e)
{
}
if (s!=null && s>=1 && s<=id)
{
dog= Integer.parseInt(data);
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else
{
Toast.makeText(getActivity().getApplicationContext(),"صفحه پیدا نشد",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbacknext() {
if (dog<id)
{
dog += 1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else {
Toast.makeText(getActivity().getApplicationContext(),"این آخرین صفحه است",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbackprev() {
if (dog!=1)
{
dog-=1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else{
Toast.makeText(getActivity().getApplicationContext(),"این اولین صفحه است",Toast.LENGTH_SHORT).show();
}
}
});
recyclerView.setAdapter(adapter);
json=jsonStr;
}
}
You haven't assigned an object to adapterCalljson. Assuming you're implementing AdapterCalljson in the host activity, assign it from the context onAttach:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
Firstly, your Activity containing the Fragment must implement that interface.
public class MainActivity implements AdapterCalljson {
#Override
void MethodCallbackjson(String jsonn) {
doSomethingWithJson(jsonn);
}
private void doSomethingWithJson(String json) {
}
// onCreate...
}
Next, I would recommend you create the RecyclerView outside the AsyncTask. You don't need to save the myFragmentView variable.
Additionally, you can't call the callback yet. There is no data.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.maghalat, container, false);
// recyclerView = rootView.findViewById
// adapter = ...
// recyclerView.setAdadpter...
asyncRun(); // This happens in the background. There is no JSON yet
return rootView;
}
Then, perhaps you should have doInBackground return the JSON string so you don't have to store it as a class variable.
The last argument is the return type.
public class GetContacts extends AsyncTask<Void, Void, String>
So, then it is public String doInBackground(Void params...) {} and public void onPostExecute(String result) {}.
In other words, don't just return null from doInBackground
#Override
protected String doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
// Parse JSON more...
return jsonStr;
}
And then you should be able to use your callback.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (adapterCalljson != null) {
adapterCalljson.MethodCallbackjson(result);
} else {
Log.w("Callback Error", "callback not assigned");
}
// adapter.notifyDataSetChanged(); // Might want this
}

GridView not updating its child views after adapter gets new items

I've been looking around everywhere in trying to find out why my code was causing an issue. I have a GridView that has an ArrayAdapter which pulls photos down with an AsyncTask. I can see the items being updated but when I try to update the adapter the GridView doesn't seem to update with the new view.
This is the relevant code that does the work...
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
//String id = object.getString("id");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
if(gridViewAdapter != null){
gridViewAdapter.clear();
gridViewAdapter.addAll(list);
gridViewAdapter.notifyDataSetChanged();
gridView.invalidateViews();
} else {
gridViewAdapter = new GridViewAdapter(getActivity(), R.layout.gridview_item, list);
gridView.setAdapter(gridViewAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}
I would really appreciate any help if possible. Trying to get the app out before new years :).
Maybe If you could tell me why this happens so It won't cause an issue again and other will see.
EDIT: Added a bit more code which has it refreshing after I click the button twice.
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
pictureAdapter = new PictureAdapter(getActivity(), list);
gridView.setAdapter(pictureAdapter);
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list);
gridView.invalidate();
progressDialog.dismiss();
}
}
Adapter:
public class PictureAdapter extends BaseAdapter {
private ArrayList<ImageItem> items;
private Context context;
private TextView titleText;
private ImageView itemImage;
public PictureAdapter(Context context, ArrayList<ImageItem> items){
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.gridview_item, parent, false);
titleText = (TextView) v.findViewById(R.id.text);
itemImage = (ImageView)v.findViewById(R.id.image);
titleText.setText(items.get(position).getTitle());
Picasso.with(context).load(items.get(position).getUrl()).fit().into(itemImage);
return v;
}
public void updateItemList(ArrayList<ImageItem> newItemList){
this.items = newItemList;
notifyDataSetChanged();
}
}
Try the below lines in post execute
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list,gridView);
progressDialog.dismiss();
}
Now in your updateItemList
public void updateItemList(ArrayList<ImageItem> newItemList,GridView gridView){
this.items = newItemList;
gridView.setAdapter(null);
gridView.invalidateViews();
gridView.deferNotifyDataSetChanged();
gridView.setAdapter(list);
}
Why you are calling Volley request from AsyncTask as Volley perform request on NetworkThread.
Remove AsyncTask and directly call Volley.
Just try this. Hope it helps.
private ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
progressDialog.show();
fetchJsonResponse(url);
}
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
pictureAdapter.notifyDataSetChanged();
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}

Categories

Resources