我正在从API调用接收数据。我可以将这些数据发送到www.example.com中的GridViewMainActivity.java,并在收到第一个版本的数据后更新一次网格视图,但当我单击网格时,数据发生了变化,我需要网格视图刷新并显示更新后的数据,而这并没有发生。我再次调用相同的回调,这是我在开始时所做的,它给了我第一个版本的数据。
我的APIManager.java类:
public class APIManager {
DeviceCallback deviceCallback;
private static final String TAG = "APIManager";
private static final String API_URL = "https://base-url"
private static final String AUTH_TOKEN = SplashScreen.getTOKEN();
private static List<Device> deviceArray = null;
public void setDeviceCallback(DeviceCallback deviceCallback) {
this.deviceCallback = deviceCallback;
}
void toggleDeviceState(Context context, String deviceID) {
String URL = "https://baseurl/" + deviceID;
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Process the JSON response
try {
parseToggleStateResponse(response);
} catch (JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle API call error
Log.e(TAG, "API error: " + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "jwt " + AUTH_TOKEN);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
void fetchInitialData(Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, API_URL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Process the JSON response
try {
//
parseResponseData(response);
JSONArray ownDevices = response.getJSONArray("owndevices");
} catch (JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle API call error
Log.e(TAG, "API error: " + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Jwt " + AUTH_TOKEN);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
ToggleResponse parseToggleStateResponse(JSONObject response) throws JSONException {
Gson gson = new Gson();
JSONObject device = response.getJSONObject("data");
Device deviceData = gson.fromJson(device.toString(), Device.class);
Log.w("API-MANAGER", "125 : Response = " + deviceData.getId());
for (int i = 0; i < deviceArray.toArray().length; i++)
{
String deviceID = deviceArray.get(i).getId();
if (deviceID == deviceData.getId()) {
Log.w("API-MANAGER", "DEVICE FOUND : " + deviceArray.get(i).getGivenName());
deviceArray.get(i).setState(deviceData.isState());
deviceCallback.deviceCallbackFunction(deviceArray);
}
}
ToggleResponse responseData = new ToggleResponse(deviceData, message);
return responseData;
}
DeviceResponse parseResponseData(JSONObject response) throws JSONException {
Gson gson = new Gson();
JSONArray ownDevicesArray = response.getJSONArray("owndevices");
Device ownDevices[] = gson.fromJson(String.valueOf(ownDevicesArray), Device[].class);
;
DeviceResponse responseData = new DeviceResponse(ownDevices);
List<Device> ownDevice = new ArrayList<>();;
List<Device> delDevice = new ArrayList<>();
// Parse ownDevices
for (int i = 0; i < ownDevicesArray.length(); i++)
{
JSONObject deviceObject = ownDevicesArray.getJSONObject(i);
Device device = new Device();
Log.w("API-MANAGER", "153" + deviceObject.getString("_id"));
device.set_id(deviceObject.getString("_id"));
device.setName(deviceObject.getString("name"));
device.setGivenName(deviceObject.getString("givenName"));
device.setState(deviceObject.getBoolean("state"));
device.setAdmin(deviceObject.getString("admin"));
device.setDelegate(getStringListFromJSONArray(deviceObject.getJSONArray("delegate")));
device.setSchedulerFlag(deviceObject.getBoolean("schedulerFlag"));
device.setTopic(deviceObject.getString("topic"));
device.setMultiState(deviceObject.optString("multiState"));
ownDevice.add(device);
}
deviceArray = ownDevice;
deviceCallback.deviceCallbackFunction(ownDevice);
responseData.setOwndevices(ownDevice);
return responseData;
}
private List<String> getStringListFromJSONArray(JSONArray jsonArray) throws JSONException {
List<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getString(i));
}
return list;
}
public interface DeviceCallback {
void deviceCallbackFunction(List<Device> deviceData);
}
}
GridAdaptr.java :
public class GridAdapter extends BaseAdapter{
Context context;
private final List<Device> deviceData;
// private final int [] images;
LayoutInflater layoutInflater;
APIManager apiManager = new APIManager();
public GridAdapter(Context context, List<Device> deviceData) {
this.context = context;
this.deviceData = deviceData;
// this.images = images;
}
@Override
public int getCount() {
return deviceData.toArray().length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Holder holder = new Holder();
View rowView;
rowView = layoutInflater.inflate(R.layout.grid_item_layout, null);
holder.GivenName = (TextView) rowView.findViewById(R.id.GivenName);
holder.image= (ImageView) rowView.findViewById(R.id.image);
holder.image.setImageResource(deviceData.get(position).isState()? R.drawable.switch_on : R.drawable.switch_off);
holder.GivenName.setText(deviceData.get(position).getGivenName());
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
apiManager.toggleDeviceState(context.getApplicationContext(), deviceData.get(position).getId());
Toast.makeText(context, "You Clicked "+deviceData.get(position).getId(), Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
return rowView;
}
public class Holder
{
TextView Name;
TextView GivenName;
TextView State;
TextView MultiState;
TextView ConnectFlag;
ImageView image;
}
}
我的MainActivity.java:
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity implements APIManager.DeviceCallback {
public static GridView gridView;
private Boolean hasConnection = false;
String token = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
token = sharedPreferences.getString("token", null);
APIManager apiManager = new APIManager();
SocketClass socketClass = new SocketClass();
apiManager.setDeviceCallback(this);
apiManager.fetchData(getApplicationContext());
getSupportActionBar().setTitle("Home");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
gridView = (GridView) findViewById(R.id.gridview);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
Log.w("API-MANAGER", "Item : " + item.toString());
return super.onOptionsItemSelected(item);
}
@Override
public void deviceCallbackFunction(List<Device> deviceData) {
GridAdapter gridAdapter = new GridAdapter(this, deviceData);
Log.w("API-MANAGER", "49" + deviceData.get(0).getGivenName());
gridView.setAdapter(gridAdapter);
}
}
1条答案
按热度按时间fsi0uk1n1#
调用adapter.notifyDataSetChanged();刷新网格后!它