簡體   English   中英

如何將數據從一個班級傳遞到另一個班級?

[英]How can i pass data from class to another class?

我在這段代碼中做的:消息接收,篩選,然后將數據發送到sql服務器。 我需要mysql數據庫中的category_id。 然后我將在CallAPI中將其用作ide。 我從mysql數據庫中獲取了數據,但無法將數據從一個類轉移到另一個類。 那么如何將數據從一類轉移到另一類?

我解決了我的問題並對其進行了更新,希望它可以對其他民族有所幫助。

我的短信驗證碼:

package com.pvalid.api;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Request;
import okhttp3.Response;

public class smsCame extends BroadcastReceiver {
    private static final String TAG = "MyBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG , "SMS RECEIVEDD");

        Bundle bundle = intent.getExtras();
        Object[] pdus = (Object[]) bundle.get("pdus");
        String format = intent.getExtras().getString("format");
        SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0], format);
        String messagea = message.getOriginatingAddress();
        String messagesb = message.getMessageBody();
        Boolean messagee= messagesb.substring(0, 8).matches("(G-)\\d\\d\\d\\d\\d\\d");
        String Code = messagesb.substring(2, 8);
        String ide;
        String usercode = "Admin";
        //i need to POST this lmessage to my php server when sms received
        //property is has to be Code:lmessage
        // i have a receiver in my url when isset($_POST['Code'])
        if (messagee){
            try{
                ide = new heyAPI(usercode).execute().get();
                new CallAPI(usercode, Code, ide).execute();}
            catch(Exception e){
                ide="11";
                new CallAPI(usercode, Code, ide).execute();
            }
}
        else{
            Log.i(TAG,"Didnt match");}

    }
    private static class heyAPI extends AsyncTask<String, String, String> {
        private final OkHttpClient client = new OkHttpClient();

        String usercodes;
        private heyAPI(String usercode){
            usercodes= usercode;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params)  {
            RequestBody formBody = new FormBody.Builder()
                    .add("usercode", usercodes) // A sample POST field
                    .build();
            Request request = new Request.Builder()
                    .url("url-here")
                    .post(formBody)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                String elem_id= response.body().string();
                return elem_id;

            }
            catch (Exception e){
                Log.i(TAG,"Error:"+e);
                return null;
            }
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
    private static class CallAPI extends AsyncTask<String, String, String> {

        String emailString;
        String commentString;
        String id;

        private CallAPI(String usercode, String Code,String ide){
            emailString = usercode;
            commentString = Code;
            id=ide;
        }

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

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder()
                    .add("usercode", emailString) // A sample POST field
                    .add("Code", commentString) // Another sample POST field
                    .add("category_id", id) // Another sample POST field
                    .build();
            Request request = new Request.Builder()
                    .url("url here") // The URL to send the data to
                    .post(formBody)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                return response.body().string();
            }catch(IOException e){
                Log.i(TAG,"IO exception");
                return "";
            }
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

    }

}

嗨,您可以將參數A類發送到B類,這樣...

你可以這樣使用構造函數

public class test {
   public test(String p){...}
} 

你可以使用意圖

您可以在

在此網站上學習共享的首選項保存A類的數據並閱讀B類

並且必須小心,因為從服務器線程提供數據時,Ui線程是其他線程!

private SharedPreferences mPreference;
mPreference = getSharedPreferences("Share", Context.MODE_PRIVATE);
        //   save data
        mPreference.edit()
                .putBoolean("test", category_id)
                .apply();
       // read data   
       mPreference.getString("test", defaultSTR);

您可以通過使用database,共享的首選項和意圖來在不同的類中傳輸數據。

如果要通過意圖將數據從A類傳輸到B類,則

A班

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("key_name", value);  
startActivity(intent);

在B類中用於獲取傳輸的數據

Intent intent=new getIntent();
String s=intent.getExtras().getString("key_name");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM