2013-10-22 2 views
0

나는이 서버에서 트래픽 보고서를로드하고, 응용 프로그램이 코드를 사용하여 서버에서 10 초마다 데이터를로드하도록 구성되어 있습니다 (트위터 같은) 타임 라인에 표시 응용 프로그램 :안드로이드 어떻게 동적으로 목록보기를 업데이 트합니까?

@Override 
     public void onResume() { 
      super.onResume(); 
      autoUpdate = new Timer(); 
      autoUpdate.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 
       public void run() { 
        new DownloadJSON2().execute(); // this is the class that downloads the data from the server. 
       } 
       }); 
      } 
      }, 0, 10000); // updates each 10 secs 
     } 


     @Override 
     public void onPause() { 
      autoUpdate.cancel(); 
      super.onPause(); 
     } 

을 문제는 목록을 아래로 스크롤하여 이전 게시물을 읽으면 목록이 새로 고쳐져 그 위로 이동한다는 것입니다. 그 데이터를 아약스처럼 다운로드하여 맨 위에 추가하고 싶습니다. 아니면 X의 새로운 보고서와 그것을 보여줄 단추가 있다고 말해줘.

어떻게 처리 할 수 ​​있습니까?

BTW 저는 안드로이드 프로그래밍에 새로운 경험이 있습니다.

미리 감사드립니다.

편집 :

public class DownloadJSON extends AsyncTask<Void, Void, Void> { 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       // Create a progressdialog 
       mProgressDialog = new ProgressDialog(MainActivity.this); 
       // Set progressdialog title 
       mProgressDialog.setTitle("Cargando reportes en tiempo real"); 
       // Set progressdialog message 
       mProgressDialog.setMessage("Por favor espere"); 
       mProgressDialog.setIndeterminate(false); 
       // Show progressdialog 
       mProgressDialog.show(); 
      } 

      @Override 
      protected Void doInBackground(Void... params) { 
       // Create an array 
       arraylist = new ArrayList<HashMap<String, String>>(); 
       // Retrieve JSON Objects from the given URL address 
       jsonobject = JSONfunctions 
         .getJSONfromURL("http://server.com/timeline.php"); 

       try { 
        // Locate the array name in JSON 
        jsonarray = jsonobject.getJSONArray("datos"); 

        for (int i = 0; i < jsonarray.length(); i++) { 
         HashMap<String, String> map = new HashMap<String, String>(); 
         jsonobject = jsonarray.getJSONObject(i); 
         // Retrive JSON Objects 
         // jsonobject1 = jsonobject.getJSONObject("contenido"); 
         map.put("imagen", jsonobject.getString("imagen")); 
         map.put("quien", jsonobject.getString("quien")); 
         map.put("fecha", jsonobject.getString("fecha")); 
         map.put("reporte", jsonobject.getString("reporte")); 
         // map.put("imgs", jsonobject1.getString("imgs")); 
         // map.put("video", jsonobject1.getString("video")); 
         // Set the JSON Objects into the array 
         arraylist.add(map); 
        } 
       } catch (JSONException e) { 
        Log.e("Error", e.getMessage()); 
        e.printStackTrace(); 
       } 
       return null; 
      } 

      @Override 
      protected void onPostExecute(Void args) { 
       // Locate the listview in listview_main.xml 
       listview = (ListView) findViewById(R.id.listview); 
       // Pass the results into ListViewAdapter.java 
       adapter = new ListViewAdapter(MainActivity.this, arraylist); 
       // Set the adapter to the ListView 
       listview.setAdapter(adapter); 
       adapter.notifyDataSetChanged(); 
       // Close the progressdialog 
       mProgressDialog.dismiss(); 
      } 
     } 

을하지만 목록보기가 새 데이터로 업데이트되지 않고, 내가 어떻게 이것을 달성 할 수 덕분에 바실리 Sochinsky에 난 다음에 추가 한?

편집 2 : 해결책을 준 cogentapps 덕분에,하지만 여전히 코드에 추가 할 수 없습니다. 어디에서 추가해야합니까? 내가 추가해야

이 내 ListViewAdapter에서 코드
protected void onPostExecute(Void args) { 
       // Locate the listview in listview_main.xml 
       listview = (ListView) findViewById(R.id.listview); 
       // Pass the results into ListViewAdapter.java 
       adapter = new ListViewAdapter(MainActivity.this, arraylist); 
       // Set the adapter to the ListView 
       adapter.addAll(); 
       listview.notifyDataSetChanged(); 
       // Close the progressdialog 
       mProgressDialog.dismiss(); 
      } 

의 adapter.add() :

나는이 일식을 제외한 시도한 많은 오류를 표시?

public class ListViewAdapter extends BaseAdapter { 

    // Declare Variables 
    Context context; 
    LayoutInflater inflater; 
    ArrayList<HashMap<String, String>> data; 
    ImageLoader imageLoader; 
    HashMap<String, String> resultp = new HashMap<String, String>(); 
    String coment; 
    public String img; 
    public int imga; 
    public ListViewAdapter(Context context, 
      ArrayList<HashMap<String, String>> arraylist) { 
     this.context = context; 
     data = arraylist; 
     imageLoader = new ImageLoader(context); 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     // Declare Variables 
     TextView quien; 
     ImageView imagen; 
     TextView reporte; 
     TextView fecha; 

     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View itemView = inflater.inflate(R.layout.listview_item, parent, false); 
     // Get the position 
     resultp = data.get(position); 

     // Locate the TextViews in listview_item.xml 
     // Locate the ImageView in listview_item.xml 
     imagen = (ImageView) itemView.findViewById(R.id.imagen); 
     fecha = (TextView) itemView.findViewById(R.id.fecha); 
     quien = (TextView) itemView.findViewById(R.id.quien); 
     reporte = (TextView) itemView.findViewById(R.id.reporte); 
     // Capture position and set results to the TextViews 
    // Capture position and set results to the ImageView 
     // Passes flag images URL into ImageLoader.class 
     imageLoader.DisplayImage(resultp.get(MainActivity.IMAGEN), imagen); 
     fecha.setText(resultp.get(MainActivity.FECHA)); 
     reporte.setText(resultp.get(MainActivity.REPORTE)); 
     quien.setText(resultp.get(MainActivity.QUIEN)); 
     // Capture ListView item click 
     /* 
     itemView.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // Get the position 
       resultp = data.get(position); 
        Intent intent = new Intent(context, SingleItemView.class); 
        // Pass all data rank 

        intent.putExtra("imagen", resultp.get(MainActivity.IMAGEN)); 

        intent.putExtra("quien", resultp.get(MainActivity.QUIEN)); 

        intent.putExtra("fecha", resultp.get(MainActivity.FECHA)); 
        // Start SingleItemView Class 
        context.startActivity(intent); 


      } 
     }); 
     */ 
     return itemView; 
    } 
} 
+0

listView.getAdapter().notifyDataSetChanged() –

+0

@VasilySochinsky 답장을 보내 주셔서 감사합니다.하지만 어디에서 어떻게 할 수 있습니까? 방해해서 미안해. –

+0

이 방법이 작동하지 않는다는 것이 이상합니다. 서버가 새 데이터를 반환하는지 확인하십시오. 서버에서받은 로그 인쇄 데이터를 넣고 확인하십시오. answer've에 대한 –

답변

1

목록에 항목을 추가 한 후 스크롤 위치를 유지하는 방법에 대한 설명/예를 들어,이 질문에 대한 답을 살펴 보자 기본적으로 Retaining position in ListView after calling notifyDataSetChanged

을, 당신은 위치와 스크롤을 기록해 새 데이터를 추가하기 전에 목록에서 첫 번째 보이는 항목의 오프셋. 그런 다음 이전 위치와 스크롤 오프셋을 복원합니다.

그러나 목록 상단에 새 항목을 추가하기 때문에 getFirstVisiblePosition()에 의해 반환 된 위치는 새로 고침 후 다른 항목을 참조 할 수 있습니다.

mList.setSelectionFromTop(index + newItemCount, top); 

당신을 : 상쾌한 전에 위치 0에 있던 항목이 지금 문제를 해결하려면 위치 (10) 될 수있다, 당신은 timeline.php에 의해 반환 새로운 항목의 수를 결정하고 다음과 같이 index에 추가해야 날짜 필드를 비교하여 어떤 항목이 새로운 항목인지 판단 할 수 있습니다.

(덧붙여 timeline.php이 가장 최근의 항목 만 반환하는 경우 더 이상 반환되지 않는 이전 항목으로 스크롤하면 문제가 발생할 수 있습니다. 새 데이터를 설정 한 후 이전 당신이 그것으로 스크롤 할 수 없습니다 때문에 항목은 더 이상 존재하지 않습니다.

이 문제를 해결하려면, 당신은 주위 이전 ArrayList을 유지에만 doInBackground()에 새 항목을 추가 할 수 있습니다. 그리고 doInBackground()notifyDataSetChanged()를 호출 할 수 있습니다. 그렇게하면 어댑터에서 이전 항목에 계속 액세스 할 수 있습니다.)

+0

감사합니다 시도 : 보호 무효 onPostExecute (무효 인수) { \t //이 listview_main.xml에서 목록보기를 찾습니다를 \t 목록보기 = (ListView를) findViewById를 (R.id.listview); \t // 결과를 ListViewAdapter.java에 전달하십시오. \t 어댑터 = 새 ListViewAdapter (MainActivity.this, arraylist); \t // 어댑터를 ListView로 설정 \t adapter.addAll(); \t listview.notifyDataSetChanged(); \t // 진행률 대화 상자 닫기 \t mProgressDialog.dismiss(); \t} 하지만 일식이 아니기 때문에 오류가 발생합니다. –

+0

좋아 보이지 않습니다. 기본 게시물에 추가 할 예정이지만 코드에 추가하는 방법을 모르겠습니다. –

+0

이것은 Eclipse에서 나타난 오류입니다. addAll() 메서드는 ListViewAdapter 유형에 대해 정의되지 않았습니다. –

관련 문제