Search code examples
javaandroidandroid-activityjsonobjectrequest

How to stop receiving data from a web server?


I have an Activity that receives and displays information from the web server and saves it to the database and, if it has already received the information once, it will read from the database.

There is no problem running the program, only when the user enters the activity and still does not receive the information from the server, exit the activity, in another Activity the application crashes.

This problem is to quit the activity because when staying in activity and loaded data completely, we have not any problems. also when reading data from the database we have not any problems.

How can stop receive data when the user quit the activity or solve this problem form another way.

This is my activity codes:

public class ShowProduct extends AppCompatActivity {
private RequestQueue mQueue;
private String id;
private Products products;
private DatabaseHelper databaseHelper;
private ProgressBar progressBar;
private Typeface IranSans,IranSansBold;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_product);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

    databaseHelper = new DatabaseHelper(this);
    products  = new Products();
    progressBar = (ProgressBar)findViewById(R.id.progressBar);
    IranSans = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb.ttf");
    IranSansBold = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb_Bold.ttf");


    Bundle extras = getIntent().getExtras();
    id= extras.getString("id");
    try {
        if (databaseHelper.dbContentChecker(id)) {
            if (connectionCheck() == false){
                Intent intent = new Intent(this, NoInternetConnection.class);
                startActivity(intent);
            }
            String url = "https://website.com/webserver/?id=" + id;
            mQueue = Volley.newRequestQueue(this);
            jsonParse(url);
        } else {
                products = databaseHelper.getOneProduct(id);
                showFromDB(products);
        }
    }catch (Exception ex){
    }


    //footer set
    Footer footer = new Footer();
    footer.footerSet(ShowProduct.this, this);
}

private void showFromDB(Products products) {
    TextView tx = (TextView)findViewById(R.id.title);
    tx.setTypeface(IranSansBold);
    tx.setText(products.getName());
    ImageView im = (ImageView)findViewById(R.id.image);
    Glide.with(ShowProduct.this)
            .asBitmap()
            .load(products.getImage())
            .into(im);
    TextView tc = (TextView)findViewById(R.id.content);
    tc.setTypeface(IranSans);
    tc.setText(Html.fromHtml(products.getContent()));
    progressBar.setVisibility(View.GONE);

}


private void jsonParse(String url) {
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray = response.getJSONArray("send");

                        JSONObject send = jsonArray.getJSONObject(0);

                        String title = send.getString("title");
                        String image = send.getString("image");
                        String content = send.getString("content");
                        TextView tx = (TextView)findViewById(R.id.title);
                        tx.setTypeface(IranSansBold);
                        tx.setText(title);
                        ImageView im = (ImageView)findViewById(R.id.image);
                        Glide.with(ShowProduct.this)
                                .asBitmap()
                                .load(image)
                                .into(im);
                        TextView tc = (TextView)findViewById(R.id.content);
                        tc.setTypeface(IranSans);
                        tc.setText(Html.fromHtml(content));



                        //Save in Database
                        try {
                            products.setProductId(id);
                            products.setName(title);
                            products.setImage(image);
                            products.setContent(content);
                            databaseHelper.editProduct(products);
                        }catch (Exception ex){
                            Toast.makeText(ShowProduct.this, "Error DB", Toast.LENGTH_SHORT).show();
                        }

                        progressBar.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    mQueue.add(request);
    //Toast.makeText(getApplicationContext(), ""+Temp , Toast.LENGTH_SHORT).show();

}



public boolean connectionCheck() {
    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
        //we are connected to a network
        return true;
    }
    else
        return false;

}
}

Solution

  • First of all you should think about your architecture. Handling fetching data inside an Activity is not a good practice. Look at MVVM or MVP and try to put your data fetching logic in another layer.

    For your specific problem you should try to cancle the request in the onStop() method of the Activity, see:

    https://developer.android.com/training/volley/simple#cancel