我是android开发的新手,我学到的一切都来自教程和Stack溢出。我的应用程序有90%的存储方式,但是无法刷新从API JSON网页提取的列表视图。
我已经阅读了几乎所有与我的问题有关的文章,并且我遵循的每个过程都会导致应用程序崩溃或什么也不做。
这是我的MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String tag = MainActivity.class.getSimpleName();
private List<DataSet> list = new ArrayList<DataSet>();
private ListView listView;
private Adapter adapter;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.mybutton) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new Adapter(this, list);
listView.setAdapter(adapter);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String ipadr = preferences.getString("signature", "0.0.0.0");
JsonArrayRequest jsonreq = new JsonArrayRequest("http://" + ipadr + "/android.php",
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DataSet dataSet = new DataSet();
dataSet.setName(obj.getString("resident"));
dataSet.setImage(obj.getString("image"));
dataSet.setWorth(obj.getString("type"));
dataSet.setSource(obj.getString("starttime"));
list.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(MainActivity.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error: Unable to connect to Server");
alert.show();
}
});
Controller.getPermission().addToRequestQueue(jsonreq);
}
public class MessageReceiver extends FirebaseMessagingService {
private static final int REQUEST_CODE = 1;
private static final int NOTIFICATION_ID = 6578;
private static final String TAG = "MyFirebaseMsgService";
public MessageReceiver() {
super();
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
final String title = remoteMessage.getData().get("title");
final String message = remoteMessage.getData().get("body");
finish();
startActivity(getIntent());
overridePendingTransition(0, 0);
showNotifications(title, message);
}
private void showNotifications(String title, String msg) {
Intent i = new Intent(this, MainActivity.class);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.rnifyround)
.setTicker("Hearty365")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle(title)
.setContentText(msg)
.setContentInfo("Info");
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
}
}
}
我的JSON输出示例
[{"image":"http://1.2.3.4/images/check.png","starttime":"2019-08-06 20:43:06","endtime":"2019-08-06 20:43:19","serial":"11298293","type":"Pendant","resident":"Resident Name","room":"APT 200","bed":"1","state":"closed"},{"image":"http://1.2.3.4/images/check.png","starttime":"2019-08-05 20:39:26","endtime":"2019-08-05 20:39:39","serial":"11298293","type":"Pendant","resident":"Resident Name","room":"APT 200","bed":"1","state":"closed"}]
我希望在收到通知且应用程序处于前台时刷新列表视图。我还需要刷新一下才能刷新它,但我仍在努力。
编辑
public class Adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> DataList;
ImageLoader imageLoader = Controller.getPermission().getImageLoader();
public Adapter(Activity activity, List<DataSet> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
@Override
public int getCount() {
return DataList.size();
}
@Override
public Object getItem(int location) {
return DataList.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.listview, null);
if (imageLoader == null)
imageLoader = Controller.getPermission().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView worth = (TextView) convertView.findViewById(R.id.worth);
TextView source = (TextView) convertView.findViewById(R.id.source);
DataSet m = DataList.get(position);
thumbNail.setImageUrl(m.getImage(), imageLoader);
name.setText("Resdient: " + (m.getName()));
source.setText("Activated: " + (m.getSource()));
worth.setText("Call Type: " + (m.getWorth()));
return convertView;
}
}
答案 0 :(得分:0)
我认为您应该创建refresh() {contain your codes: fetch data, add to list and notifyDataSetChange}
函数并在onCreate()
和onMessageReceived()
中调用它,而不要完成并重新启动活动
答案 1 :(得分:0)
感谢@urukh,我能够通过广播来解决这个问题。
在我的MessageReciever Activity showMessage方法中,我调用方法sendMessage();
sendMessage方法
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
然后在我的MainActivity中
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Code to refresh listview
}
}