从后台服务传递对象通过意向活动 [英] passing object through intent from background service to an activity

查看:79
本文介绍了从后台服务传递对象通过意向活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要包含从后台服务数据的定制矢量对象,以便传递给活动更新该活动的用户界面。 我不能够通过意图通过我的数据。请帮助我什么,我需要做的。

下面是我使用的code段。在下面code我想文章列表传递给一个活动。

 矢量< RowData> getArticleLog()抛出JSONException {

    矢量< RowData> articleList =新矢量< RowData>();

    RowData次;
    InputStream的是= NULL;
    字符串结果= NULL;
    JSONArray jarray =新JSONArray();

    //添加数据被发送。
    ArrayList的<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
    nameValuePairs.add(新BasicNameValuePair(article_title,飞马));

    尝试 {

        HttpClient的HttpClient的=新DefaultHttpClient();

        //为本地服务器XAMPP
        HttpPost httppost =新HttpPost(http://10.0.2.2/groupbook/return_article_log.php);

        httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
        HTT presponse响应= httpclient.execute(httppost);

        HttpEntity实体= response.getEntity();
        是= entity.getContent();
        Log.i(POSTDATA,response.getStatusLine()的toString());

    }赶上(例外五){
        Log.e(TAG,json的错误:+ e.toString());
    }
    //转换响应串
    尝试 {
         的BufferedReader读卡器=新的BufferedReader(新InputStreamReader的(就是,ISO-8859-1),8);
         StringBuilder的SB =新的StringBuilder();
         串线= NULL;
         而((行= reader.readLine())!= NULL){
                 sb.append(行+\ N);
         }
         is.close();

         结果= sb.toString();
    }赶上(例外五){
         Log.e(TAG,错误将导致+ e.toString());
    }

    尝试 {
        jarray =新JSONArray(结果);
    }赶上(JSONException E){
        e.printStackTrace();
    }
    //在数组列表的形式返回jArray;
    JSONObject的rowElement = NULL;
    INT观众= 0​​;
    INT票= 0;

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

        观众= rowElement.getInt(观众);
        票= rowElement.getInt(票);

        RD =新RowData(我,
                rowElement.getString(article_title),
                Integer.toString(i)中,
                rowElement.getString(last_post_by),
                2小时,
                rowElement.getString(catagory_tag),
                Integer.toString(观众),
                rowElement.getString(privacy_tag),
                Integer.toString(票)
                rowElement.getString(catagory_title));
        articleList.add(RD);
    }

    返回articleList;
}
 

RowData类如下:

 公共类RowData {

保护INT MID;
公共字符串articleTitle;
公共字符串articleCounter;
公共字符串lastPostBy;
公共字符串updatedTime;
公共字符串catagoryTag;
公共字符串viewingNow;
公共字符串privacyTag;
公共字符串票;
公共字符串catagoryTitle;

公共RowData(INT MID,字符串articleTitle,字符串articleCounter,
        字符串lastPostBy,字符串updatedTime,字符串catagoryTag,
        字符串viewingNow,字符串privacyTag,串票,
        字符串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 =票;
    this.catagoryTitle = catagoryTitle;
}
}
 

时下面的方法是正确的方式?

 私人无效DisplayingInfo()抛出JSONException {
    Log.d(TAG,进入DisplayLoggingInfo);
    intent.putExtra(articleLog,getArticleLog());
    sendBroadcast(意向);
}
 

解决方案

一件事你可以做的是让你的自定义类实现序列化(或 Parcelable ),用 putExtra()法的活动,并使用 getSerializableExtra()您的活动得到它。


修改1: 一个简单的例子:

在自定义类:

 的Bean;

@燮pressWarnings(串行)
公共类YourCustomVectorClass实现Serializable {
    // ...
}
 

在您的服务,您要启动的活动:

 意向意图=新的意图(yourContext,yourActivity.class);
intent.putExtra(theNameOfTheObject,yourObject);
startActivity(意向);
 

在你的活动:

  YourCustomVectorClass yourVector =(YourCustomVectorClass)getIntent()getSerializableExtra(theNameOfTheObject)。
 


编辑2:再次读取的问题后,我意识到,你传递一个向量 RowData 对象的活动。

由于 的Java Vector类 工具序列化,我想你不应该做任何事情,但使用过的载体活动 putExtra(),并把它与 getSerializableExtra()的活动。

I want to pass a custom made vector object containing data from background service to an activity in order to updating UI of that activity. I am not able to pass my data via intent. Please assist me what i need to do..

Following is the code snippet that i am using. In below code I want to pass article list to an activity.

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 class is as follows :

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;
}
}

Is following way is right way??

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

解决方案

One thing you can do is to make your custom class implements Serializable (or Parcelable), send the serializable object with putExtra() method to the activity and use getSerializableExtra() on your activity to get it.


Edit 1: a quick example:

In your custom class:

import java.io.Serializable;

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

In your service where you want to start the activity:

Intent intent = new Intent(yourContext, yourActivity.class);
intent.putExtra("theNameOfTheObject", yourObject);
startActivity(intent);

In your activity:

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


Edit 2: After reading the question again, I realized that you're passing a Vector of RowData objects to your Activity.

Since Java Vector class implements Serializable, I think you shouldn't do anything but passing the vector to the activity using putExtra() and get it with getSerializableExtra() on the Activity.

这篇关于从后台服务传递对象通过意向活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆