Pato
Pato

Reputation: 61

Android AsyncTask doInBackground works in 1 phone but not in other

I have an app that works OK in my Samsung Galaxy S7, version 7.0, API 24. But when i tried it in a Huawei CAM-L03, version 6.0, API 23 it doesnt work.

Basically i have a class like this:

public class Sender extends AsyncTask {...}

That have the methods onPreExecute, doInBackground and onPostExecute, for comunication with a php file using internet. When i run it in the Samsung Galaxy S7, and do a Toast.makeText, for showing text on screen in every method, it works pretty well and fine. But when i run it in the Huawei CAM-L03, only shows me text from onPreExecute and onPostExecute, but never enter to doInBackground, and i don't know why.

To call the class i do this:

Sender s = new Sender(MainActivity.this, URL_Total);

s.execute();


I don't know if is the version, the SDK, or something else. Any help is appreciated.

Here is my build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.pruebainsp"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.android.support:design:26.1.0'
    implementation files('libs/PhotoUtil.jar')
    implementation files('libs/GenAsync.1.2.jar')
}


EDIT 1: The toast message is not really the problem.. i only add them for the view, only to check the methods. The real trouble is that DoInBackground dont run or do anything.

Here is the code of the Sender class. With the Samsung Galaxy S7 it enters to if (MainActivity.ResponseWeb != null), but in the Huawei CAM-L03 the ResponseWeb is always null, so every time i got the message Toast.makeText(c, "Error: response " + MainActivity.ResponseWeb , Toast.LENGTH_SHORT).show();, and never go to do private String send() for the connection, because doInBackground dont work here (ONLY IN THE HUAWEI PHONE).

GO TO EDIT 2


EDIT 2: I update the code with the logs, so here it is:

public class Sender extends AsyncTask<Void,Void,String> {
    Context c;
    String urlAddress;
    ProgressDialog pd;
    String fileTodosUsers = "TodosUsuarios";

    private static final String TAG = Sender.class.getSimpleName();
    /*
            1.OUR CONSTRUCTOR
    2.RECEIVE CONTEXT,URL ADDRESS AND EDITTEXTS FROM OUR MAINACTIVITY
    */
    public Sender(Context c, String urlAddress) {
        this.c = c;
        this.urlAddress = urlAddress;
        //Log.v(TAG, "Mensaje 2");
    }
    /*
   1.SHOW PROGRESS DIALOG WHILE DOWNLOADING DATA
    */
    @Override
    protected void onPreExecute() {
        Log.i(TAG, "OnPre");
        super.onPreExecute();
        pd=new ProgressDialog(c);
        pd.setTitle("En Proceso");
        pd.setMessage("Procesando datos...Espere por favor");
        pd.show();
    }
    /*
    1.WHERE WE SEND DATA TO NETWORK
    2.RETURNS FOR US A STRING
     */
    @Override
    protected String doInBackground(Void... params) {
        Log.i(TAG, "doInBack");
        return this.send();
    }
    /*
  1. CALLED WHEN JOB IS OVER
  2. WE DISMISS OUR PD
  3.RECEIVE A STRING FROM DOINBACKGROUND
   */
    @Override
    protected void onPostExecute(String response) {
        Log.i(TAG, "onPost");
        super.onPostExecute(response);
        MainActivity.ResponseWeb = response;

        if (MainActivity.ResponseWeb != null) {
         //...
         //HERE CODE DO SOME STUFF
         //...
        }
        else {
            Toast.makeText(c, "Error: response " + MainActivity.ResponseWeb , Toast.LENGTH_SHORT).show();
        }
        pd.dismiss();
    }
    
    
    /*
    SEND DATA OVER THE NETWORK
    RECEIVE AND RETURN A RESPONSE
     */
    private String send()
    {
        Log.i(TAG, "On Send 1");
        //CONNECT
        HttpURLConnection con=Connector.connect(urlAddress);
        Log.i(TAG, "On Send 2");
        if(con==null)
        {
            Log.i(TAG, "On Send 3");
            return null;
        }
        try
        {
            Log.i(TAG, "On Send 4");
            OutputStream os=con.getOutputStream();
            Log.i(TAG, "On Send 5");
            //WRITE
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            Log.i(TAG, "On Send 6");
            bw.flush();
            Log.i(TAG, "On Send 7");
            //RELEASE RES
            bw.close();
            Log.i(TAG, "On Send 8");
            os.close();
            Log.i(TAG, "On Send 9");
            //HAS IT BEEN SUCCESSFUL?
            int responseCode=con.getResponseCode();
            Log.i(TAG, "On Send 10");
            Log.i(TAG, "responseCode = " + responseCode);
            if(responseCode==con.HTTP_OK)
            {
                Log.i(TAG, "On Send 11");
                //GET EXACT RESPONSE
                BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
                Log.i(TAG, "On Send 12");
                StringBuffer response=new StringBuffer();
                Log.i(TAG, "On Send 13");
                String line;
                Log.i(TAG, "On Send 14");
                //READ LINE BY LINE
                while ((line=br.readLine()) != null)
                {
                    Log.i(TAG, "On Send 15");
                    response.append(line);
                }
                //RELEASE RES
                Log.i(TAG, "On Send 16");
                br.close();
                Log.i(TAG, "On Send 17");
                return response.toString();
            }else
            {
                Log.i(TAG, "On Send 18");
            }
        } catch (IOException e) {
            Log.i(TAG, "On Send 19");
            e.printStackTrace();
        }
        Log.i(TAG, "On Send 20");
        return null;
    }

And here is the logcat:

04-04 15:34:01.402 20341-20341/com.example.pruebainsp I/Sender: OnPre
04-04 15:34:01.445 20341-20550/com.example.pruebainsp I/Sender: doInBack
04-04 15:34:01.445 20341-20550/com.example.pruebainsp I/Sender: On Send 1
04-04 15:34:01.445 20341-20550/com.example.pruebainsp I/Sender: On Send 2
04-04 15:34:01.446 20341-20550/com.example.pruebainsp I/Sender: On Send 4
04-04 15:34:01.561 20341-20550/com.example.pruebainsp I/Sender: On Send 5
04-04 15:34:01.562 20341-20550/com.example.pruebainsp I/Sender: On Send 6
04-04 15:34:01.562 20341-20550/com.example.pruebainsp I/Sender: On Send 7
04-04 15:34:01.562 20341-20550/com.example.pruebainsp I/Sender: On Send 8
04-04 15:34:01.562 20341-20550/com.example.pruebainsp I/Sender: On Send 9
04-04 15:34:01.700 20341-20550/com.example.pruebainsp I/Sender: On Send 10
04-04 15:53:57.934 27226-27436/com.example.pruebainsp I/Sender: responseCode = 403
04-04 15:34:01.700 20341-20550/com.example.pruebainsp I/Sender: On Send 18
04-04 15:34:01.700 20341-20550/com.example.pruebainsp I/Sender: On Send 20
04-04 15:34:02.214 20341-20341/com.example.pruebainsp I/Sender: onPost

Upvotes: 2

Views: 1019

Answers (1)

Sagar
Sagar

Reputation: 24917

doInBackground() as the name suggests executes task in background thread. Ideally, you cannot perform UI related operations on background thread. Some Samsung devices tend to allow this, which is quite strange. On some phones it will directly crash your app.

In order to make it work on all the devices, you can either :

@Override
protected Object doInBackground(Object[] objects) {
    activityObj.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(contet, "Hello", Toast.LENGTH_LONG).show();
            }
    });
    return null;
}

OR

@Override
protected Object doInBackground(Object[] objects) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
            }
        });
}

Upvotes: 1

Related Questions