简体   繁体   中英

How can i pass data from class to another class?

I am doing in this code: message receiving,filtering and getting then sending data to a sql server. I need the category_id from mysql database. Then i will use it in CallAPI as ide . I took the data from my mysql database but i couldn't transfer the data one class to another. So how can i transfer the data from one class to another?

I solved my problem and updated it i hope it can help to another peoples.

my smsCame codes:

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);
        }

    }

}

hi you can send parameters class A to class B is so way...

you can use constructor like this

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

and you can use intent

you can use shared preference in

learn with this site Shared preference save data from class A and read class B

and you must be careful because when you give data from server thread is different Ui thread !

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

You can use transfer your data in different class by using database , shared preference and intents.

If You want to transfer data from class A to B by intent then

In class A

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

and In class B for getting the transferred data

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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