问题
I am trying to fetch the contents of this url. The contents will get changed for each refresh.
I am wrote my code to fetch the content and display it in my app using TextView by a Button Click.
But it takes more time ( Minimum 2 seconds , Maximum 6 seconds ) to get the data and display into Textview. So what change do i need in my code to make it efficiant and reduce the delay.
Here is my code,
( Fetching done in getData() method using URLConnection method )
public class MainActivity extends AppCompatActivity {
TextView resultView;
String TAG="MainActivity kbt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults();
resultView = (TextView) findViewById(R.id.result);
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
Button insert=(Button) findViewById(R.id.button);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void getData() throws IOException {
String result = "";
InputStream isr = null;
URLConnection urlConnection = null;
URL url = new URL("http://kbtganesh.16mb.com/index.php");
urlConnection = url.openConnection();
isr =urlConnection.getInputStream();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
resultView.setText(result);
}
catch(Exception e) {
Log.e("log_tag", "Couldn't set text, damnit.");
}
}
}
Thanks in Advance (:
回答1:
Try test it in on a local server on your computer, instead of a remote one like you have. Sometimes it's just slow internet speed slowing the page down, and nothing to do with the code.
回答2:
Remove the StrictMode.enableDefaults();
instead use the AsyncTask to fetch the data from the network as doc says
"Keeping disk and network operations off the main thread makes for much smoother, more responsive applications"
check doc here StrictMode Doce
Else everything looks fine you can also check the improvment on the webservice end check the query it can be optimized as there is a very less data your api is returns
来源:https://stackoverflow.com/questions/34327689/slow-fetching-of-contents-from-url