简体   繁体   中英

Parsing JSON to Parcelable objects to send Parcelable object to another Activity in Android

I wanted to pass the JSON Data coming response from POST Request done on an API. I have created Sharing class which implements the Parcelable class. I want to make use to parcelable class to hold few objects(client information) JSON response in main activity and send them to second activity to display only the client information.Here are my respective codes, Here is the api response.. { "success": "true", "message": "Logged in successfuly", "user": { "id": 13, "userNo": "", "name": "Adam", "username": "Adam@gmail.com", "actualPassword": "12345", "email": "apollo@client.com", "secondaryEmail": null, "primaryPhone": 9876544345, "secondaryPhone": null, "clientId": { "clientId": 1, "name": "Charlie", "address": "India", "createdBy": null, "createdAt": "2018-10-25T11:25:19.000Z", "updatedAt": "2019-01-21T10:10:39.000Z", "is_active": 1, "clientCode": "APL", "startTime": "08:00:00.000000", "endTime": "07:59:59.000000", }, "gender": null, "dob": null, "emergencyMobile": null, "officeNo": null, "loggedInStatus": 0, } }

Here is my Main Activity..

public class MainActivity extends AppCompatActivity {


public  static String myUrl="IP Address URL Link";
TextView tvIsConnected;
EditText etEmail;
EditText etPassword;
TextView tvResult;
Button btn_Send;
String name="";

TextView client_ID;
TextView client_Name;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etEmail = findViewById(R.id.etEmail);
    etPassword = findViewById(R.id.etPassword);
    tvResult = (TextView) findViewById(R.id.tvResult);

    btn_Send =(Button)findViewById(R.id.btnSend);


    final HTTPAsyncTask process = new HTTPAsyncTask();
    btn_Send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            process.execute();
        }
    });


}


@SuppressLint("ParcelCreator")
public  class HTTPAsyncTask extends AsyncTask<String, Void, String> implements Parcelable {
    JSONObject jsonObject = new JSONObject();
    Intent i = new Intent(MainActivity.this, DashboardActivity.class);

    @Override
    protected String doInBackground(String... urls) {

        StringBuffer output = new StringBuffer();
        try {
            try {

                URL url = new URL(myUrl);

                jsonObject.put("userName", etEmail.getText().toString());
                jsonObject.put("password", etPassword.getText().toString());



                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setReadTimeout(15000 );
                conn.setConnectTimeout(15000 );
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");



                OutputStream os = conn.getOutputStream();

                os.write(jsonObject.toString().getBytes());
                os.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                String temp;
                while ((temp = br.readLine()) != null) {
                    output.append(temp);
                }
                conn.disconnect();

            } catch (JSONException e) {
                e.printStackTrace();
                return "Error";
            }
        }
        catch (IOException e) {
            return "Error while retrieving screen";
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();
}



    @Override
    public void onPostExecute(String result ) {



        i.putExtra("key",result);

        startActivity(i);



    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

    }
}


}

Following is my Sharing class which implements Parcelable Class..

public class SharingClass implements Parcelable {

private int ClientId ;
private String ClientName;
private String ClientAddress;

public SharingClass(){
    super();
}

public SharingClass(Parcel parcel){
    this.ClientId = parcel.readInt();
    this.ClientName = parcel.readString();
    this.ClientAddress = parcel.readString();
}

public SharingClass(Parcelable sharedObject) {
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(ClientId);
    dest.writeString(ClientName);
    dest.writeString(ClientAddress);
}

public static final Creator<SharingClass> CREATOR = new Creator<SharingClass>() {
    @Override
    public SharingClass createFromParcel(Parcel parcel) {
        return new SharingClass(parcel);
    }

    @Override
    public SharingClass[] newArray(int i) {
        return new SharingClass[i];
    }
};

public void setClientId(int ClientId) {
    this.ClientId = ClientId;
}

public void setClientName(String ClientName) {
    this.ClientName = ClientName;
}

public void setClientAddress(String ClientAddress) {
    this.ClientAddress = ClientAddress;
}

public int getClientId() {
    return ClientId;
}

public String getClientName() {
    return ClientName;
}

public String getClientAddress() {
    return ClientAddress;
}


}

Kindly give me a solution to access the JSON Data to display the client information in second activity and also show the parsing as i am new to Android

Since you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

Then you can pull them back out with getParcelableExtra():

Intent i = getIntent();
SharingClass sharingClass = (SharingClass) i.getParcelableExtra("name_of_extra");

and if you have to access the data inside the POJO you can get by using the getter methods, which in your case for eg. If you have to access the ClientId then you can do it by.

int clientId = sharingClass.getClientId();

Hope this helps.

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