2017-03-03 15 views
-2

こんにちは私はアンドロイドでソーシャルネットワークを作成していますが、mysqlデータからデータを取り出して、ここ 私を助けてください起こる新しい挿入データがある場合は、リストビューおよび通知のためのリフレッシュ私は放送受信機およびサービスを使用していますが、それは何もないことは、ここに私のコードバックグラウンドの自動リフレッシュリストビューでリストアアダプタを更新し、データベースから新しいデータがある場合に通知する必要があります。

Broadcast receiver 

public class BraodcastReceiverNotif extends BroadcastReceiver { 
    static int noOfTimes = 0; 
    JSONObject data; 
    Exception exception; 
    SharedPreferences sharedpreferences;; 
    public static final String mypreference = "pkAppPrefs"; 
    int pageNumber = 0; 
    public static final int REQUEST_CODE = 12345; 
    Intent intnt; 
    Context context; 

    @Override 
    public void onReceive(final Context context, Intent intent) { 
     sharedpreferences = context.getSharedPreferences(mypreference, Context.MODE_PRIVATE); 
     noOfTimes++; 
     //Toast.makeText(context, "BC Service Running for " + noOfTimes + " times", Toast.LENGTH_SHORT).show(); 
     // TODO Auto-generated method stub 
     noOfTimes++; 
     try { 
      startNetworkCalls(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
    private void startNetworkCalls() throws JSONException { 

     data = new JSONObject(); 
     data.put("user_key", sharedpreferences.getString("userKey", "")); 
     data.put("city_id", sharedpreferences.getString("user_city_id", "")); 
     data.put("sector_id", sharedpreferences.getString("sector_id", "")); 
     data.put("page", pageNumber); 

     String URL = "............................................."; 
     getOnlinePosts onlinePosts = new getOnlinePosts(); 
     onlinePosts.execute(URL); 
    } 
    private class getOnlinePosts extends AsyncTask<String, Void, String[]> { 
     private final String LOG_TAG =getOnlinePosts.class.getSimpleName(); 
     private Exception exception = null; 

     @Override 
     protected void onPreExecute() { 

     } 

     @Override 
     protected String[] doInBackground(String... params) { 
      URL url; 
      HttpURLConnection urlConnection = null; 
      BufferedReader reader = null; 
      String docsJson = null; 
      String JsonDATA = data.toString(); 
      String JsonResponse = null; 
      Context context = null; 

      try { 
       Log.e(LOG_TAG, "Started Connecting to " + params[0] + " Sending " +JsonDATA); 
       url = new URL(params[0]); 

       urlConnection = (HttpURLConnection) url.openConnection(); 
       urlConnection.setDoOutput(true); 
       urlConnection.setRequestMethod("POST"); 
       urlConnection.setRequestProperty("Content-Type", "application/json"); 
       urlConnection.setRequestProperty("Accept", "application/json"); 

       Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); 
       writer.write(JsonDATA); 
       writer.close(); 

       InputStream inputStream = urlConnection.getInputStream(); 
       StringBuffer buffer = new StringBuffer(); 
       if (inputStream == null) { 
        // Nothing to do. 
        return null; 
       } 
       reader = new BufferedReader(new InputStreamReader(inputStream)); 

       String inputLine; 
       while ((inputLine = reader.readLine()) != null) 
        buffer.append(inputLine + "\n"); 
       if (buffer.length() == 0) { 
        // Stream was empty. No point in parsing. 
        return null; 
       } 

       docsJson = buffer.toString(); 
       Log.v(LOG_TAG, "My data is: " + docsJson); 

      } catch (Exception e) { 
       exception = e; 
       e.printStackTrace(); 
      } finally { 
       if (urlConnection != null) { 
        urlConnection.disconnect(); 
       } 
      } 

      try { 
       return getDocumentDataFromJson(docsJson); 
      } catch (JSONException e) { 
       Log.e(LOG_TAG, e.getMessage(), e); 
       e.printStackTrace(); 
      } 
      // this will only happen if there is an error 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String[] result) { 


     } 
    } 
    private String[] getDocumentDataFromJson(String documentJsonStrArr) 
      throws JSONException { 

     final String data_status = "status"; 
     final String data_data = "data"; 
     final String data_name = "fullname"; 
     final String data_username = "community"; 
     JSONObject documentJson = new JSONObject(documentJsonStrArr); 
     String status = documentJson.getString(data_status); 

     if (status.equals("success")) { 

      JSONArray docs = documentJson.getJSONArray(data_data); 
      if (docs.length() > 0) { 
       for (int i = 0; i < docs.length(); i++) { 
        JSONObject singleDoc = docs.getJSONObject(i); 
        // String success = singleDoc.getString(documentJson.getString(data_status)); 
        String name = singleDoc.getString(data_name); 
        String username = singleDoc.getString(data_username); 


        intnt = new Intent(context, MyService.class); 

        // Set unsynced count in intent data 
        intnt.putExtra("success", "success"); 
        intnt.putExtra("name", name); 

        // Call MyService 
        context.startService(intnt); 

       } 
      } 
     } 
     return null; 
    } 

} 

である私のサービスは

public class MyService extends Service { 
    int numMessages = 0; 
    ArrayList<SinglePost> PostEntries = null; 
    public ArrayAdapter<SinglePost> mycardAdapter; 
    SharedPreferences sharedpreferences;; 
    public static final String mypreference = "pkAppPrefs"; 

    public MyService() { 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 

    @Override 
    public void onCreate() { 
     Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show(); 
     sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
     Intent resultIntent = new Intent(this, Community.class); 

     Toast.makeText(this, intent.getStringExtra("name"), Toast.LENGTH_LONG).show(); 

     PostEntries.add(new SinglePost(intent.getStringExtra("post_key"), 
       intent.getStringExtra("name"), 
       intent.getStringExtra("username"), intent.getStringExtra("profile_image"),intent.getStringExtra("poster_key") , 
       intent.getStringExtra("postdate"),intent.getStringExtra("message") ,intent.getStringExtra("likes") , 
       intent.getStringExtra("liked"),intent.getStringExtra("comments") ,intent.getStringExtra("commented") , 
       Boolean.parseBoolean(intent.getStringExtra("moderate")),intent.getStringExtra("sector") , 
       intent.getStringExtra("district"),intent.getStringExtra("province") , 
       intent.getStringExtra("city"),intent.getStringExtra("country") ,intent.getStringExtra("media") , 
       Integer.parseInt(intent.getStringExtra("media_count")), 
       Integer.parseInt(intent.getStringExtra("moderate_level")) , 
       Boolean.parseBoolean(intent.getStringExtra("own_post")) ,intent.getStringExtra("online"))); 

     //if (Integer.parseInt(intent.getStringExtra("count_data")) < Integer.parseInt(sharedpreferences.getString("count_data", ""))){ 

      PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, 
        resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
      NotificationCompat.Builder mNotifyBuilder; 
      NotificationManager mNotificationManager; 
      mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
      // Sets an ID for the notification, so it can be updated 
      int notifyID = 9001; 
      mNotifyBuilder = new NotificationCompat.Builder(this) 
        .setContentTitle("Alert") 
        .setContentText("You've received new messages.") 
        .setSmallIcon(R.drawable.ic_launcher); 
      // Set pending intent 
      mNotifyBuilder.setContentIntent(resultPendingIntent); 
      // Set Vibrate, Sound and Light 
      int defaults = 0; 
      defaults = defaults | android.app.Notification.DEFAULT_LIGHTS; 
      defaults = defaults | android.app.Notification.DEFAULT_VIBRATE; 
      defaults = defaults | android.app.Notification.DEFAULT_SOUND; 
      mNotifyBuilder.setDefaults(defaults); 
      // Set the content for Notification 
      mNotifyBuilder.setContentText(intent.getStringExtra("success")); 
      // Set autocancel 
      mNotifyBuilder.setAutoCancel(true); 
      // Post a notification 
      mNotificationManager.notify(notifyID, mNotifyBuilder.build()); 
     // } 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); 

    } 


MainActivity class i am passing scheduleAlarm method to check every 10 second in database and refresh my listview 

    Setup a recurring alarm every 10 seconds 
    public void scheduleAlarm() { 

      BroadCase Receiver Intent Object 
      Intent alarmIntent = new Intent(getContext().getApplicationContext(), BraodcastReceiverNotif.class); 
      // Pending Intent Object 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext().getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
      Alarm Manager Object 
      AlarmManager alarmManager = (AlarmManager) getContext().getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
      // Alarm Manager calls BroadCast for every Ten seconds (10 * 1000), BroadCase further calls service to check if new records are inserted in 
      // Remote MySQL DB 
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 5000, 10 * 1000, pendingIntent); 

    } 
です

固定形式

+1

あなたがそこにあるニースコード。質問はなんですか? –

+0

J.Baobyさん、ありがとうございました。私の質問は:私はリストビューアをリフレッシュせずにバックグラウンドで更新する必要があります。データベースから新しいデータがある場合は通知してください。 –

+1

投稿を編集して投稿に追加できますか? –

答えて

0

私は本当にあなたの質問を理解していないが、私はいくつかの意味がある。

私が正しく理解していれば、あなたは、サーバーからSQLiteデータベースに格納するデータを取得し、この機能を実現するには、リストビュー

内のデータを表示したい、

  1. からデータを取得するのHttpクラスを作成します。サーバー。
  2. HTTP要求を行うIntentServiceを作成します。
  3. サーバーからデータを受信したら、SQLiteに挿入します。ブロードキャスト

ブロードキャストの仕方は、 あなたはリストビューを持つあなたの活動に放送受信機を登録します。 ブロードキャストは、サーバーからのデータフェッチを決定する 'ブール値'としてメッセージを渡しますか?サーバーから正常にフェッチされた場合は、ブール値trueを渡し、ブロードキャスト受信後にローカルdbコールを行い、すべての変更をフェッチします。その後、リストビューを更新することができます

+0

私はリモートデータベース(mysql)からのデータを持っているので、ユーザーはリモートデータベースに新しいデータを投稿し、その新しいレコードをスワイプしてリストビューをリフレッシュするのを見るために私のアプリで表示しますが、他のユーザーに新しい投稿を通知する –

関連する問題