I using the class async to download and upload data in two activitys. The upload is not working and I dunno why.
This one works fine!
new DatabaseConnector(true).execute("http://web2page.ch/apps/FruityNumber/highscoreShow.php");
But this one not!
new DatabaseConnector(false).execute("http://web2page.ch/apps/FruityNumber/highscoreUpload.php?user=test7&highscore=timer7");
But if I remove "if" in the class it works fine... Does someone understand why?
public DatabaseConnector(Boolean download) {
this.download = download;
}
#Override
protected Long doInBackground(String... params) {
try {
try {
//Verbinden
url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
if (download) {
//Falls die App nochmal geladen wird, sind die Daten nur einmal enthalten. Darum leeren.
arrayList.clear();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
arrayList.add(line);
}
} else {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
See comments in code
new DatabaseConnector(false) means
public DatabaseConnector(Boolean download) {
this.download = false; // see here
}
so
if (download) { // this won't execute because download == false
and
else {
// there is nothing here to do!
}
I'm not sure how you expect anything different..
To solve this will depend on why you are even using the boolean variable. If there is no reason for it then remove that and don't pass it anything.
Otherwise, it sounds like you want to put the upload code in the else{}
Related
I'm using Asynctask to pass the parameters of API. The Asynctask executing but the String Response in Asynctask PostExecute giving me a null for a device with SDK 23 and below. But when the device is equal or higher to SDK24(Nougat), it works perfectly and the data are being sent to the API however when the SDK is 23 and lower data are not being sent to API. Does anyone encounter this problem? Please enlighten me what I miss in my code or I do wrong code. Massive thank you.
private class sendToServerOfficial extends AsyncTask<String,Void,String> {
int statusCodeone;
String convert_txt_et_username = et_username.getText().toString();
String convert_txt_content = et_content.getText().toString();
#Override
protected String doInBackground(String... strings) {
try {
urlURL = new URL("http://www.testingsite.com/api/sendServer?/ip="+getIPAddress+"&phone_num="+getMobilePhoneNumber+"&user_text="+convert_txt_et_username+"&content_text="+convert_txt_content);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlURL.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","UTF-8");
httpURLConnection.connect();
statusCodeone = httpURLConnection.getResponseCode();
if (statusCodeone == 200) {
InputStream it = new BufferedInputStream(httpURLConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
buff.close();
read.close();
return dta.toString();
}
}
catch (ProtocolException e) { e.printStackTrace(); }
catch (MalformedURLException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return null;
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(MainActivity.this, response + "Form is submitted already" + urlURL, Toast.LENGTH_LONG).show();
txt_inputURL.setEnabled(true);
btnClick.setClickable(true);
txt_inputURL.getText().clear();
}
}
I am downloading JSON Content from server in the MainActivity and passing the JSON from MainActivity to ListActivity, the problem here is I have added a sleep time of 10s in the backend server i.e. Php from where the data is fetched. Since, the response will the delayed I would expect that screen opens and waits until the response comes and move to next screen.
But what is happening is the screen goes white/black completely untill the response is recieved and ListActivity is loaded, the problem here is the MainActivity is never visible. Below is code for the same:
MainActivity
JSONData jsonData = new JSONData();
String jsonList = jsonData.fetchList();
Intent intent = new Intent(getApplicationContext(),ListActivity.class);
intent.putExtra("jsonList",jsonList);
startActivity(intent);
finish();
JSON Data class
public String fetchList() {
try {
String list = new DownloadJSONData().execute(listURL).get().toString();
return list;
} catch (Exception e) {
return "";
}
}
private class DownloadJSONData extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
you are using get() method which accquires the main thread or ui thread untill the async task is completed
you should avoid using get() and also can use progress dialog in onPreExecute for displaying progression on network call to user
Not very easy to explain:
I have this app for streaming online radio. The problem was first with m3u format (which android somehow cannot normally stream like pls), so I have to parse the url with this ParserM3UToURL (that I found somewhere)... like this:
Uri u = Uri.parse(ParserM3UToURL.parse(STREAM_URL, sdkVersion, c));
player = MediaPlayer.create(c, u);
Mostly it works ok but it has one bug...
I'm testing this on two devices one old 2.2.2. (api level 17), other 4.3 (api level 23). Older device works fine. It can stream radio over wifi or mobile data, but the newer device has some problem with streaming over mobile data (on wifi it works ok). The application crashes because the parse function returns null: http://pastebin.com/ghbAqGzM
And I assume there are many more phones with 4.x than 2.x android. Which of course is very painful for me. Somehow I have to fix this.. So I really hope somebody will have some clue about this. I hope my explanation was not to confusing...
This is the ParserM3UToURL.parse() function:
public static String parse(String paramString, int sdkVersion, Context c)
{
try
{
StrictModeWrapper.init(c);
HttpURLConnection localHttpURLConnection = (HttpURLConnection)new URL(paramString).openConnection();
InputStream localInputStream = localHttpURLConnection.getInputStream();
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));
StringBuffer localStringBuffer = new StringBuffer();
while (true)
{
String str = localBufferedReader.readLine();
if (str == null)
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
break;
}
if (str.contains("http"))
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
return str;
}
localStringBuffer.append(str);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Below is what i worked on to stream radio (m3Urls). The example below uses a service. When the service is started, the url is parsed. Note that in the onPostExecute, parsed file is prepared. Once the file is prepared(completed buffering), the file is played/started and stopped upon completion.
public class BackgroundRadioService extends Service implements
OnCompletionListener, OnPreparedListener{
MediaPlayer mediaPlayer;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
parseM3uUrlAndPrepare("http://listen.radionomy.com/andalousse.m3u");
return START_STICKY;
}
private void parseM3uUrlAndPrepare(final String url){
AsyncTask<String, Integer, String> asyn = new AsyncTask<String, Integer, String>(){
HttpClient httpClient;
HttpGet getRequest;
HttpResponse httpResponse = null;
String filePath = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
httpClient = new DefaultHttpClient();
getRequest = new HttpGet(url);
}
#Override
protected String doInBackground(String... params) {
try {
httpResponse = httpClient.execute(getRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(httpResponse != null)
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
} else {
InputStream inputStream = null;
try {
inputStream = httpResponse.getEntity().getContent();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
//Log.v("PLAYLISTLINE", "ORIG: " + line);
if (line.startsWith("#")) { // Metadata
} else if (line.length() > 0) {
filePath = "";
if (line.startsWith("http://")) { // Assume it's a full URL
filePath = line;
} else { // Assume it's relative
try{
filePath = getRequest.getURI().resolve(line).toString();
}catch(IllegalArgumentException e){
}catch(Exception e){
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepareAsync(); //this will prepare file a.k.a buffering
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
asyn.execute("");
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
}//end of Service class declaration
Note: This ignores playlists hence assumes the m3u parsed will return only one file. Let me know if you would like to handle playlists so I modify my answer :)
I solved it thanks to this question's comments: POST request failing when in 3G
The problem was actually with proxies on 3G. So if proxies are disabled, no weird http requests.
I modified my code a little. Thanks to Nana's answer I no longer need a m3u parser. I also no longer use HttpClient but HttpURLConnection instead. So when calling URL.openConnection() I add the Proxy.NO_PROXY parameter to that function and bam!
So the solution is "use HttpURLConnection not HttpClient and add NO_PROXY parameter":
conn = (HttpURLConnection) the_url.openConnection( Proxy.NO_PROXY );
I'm having an issue on multiple devices where when the device isn't interacted with for a period of time, my HttpUrlConnection's don't operate as expected. The projects target platform is Android 4.0.3.
Below is an example of how I'm using HttpUrlConnection.
new AsyncRequestDTOBaseItemArray(callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
The actual AsyncTask
public class AsyncRequestDTOBaseItem extends AsyncTask<String,String,Object> {
HttpURLConnection connection;
InputStream inStream;
IApiCallback callback;
public AsyncRequestDTOBaseItem(IApiCallback callback) {
this.callback = callback;
}
#Override
protected Object doInBackground(String... uri) {
try {
URL url = new URL(uri[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.addRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.connect();
String encoding = connection.getContentEncoding();
// Determine if the stream is compressed and uncompress it if needed.
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
inStream = new GZIPInputStream(connection.getInputStream());
} else {
inStream = connection.getInputStream();
}
if (inStream != null) {
InputStreamReader isr = new InputStreamReader(inStream);
Gson gson = new Gson();
try {
DTOBaseItem item = gson.fromJson(isr, DTOBaseItem.class);
return item;
} catch (Exception e) {
Log.i("AsyncRequestDTOBaseItem", "Exception");
if (e != null && e.getMessage() != null) {
Log.e("AsyncRequestDTOBaseItem", e.getMessage());
}
} finally {
inStream.close();
}
}
} catch (SocketTimeoutException e) {
Log.i("AsyncRequestDTOBaseItem", "Socket Timeout occured");
} catch (IOException e) {
Log.i("AsyncRequestDTOBaseItem","IOException");
if (e != null && e.getMessage() != null) {
Log.i("AsyncRequestDTOBaseItem",e.getMessage());
}
} finally {
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(Object result) {
callback.Execute(result);
}
}
I don't see any issues with the above code unless the device has been inactive. When the device has been inactive the last code line that executes is
String encoding = connection.getContentEncoding();
I've also gone into the wifi settings and made sure that my wifi doesn't sleep. I thought at first it might be that the wifi reconnecting was creating this issue.
It looks like the issue may have been the server not sending data back.
I added connection.setReadTimeout(5000); and now the issue seems to have gone away.
This question was asked and answered some time ago link. However the answer did not help me yet. I am in sort of the same position as the OP of the other post:
I have an Asynctask in which I make a connection to a certain website, however, most of the time the connection will take some time due to a laggy internetconnection.
I want the user to be able to stop trying to connect at any time.
public class DownloadWebHtml extends AsyncTask<String, Void, Map<String,ArrayList<ArrayList<String>>>> {
HttpURLConnection con = null;
#Override
protected void onPreExecute(){
Button but = (Button) findViewById(301);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel(true);
con.disconnect();
}
});
}
#Override
protected Map<String, ArrayList<ArrayList<String>>> doInBackground(String... urlcodes) {
//stuff
BufferedReader in = null;
try {
URL url = new URL("some url");
con = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(con.getInputStream(),Charset.forName("ISO-8859-1")));
String line = "";
while ((line = in.readLine()) != null && !isCancelled()) {
html.add(line);
}
in.close();
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
} finally {
con.disconnect();
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.d("gettxt", e.getMessage());
}
}
}
if(!html.isEmpty()) {
return //stuff;
}
return null;
}
#Override
protected void onCancelled(){
//cancellation
}
//onpostexecute doing stuff
}
Whenever the button is pressed the whole AsyncTask will by cancelled only after a connection has been made.
Is it possible to immediately stop the whole process on a button press?
Can it be done using the default httpurlconnection?
I tried using the disconnect to trigger an exception while the con.getInputStream is busy, but it failed to work.
I recommend switching to Apache's HTTP Components. It works a charm, and has a thread-safe abort method, as outlined here.