tipu
tipu

Reputation: 9604

how to solve.. abstract class? generics?

In my current setup I have a centralized helper class like the following:

 @Override
 protected void onPostExecute(String result)
 {
     super.onPostExecute(result);
     if(task == null) {
         return;
     }

    Gson gson = new GsonBuilder().create();
    ResponseJson p = null;
    try {
        p = gson.fromJson(result, ResponseJson.class);
    } catch(JsonSyntaxException e) {
        //Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.toast_sync_completed), Toast.LENGTH_SHORT).show();
        Log.e("", e.getMessage() + " got '" + result + "'");
    }
    Log.i("", p.toString());
    Log.i("", result);

    if(p.status.equals(ResultStatus.SUCCESS.toString())) {
        task.success(p.data);
    } else if (p.status.equals(ResultStatus.FAIL.toString())) {
        task.fail(p.data);
    } else if (p.status.equals(ResultStatus.ERROR.toString())) {
        task.error(p.message);
    } else {
        throw new UnsupportedOperationException();
    }
 }

the problem is i want to make the ResponseJson class to be dynamic and the data attribute to be unique (sometimes i need ArrayList<Something> other times HashMap<String, String>) works for converting my JSON result. can i achieve this using generics or some other means?

Upvotes: 0

Views: 91

Answers (1)

Timu&#231;in
Timu&#231;in

Reputation: 4673

If you set Object as type of data,

class ResponseJson {
    Object data;
}

Later you can get the results as ArrayList or Hashmap as follows;

if (responseJson.data instanceof ArrayList<?>) {
    ArrayList<String> arrayList = (ArrayList<String>) responseJson.data;
} else if(responseJson.data instanceof HashMap<?, ?>) {
    HashMap<String, String> hashmap = (HashMap<String, String>) responseJson.data;
}

Due to type erasure, the parameterised type cannot be known at runtime. But if you know the type you can do an unchecked cast.

Upvotes: 1

Related Questions