【问题标题】:Asynctask used by multiple Java Fragments多个 Java Fragment 使用的 Asynctask
【发布时间】:2018-10-11 10:48:36
【问题描述】:

我目前正在做一个项目,我在 Android 上从 JSON 转储中获取数据。到目前为止,我是否在每个片段中设置了一个自定义的 Asynctask,我需要从 JSON 转储中获取数据。我很好奇的是我是否可以拥有一个公共 Java 类,片段可以在需要获取数据时“使用”它。

这是我尝试这样做的一个示例。首先是从公共 java 类调用 Asynctask 的片段:

public class DataTabelFragment extends Fragment {

private TextView sensor1;
private Button jsonButton;

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 );
    //jsonButton = (Button) view.findViewById( R.id.buttonjson );

    new jsonAsynctask().execute();

    for (int i = 0; i < jsonasynctask.allId.size(); i++) {
        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" );

    }

    //new jsonConnection().execute();

    /*

    jsonButton.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new jsonConnection().execute();
        }
    } );*/



    return view;

}


}

这是带有 Asynctask 的 java 类:

public class jsonAsynctask extends MainActivity {

private TextView sensor1;
private Button jsonButton;

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 = "";
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 );

}

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

    @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();

        pd = new ProgressDialog( new MainActivity() );
        pd.setMessage( "Være sød at vente" );
        //pd.setCancelable( false );
        pd.show();
    }

    @Override
    public void onPostExecute(Void result) {
        super.onPostExecute( result );
        if (pd.isShowing()) {
            pd.dismiss();
        }

        System.out.println( data );

        gson = new Gson();

        json = gson.toJson( data );

        System.out.println( "String json: " + json );

        json_string = data;

        System.out.println( "json_string: " + json_string );

//            System.out.println( "DET HER ER ID!!: " + allId.get( 1 ) );

        //textView2.setMovementMethod( new ScrollingMovementMethod() );


        System.out.println("Size of Array: " + allId.size());



    }
        }


}

我可以这样编程吗,还是应该在每个片段中继续有一个 Asynctask?顺便说一句,“new jsonAsynctask().execute();”在片段中不起作用,我收到此错误:

错误:找不到符号类执行

* 更新 *

这是 Java 类中的更新,Asynctask 所在的位置。

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

private TextView sensor1;
private Button jsonButton;

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 = "";
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();

        pd = new ProgressDialog( new MainActivity() );
        pd.setMessage( "Være sød at vente" );
        pd.show();
    }

    @Override
    public void onPostExecute(Void result) {
        super.onPostExecute( result );
        if (pd.isShowing()) {
            pd.dismiss();
        }

        gson = new Gson();

        json = gson.toJson( data );

        json_string = data;


      }
        }

}

我收到的错误:

错误:需要类、接口或枚举

感谢您的帮助!提前致谢。

【问题讨论】:

  • 因为jsonAsynctask 是您的活动而不是AsyncTask。你也不能实例化活动。
  • 嗨,皮尤什。我不确定我是否明白你在说什么。您能详细说明一下吗?顺便说一句,非常感谢您抽出宝贵时间!
  • 如果你想从活动中访问你的异步任务,那么你可以得到(jsonAsynctask)getActivity()).new jsonConnection ().execute();而不是创建你的活动实例。您也可以在片段而不是在活动中创建异步任务。
  • 我已经更新了我的问题,并且我已经编辑了 jsonAsynctask Java 类,但是我收到了一个新的错误。
  • jsonAsynctask 中删除extends MainActivity。现在在声明部分的片段类中声明,如jsonAsynctask mjsonTask; 现在在onCreateView() 方法中创建实例mjsonTask = new jsonAsynctask(); 之后调用mjsonTask.new jsonConnection ().execute();

标签: android android-fragments android-asynctask


【解决方案1】:

为 AsynctTask 创建单独的类更好,而不是在每个片段中创建 AsyncTask。 您收到错误是因为在 new jsonAsynctask().execute() // jsonAsyncTask 继承自 MainActivity,所以它不是 AsyncTask

用新的 jsonConnection .execute() 替换上面的行

【讨论】:

  • 我已经用你写的内容替换了这一行,但是我收到了这个错误:错误:包 jsonConnection 不存在
  • @Yas 从 jsonAsynctask 类中移除 jsonConnection 类。我的意思是你不需要 jsonAsynctask 类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多