2012-02-11 2 views
0

백그라운드 서비스의 데이터를 포함하는 맞춤형 벡터 객체를 액티비티로 전달하여 해당 액티비티의 UI를 업데이트하려고합니다. 의도를 통해 데이터를 전달할 수 없습니다. 내가해야 할 일을 도와주세요.백그라운드 서비스에서 인 텐트를 통해 액티비티로 객체를 전달

다음은 내가 사용하고있는 코드 조각입니다. 아래 코드에서 활동에 기사 목록을 전달하고 싶습니다. 다음과 같이

Vector<RowData> getArticleLog() throws JSONException{ 

    Vector<RowData> articleList = new Vector<RowData>(); 

    RowData rd; 
    InputStream is = null; 
    String result = null; 
    JSONArray jarray = new JSONArray(); 

    //Add data to be send. 
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("article_title", "Flying Horse")); 

    try { 

     HttpClient httpclient = new DefaultHttpClient(); 

     // for local server xampp 
     HttpPost httppost = new HttpPost("http://10.0.2.2/groupbook/return_article_log.php"); 

     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 

     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
     Log.i("postData", response.getStatusLine().toString()); 

    } catch (Exception e) { 
     Log.e(TAG, "json error : " + e.toString()); 
    } 
    //convert response to string 
    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
     } 
     is.close(); 

     result=sb.toString(); 
    } catch (Exception e) { 
     Log.e(TAG, "Error converting result "+e.toString()); 
    } 

    try { 
     jarray = new JSONArray(result); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    //return jArray in the form of Array list; 
    JSONObject rowElement = null; 
    int viewers = 0; 
    int votes = 0; 

    for (int i = 0; i < jarray.length(); i++) { 
     rowElement = jarray.getJSONObject(i); 

     viewers = rowElement.getInt("viewers"); 
     votes = rowElement.getInt("votes"); 

     rd = new RowData(i, 
       rowElement.getString("article_title"), 
       Integer.toString(i), 
       rowElement.getString("last_post_by"), 
       "2 hours", 
       rowElement.getString("catagory_tag"), 
       Integer.toString(viewers), 
       rowElement.getString("privacy_tag"), 
       Integer.toString(votes), 
       rowElement.getString("catagory_title")); 
     articleList.add(rd); 
    } 

    return articleList; 
} 

rowData 하행 클래스는 다음과 같습니다

public class RowData { 

protected int mId; 
public String articleTitle; 
public String articleCounter; 
public String lastPostBy; 
public String updatedTime; 
public String catagoryTag; 
public String viewingNow; 
public String privacyTag; 
public String votes; 
public String catagoryTitle; 

public RowData(int mId, String articleTitle, String articleCounter, 
     String lastPostBy, String updatedTime, String catagoryTag, 
     String viewingNow, String privacyTag, String votes, 
     String catagoryTitle) { 
    this.mId = mId; 
    this.articleTitle = articleTitle; 
    this.articleCounter = articleCounter; 
    this.lastPostBy = lastPostBy; 
    this.updatedTime = updatedTime; 
    this.catagoryTag = catagoryTag; 
    this.viewingNow = viewingNow; 
    this.privacyTag = privacyTag; 
    this.votes = votes; 
    this.catagoryTitle = catagoryTitle; 
} 
} 

다음과 같다 방법은 올바른 방법입니다? 당신이 할 수있는

private void DisplayingInfo() throws JSONException{ 
    Log.d(TAG, "entered DisplayLoggingInfo"); 
    intent.putExtra("articleLog", getArticleLog()); 
    sendBroadcast(intent); 
} 

답변

2

한 가지, 사용자 정의 클래스가 Serializable (또는 Parcelable)를 구현하게 활동을 putExtra() 방법으로 직렬화 객체를 보내고 그걸 얻기 위해 활동에 getSerializableExtra()을 사용하는 것입니다.


편집 1 : 빠른 예 :

사용자 정의 클래스에서

:

Intent intent = new Intent(yourContext, yourActivity.class); 
intent.putExtra("theNameOfTheObject", yourObject); 
startActivity(intent); 
: 당신이 활동을 시작하려는

서비스에서
import java.io.Serializable; 

@SuppressWarnings("serial") 
public class YourCustomVectorClass implements Serializable { 
    // ... 
} 

활동 내역 :

YourCustomVectorClass yourVector = (YourCustomVectorClass) getIntent().getSerializableExtra("theNameOfTheObject"); 

편집 2 : 다시 질문을 읽고 나면, 나는 당신이 당신의 활동에 VectorRowData의 객체를 전달하는 것을 깨달았다.

Java Vector class부터 구현 Serializable, 난 당신이 putExtra()을 사용하고 활동에 getSerializableExtra()으로 그것을 얻을 활동에 벡터를 통과하지만 아무것도하지한다고 생각합니다.

+0

친절하고 빠른 답장을 보내 주셔서 감사합니다. 제발 좀 더 정교한 RowData 클래스 Serializable 또는 getArticleLog 메서드를 포함하는 클래스를 만들어야합니까 ?? 위의 getArticleLog 메소드는 백그라운드 서비스로 작성되었습니다. –

+0

Serializable을 사용하거나 사용하지 않고 확인했지만 getSerializableExtra를 사용하면 예외가 발생합니다. getSerializableExtra Serializable 또는 String 반환 질문이 있습니까 ?? –

+0

** 객체 **를 반환합니다. 실제 유형으로 캐스팅해야합니다 (귀하의 경우 **'Vector ** '). 그래서 당신의 코드는'Vector receivedObject = (Vector ) getIntent(). getSerializableExtra ("theNameOfTheObject");와 같이 나타날 것입니다. – fardjad

관련 문제