Я пытаюсь найти способ, чтобы входной поток из одного класса был проанализирован в другом классе - PullRequest
0 голосов
/ 24 января 2011

Я довольно новичок в Android, и мне нравится, когда входящий поток переносится из одного класса в другой. По сути, я пытаюсь получить геокодированное местоположение для отправки на сервер и ответ для отправки другому классу для анализа.

вот фрагмент кода, который у меня есть для ответа httppost и inputtream:

Location1.java

private void updateWithNewLocation(Location location) {
  if (location != null) {
    double lat = location.getLatitude();
    String lat1 = Double.toString(lat);
    double lng = location.getLongitude();
    String lng1 = Double.toString(lng);

 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://...");

 try {

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

nameValuePairs.add (new BasicNameValuePair ("lat", lat1)); nameValuePairs.add (new BasicNameValuePair ("lng", lng1)); httppost.setEntity (новый UrlEncodedFormEntity (nameValuePairs));

     HttpResponse response = httpclient.execute(httppost);
 InputStream is = response.getEntity().getContent();

BufferedInputStream bis = new BufferedInputStream (is); ByteArrayBuffer baf = new ByteArrayBuffer (20);

int current = 0;  
while((current = bis.read()) != -1){  
 baf.append((byte)current);  
}  

Вот фрагмент из другого класса, в котором я хочу проанализировать входной поток ... В этом классе уже был входной поток, и я пытался выяснить, как заменить его другим потоком из другого класса.

parser1.java

       //I already have an inputstream here and this is where I want to inject the other class inputstream

          InputStream in = httpConnection.getInputStream(); 
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   DocumentBuilder db = dbf.newDocumentBuilder();

   // parse the feed
   Document dom = db.parse(in);      
   Element docEle = dom.getDocumentElement(); ...

Любая помощь будет высоко ценится.

1 Ответ

0 голосов
/ 24 января 2011

Я думаю, что это больше вопрос Java, чем вопрос Android.Разве вы не можете просто создать существующий метод updateWithNewLocation() public и вернуть InputStream вместо void?Что-то вроде:

Location1.java

public static InputStream updateWithNewLocation(Location location) {
    InputStream result = null;
    if (location != null) {
        double lat = location.getLatitude();
        String lat1 = Double.toString(lat);
        double lng = location.getLongitude();
        String lng1 = Double.toString(lng);

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://...");

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("lat", lat1));
            nameValuePairs.add(new BasicNameValuePair("lng", lng1));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            result = response.getEntity().getContent();
        } catch(Exception e) {
            //error handling
        }
    return result;
}

parser1.java

...
InputStream in = Location1.updateWithNewLocation(location)
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

// parse the feed
Document dom = db.parse(in);      
Element docEle = dom.getDocumentElement();
...
...