0

I have csv files stored on my server. If I enter the right key (which is a part of URL) I get what I want, but if the entered key was wrong my app crashes. I want to be able to catch the error.

    String url="http://mysite.com/template";
            url=url+et.getText().toString().toLowerCase()+".csv";

            csv.setURL(url);
            if(csv.checkURL()){
                enterToDB();

            }
            else{
                tv.setText("Wrong key");
            }       

and my CSVReader looks like:

 public void setURL(String file){

     try {
        URL url = new URL(file);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    success=true;
        in.close();
    } catch (MalformedURLException e) { success=false;} catch (IOException e) {  success=false;     }
   }

public boolean checkURL(){
    return success;
}

  }
OMG Ponies
  • 300,587
  • 73
  • 490
  • 482
Alanagh
  • 232
  • 5
  • 14

1 Answers1

0

Without the complete minimal code necessary to replicate the problem, and without information about what the specific error is (like a stack trace), I'm just guessing that the setURL/checkURL routines don't exactly do what you want. They appear to assume that openStream will throw an exception if the key in the URL is wrong, but that's not the case. Even if the path or key in the URL is wrong, the HTTP server will still provide a response. The response might not be 200 OK and the response body might not include what you're looking for, but it'll still give a response, and the open stream can be used to read the response.

So, if I understand correctly, you actually want to inspect the contents of the response (including probably the HTTP status code), before deciding whether the "success" is true or false.

Thane posted some code I gave him over in How should I handle server timeouts and error code responses to an http post in Android App?. I recommend reviewing it and seeing if it provides the structure you need to handle successful and failed responses accordingly.

Making sense?

Community
  • 1
  • 1
Programmer Bruce
  • 58,151
  • 6
  • 96
  • 93