2014-01-03 4 views
2

Я после книги «Head First Android», и я застрял в главе 3.Android Head First «НАСА ежедневно изображение App»

Это небольшое приложение является действительно основной макет; 3 текстовых представления и 1 вид изображения, которые должны обновляться после чтения из ежедневного изображения NASA RSS.

Я закончил эту главу, но теперь при запуске приложения отображается только экран «Пустой».

Любая помощь приветствуется. Это код:

public class MainActivity extends Activity { 

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     IotdHandler handler = new IotdHandler(); 
     handler.processFeed(); 
     resetDisplay (handler.getTitle(), handler.getDate(), handler.getImage(), handler.getDescription()); 
    } 

    public class IotdHandler extends DefaultHandler { 
     private String url = "http://www.nasa.gov/rss/dyn/image_of_the_day.rss"; 
     private boolean inUrl = false; 
     private boolean inTitle = false; 
     private boolean inDescription = false; 
     private boolean inItem = false; 
     private boolean inDate = false; 
     private Bitmap image = null; 
     private String title = null; 
     private StringBuffer description = new StringBuffer(); 
     private String date = null; 


     public void processFeed() { 
      try { 
      SAXParserFactory factory = 
      SAXParserFactory.newInstance(); 
      SAXParser parser = factory.newSAXParser(); 
      XMLReader reader = parser.getXMLReader(); 
      reader.setContentHandler(this); 
      InputStream inputStream = new URL(url).openStream(); 
      reader.parse(new InputSource(inputStream)); 
      } catch (Exception e) { } 
     } 

      private Bitmap getBitmap(String url) { 
       try { 
       HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection(); 
       connection.setDoInput(true); 
       connection.connect(); 
       InputStream input = connection.getInputStream(); 
       Bitmap bilde = BitmapFactory.decodeStream(input); 
       input.close(); 
       return bilde; 
       } catch (IOException ioe) { return null; } 
       } 

      public void startElement(String url, String localName, String qName, Attributes attributes) throws SAXException { 
        if (localName.endsWith(".jpg")) { inUrl = true; } 
        else { inUrl = false; } 

        if (localName.startsWith("item")) { inItem = true; } 
        else if (inItem) { 

         if (localName.equals("title")) { inTitle = true; } 
         else { inTitle = false; } 

         if (localName.equals("description")) { inDescription = true; } 
         else { inDescription = false; } 

         if (localName.equals("pubDate")) { inDate = true; } 
         else { inDate = false; } 
         } 
        } 


      public void characters(char ch[], int start, int length) { String chars = new String(ch).substring(start, start + length); 
       if (inUrl && url == null) { image = getBitmap(chars); } 
       if (inTitle && title == null) { title = chars; } 
       if (inDescription) { description.append(chars); } 
       if (inDate && date == null) { date = chars; } 
     } 

     public Bitmap getImage() { return image; } 
     public String getTitle() { return title; } 
     public StringBuffer getDescription() { return description; } 
     public String getDate() { return date; } 
} 

    private void resetDisplay (String title, String date, Bitmap image, StringBuffer description) { 

     TextView titleView = (TextView) findViewById (R.id.imageTitle); 
     titleView.setText(title); 

     TextView dateView = (TextView) findViewById(R.id.imageDate); 
     dateView.setText(date); 

     ImageView imageView = (ImageView) findViewById (R.id.imageDisplay); 
     imageView.setImageBitmap(image); 

     TextView descriptionView = (TextView) findViewById (R.id.imageDescription); 
     descriptionView.setText(description); 
    } 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 
} 
+0

вы получаете LogCat мощность если так пожалуйста post это тоже. –

ответ

3

Вы должны использовать AsyncTask как внутренний класс.

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    IotdHandler handler = new IotdHandler(); 
    new MyTask().execute(); 
} 

, а затем разобрать документ в doInBackground() и вызвать resetDisplay в onPostExecute().

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

@Override 
protected Void doInBackground(Void... params) { 
    handler.processFeed(); 
    return null; 
} 

@Override 
protected void onPostExecute(Void result) { 
    resetDisplay (handler.getTitle(), handler.getDate(), handler.getImage(), handler.getDescription()); 
    super.onPostExecute(result); 
} 
} 

Для получения дополнительной информации, как передать параметр, обратный результат и т.д .. AsyncTask Document

0

Там будет больше ошибок вы будете облицовочные, если вы идете вперед из этой книги, и именно поэтому глава сначала взял эту книгу от amazon.So если и новички, то попробуйте Бостон, MARČANA, vogella tutorils или и можно попробовать Android tutorials from google и тот же вопрос, вы можете обратиться к Recommend a good Android tutorial with Step by Step examples

0

Одна из других проблем с этим является то, что RSS канал, как из время написания книги было единственным сообщением, и теперь это список последние тридцать дней ежедневного фида. Это привело меня к той же проблеме. Поэтому для обработки рабочего приложения необходимо было обновить обработку XML и использовать AsyncTask.

0

Два clases решена:

1 - IotdHandler:

package com.headfirstlab.nasadailyimage; 

    import android.support.v7.app.ActionBarActivity; 
    import android.os.Bundle; 
    import android.view.Menu; 
    import android.view.MenuItem; 
    import android.widget.ImageView; 
    import android.widget.TextView; 

    public class NasaDailyImage extends ActionBarActivity { 

    IotdHandler iotdHandler = new IotdHandler(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_nasa_daily_image); 

    IotdHandler handler = new IotdHandler(); 

    handler.processFeed(); 
    resetDisplay(iotdHandler.getTitle(), iotdHandler.getDate(), 
      iotdHandler.getUrl(), iotdHandler.getDescription()); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.nasa_daily_image, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

private void resetDisplay(String title, String date, 
     String imageUrl, String description) { 

    TextView titleView = (TextView)findViewById(R.id.imageTitle); 

    titleView.setText(title); 

    TextView dateView = (TextView)findViewById(R.id.imageDate); 

    dateView.setText(date); 

    ImageView imageView =(ImageView)findViewById(R.id.imageDisplay); 

    imageView.setImageBitmap(iotdHandler.getUrl()); 
    imageView.setImageBitmap(IotdHandler.getBitmap(iotdHandler.getUrl())); 
    TextView descriptionView = (TextView)findViewById(R.id.imageDescription); 

    descriptionView.setText(description); 


    } 
} 

2 - NasaDailyImage:

package com.headfirstlab.nasadailyimage; 

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class NasaDailyImage extends ActionBarActivity { 

IotdHandler iotdHandler = new IotdHandler(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_nasa_daily_image); 

    IotdHandler handler = new IotdHandler(); 

    handler.processFeed(); 
    resetDisplay(iotdHandler.getTitle(), iotdHandler.getDate(), 
      iotdHandler.getUrl(), iotdHandler.getDescription()); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.nasa_daily_image, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

private void resetDisplay(String title, String date, 
     String imageUrl, String description) { 

    TextView titleView = (TextView)findViewById(R.id.imageTitle); 

    titleView.setText(title); 

    TextView dateView = (TextView)findViewById(R.id.imageDate); 

    dateView.setText(date); 

    ImageView imageView =(ImageView)findViewById(R.id.imageDisplay); 

    imageView.setImageBitmap(IotdHandler.getBitmap(iotdHandler.getUrl())); 
    TextView descriptionView = (TextView)findViewById(R.id.imageDescription); 

    descriptionView.setText(description); 


    } 
} 

надеюсь, что вы найдете его полезным:)

Смежные вопросы