I'm new to Android and am making a global a high score feature for a simple minesweeper game I've made. I made the highscore feature using PHP so it just visits a URL with some get parameters and the score is saved automatically. To get the score is similar it should read the JSON contents of the URL into a String.
I know you can't access the network from the main thread so I created a AsyncTask. I then call it from my activity.
But I still get the error android.os.NetworkOnMainThreadException
Below is the AsyncTask class
package net.as93.minesweeper.util;
import android.os.AsyncTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Eventupdate extends AsyncTask<String, Void, Void> {
String pageContents;
@Override
protected Void doInBackground(String... url) {
try {
Thread.sleep(4000);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url[0]);
HttpResponse response = httpClient.execute(httpGet,localContext);
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null) {
result += line + "\n";
}
pageContents = result;
} catch (InterruptedException e) {
System.out.println(e);
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
public String getPageContents() {
return pageContents;
}
}
And here is the saveScore() method that should call the AsyncTask
public void saveScore(ScoreObj scoreObj) throws IOException {
String usersname = scoreObj.getUsersName();
String time = Integer.toString(scoreObj.getTime());
String mode = scoreObj.getGameMode();
String timed = ((scoreObj.isTimed()) ? "true" : "false");
String myUri = "http://android.as93.net/minesweeper/setscore.php?usersname="+usersname+"&time="+time+"&timed="+timed+"&mode="+mode;
try{
Eventupdate eu = new Eventupdate();
eu.execute(myUri);
eu.doInBackground(myUri);
}catch (Exception e){System.out.println("Another error: "+e);}
}
I have already added <uses-permission android:name="android.permission.INTERNET"/>
to the manifest
I have been trying to figure this out for so many hours, can't find the solution on the internet anywhere. Thanks in advance for any suggestions