简体   繁体   English

(Android)片段onCreate未运行整个方法

[英](Android) Fragment onCreate not running whole method

I am working on an android project, where I fetch data from a JSON dump. 我正在开发一个Android项目,该项目是从JSON转储中获取数据的。 I have a fragment, where i call an Asynctask from another public Java Class. 我有一个片段,其中我从另一个公共Java类调用Asynctask。 For some reason won't my fragment run it's whole onCreateView, and after I call the Asynctask, then it stops running the rest of the onCreateView. 由于某种原因,我的片段不会全部运行在onCreateView上,在我调用Asynctask之后,它将停止运行其余的onCreateView。 There's an important for loop, which won't run. 有一个重要的for循环,它将不会运行。

The fragment looks like this, and you can see in my comments where it stops running. 该片段看起来像这样,您可以在我的注释中看到它停止运行的位置。

public class DataTabelFragment extends Fragment {

private TextView sensor1;

jsonAsynctask jsonasynctask = new jsonAsynctask();


public DataTabelFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate( R.layout.fragment_data_tabel, container, false );

    sensor1 = (TextView) view.findViewById( R.id.sensor1Box );

    new jsonAsynctask().execute(); //THIS IS THE LAST CODE RUNNING

    //NOT RUNNING CODE AFTER THIS

    System.out.println( jsonasynctask.allDevice );

    for (int i = 0; i < jsonasynctask.allId.size(); i++) {

        // String date_time = allDate_time.get( i );
        // String date = date_time.substring( 0, date_time.indexOf( "T" ) );
        // String time = date_time.substring( date_time.indexOf( "T" ) + 1, date_time.indexOf( "+" ) );
        // textView2.append( allId.get( i ) + "  " + allTemp.get( i ) + "  " + allHum.get( i ) + "  " + allBat.get( i ) + "  " + allMode.get( i ) + "  " + date + "  " + time + "  " + allLux.get( i ) + "\n\n" );
        sensor1.append( jsonasynctask.allId.get( i ) + " | " + jsonasynctask.allDevice.get( i ) + " | " + jsonasynctask.allTemp.get( i ) + " | " + jsonasynctask.allHum.get( i ) + " | " + jsonasynctask.allBat.get( i ) + " | " + jsonasynctask.allMode.get( i ) + " | " + jsonasynctask.allLux.get( i ) + " | " + jsonasynctask.allDate_time.get( i ) + "\n\n" );

    }

    return view;

    }

}

This is the public java class where the Asynctask is: 这是Asynctask在其中的公共Java类:

public class jsonAsynctask extends AsyncTask<Void, Void, Void> {

JSONObject deviceArray;
JSONObject tempArray;
JSONObject humArray;
JSONObject batArray;
JSONObject modeArray;
JSONObject date_timeArray;
JSONObject luxArray;

JSONArray json2;

List<String> allId = new ArrayList<String>();
List<String> allDevice = new ArrayList<String>();
List<String> allTemp = new ArrayList<String>();
List<String> allHum = new ArrayList<String>();
List<String> allBat = new ArrayList<String>();
List<String> allMode = new ArrayList<String>();
List<String> allDate_time = new ArrayList<String>();
List<String> allLux = new ArrayList<String>();

String basicAuth;
String line;
String json_string;
String json;
String cxwebURL;
String credentials;
String password;
String username;

Gson gson;
ProgressDialog pd;
String data = "";
//HttpsURLConnection connection;
HttpURLConnection connection;
BufferedReader bufferedReader;

String id = "";
JSONObject idArray;

URL url;


private static String encodeBase64URLSafeString(byte[] binaryData) {

    return android.util.Base64.encodeToString( binaryData, android.util.Base64.URL_SAFE );

}

    @Override
    protected Void doInBackground(Void... voids) {

        username = "xxx";

        password = "xxx";

        credentials = username + ":" + password;

        cxwebURL = "https://" + credentials + "@xxx.com/fetch.php?device=xxx";

        try {

            url = new URL( cxwebURL );

            connection = (HttpsURLConnection) url.openConnection();

            basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );

            connection.setRequestProperty( "Authorization", basicAuth );
            connection.setRequestMethod( "GET" );
            connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
            connection.setRequestProperty( "Content-Language", "en-US" );
            connection.setUseCaches( false );
            connection.setDoInput( true );
            connection.setDoOutput( true );
            connection.connect();

            InputStream stream = connection.getInputStream();

            bufferedReader = new BufferedReader( new InputStreamReader( stream ) );

            line = "";

            while (line != null) {
                line = bufferedReader.readLine();
                data = data + line;
            }

            json2 = new JSONArray( data );

            for (int i = 0; i < json2.length(); i++) {
                idArray = json2.getJSONObject( i );
                deviceArray = json2.getJSONObject( i );
                tempArray = json2.getJSONObject( i );
                humArray = json2.getJSONObject( i );
                batArray = json2.getJSONObject( i );
                modeArray = json2.getJSONObject( i );
                date_timeArray = json2.getJSONObject( i );
                luxArray = json2.getJSONObject( i );
                id = idArray.getString( "id" );

                String temp = tempArray.getString( "temp" );
                String device = deviceArray.getString( "device" );

                String hum = humArray.getString( "hum" );

                String bat = batArray.getString( "bat" );

                String mode = modeArray.getString( "mode" );

                String date_time = date_timeArray.getString( "time" );

                String lux = luxArray.getString( "light" );

                allId.add( id );
                allDevice.add( device );
                allTemp.add( temp );
                allHum.add( hum );
                allBat.add( bat );
                allMode.add( mode );
                allDate_time.add( date_time );
                allLux.add( lux );


            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    public void onPostExecute(Void result) {
        super.onPostExecute( result );

        gson = new Gson();

        json = gson.toJson( data );

        json_string = data;


        }
    }

If you have studied about AsyncTask it runs on background UI . 如果您学习过有关AsyncTask的信息,那么它将在后台UI上运行。

Although you are calling Loop after this method but Loop is on Main UI so it executes before AsyncTask is completed. 尽管您是在此方法之后调用Loop的,但是Loop在Main UI上,因此它会在AsyncTask完成之前执行。

so it feels like Loop is not executing 所以感觉循环没有执行

Put your Loop in onPost() method of AsynTask so it get executed once AsyncTask has completed its work 将您的Loop放入AsynTask的onPost()方法中,以便在AsyncTask完成工作后立即执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM