Avatar billede kentora Nybegynder
02. december 2010 - 10:15 Der er 6 kommentarer og
1 løsning

Android filhåndtering

Jeg skal have lavet en fil til at gemme nogle oplysninger i, men når jeg bruger nedenstående kode, kommer den med masser af fejl:

    InputStream in =openFileInput("number.txt");
    byte b[]=new byte [in.available()];
    in.read(b);
    String fileData=new String(b);
    Toast.makeText(this, fileData, Toast.LENGTH_LONG).show();

Fejlmeldinger:

- The method openFileInput(String) is undefined for the type  TestWidget
- number cannot be resolved to a variable
- InputStream cannot be resolved to a type
- Syntax error on token "b", VariableDeclaratorId expected after
this token
- Syntax error on token(s), misplaced construct(s)
- Syntax error on token "(", = expected
- Syntax error on token(s), misplaced construct(s)
- Syntax error on token(s), misplaced construct(s)
- Syntax error on token ")", delete this token
- Syntax error on token "show", Identifier expected after
this token

Dette er min 2. widget, og jeg fåver der er nogle der kan hjælpe mig.
Avatar billede kentora Nybegynder
02. december 2010 - 10:15 #1
laver*
Ved ikke lige hvad der gik galt. xD
Avatar billede arne_v Ekspert
02. december 2010 - 13:12 #2
InputStream cannot be resolved to a type

du mangler at importere java.io.InputStream
Avatar billede arne_v Ekspert
02. december 2010 - 13:14 #3
The method openFileInput(String) is undefined for the type  TestWidget

må betyde at:

InputStream in =openFileInput("number.txt");

skal være:

InputStream in = etellerandet.openFileInput("number.txt");
Avatar billede kentora Nybegynder
02. december 2010 - 16:06 #4
Hvad skal der stå foran openFileInput(..)?
Avatar billede arne_v Ekspert
02. december 2010 - 22:31 #5
et objekt eller en klasse med den metode
Avatar billede kentora Nybegynder
07. december 2010 - 16:17 #6
Hmm.. Her er koden jeg gerne vil have det ind i:

/**
* @author Gordon Endersby
* Example Android widget to receive xml and display
* it a formatted manner on the home screen
*
*/

package dk.nextsms.android.widget;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.util.Log;

/**
* The class representing our widget
*
*/


public class NextSMSWidget extends AppWidgetProvider {
   
    // Global variables
    private String wStationURLXml = "http://example.com/test.php"; // Url for the xml

   
    /**
    * Gets the component name representing this widget.
    * Needed in onReceive to get the WidgetIds.
    */
    static final ComponentName THIS_APPWIDGET =
        new ComponentName("dk.nextsms.android.widget", "dk.nextsms.android.widget.NextSMSWidget");

    /*
    * Override of android.appwidget.AppWidgetProvider#onReceive(android.content.Context, android.content.Intent)
    * Receives any Intents aimed at the widget as defined in the widgets manifest.
    * In this case listens for the click on the title text field in the widget
    */
    @Override
    public void onReceive(Context context, Intent intent)
    {
        super.onReceive(context, intent);
       
        String text = "";
               
        // Is this our click intent
        if(intent.getAction().equals("dk.nextsms.android.widget.CLICK"))
        {
            // Get the AppWidgetManager and AppWidgetIds from the context as they are out
            // of scope of this overridden method.
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            int[] appWidgetIds = appWidgetManager.getAppWidgetIds(THIS_APPWIDGET);

            // Display a warning that the text is updating
            UpdateTextField(context, appWidgetManager, appWidgetIds, "Opdaterer");
            // Get the text to display
            text =  GetText( wStationURLXml);
            // Display the text in the widget
            UpdateTextField(context, appWidgetManager, appWidgetIds, text);
        }
    }

    /*
    * Override of android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[])
    * Specific to this widget. Called by the home screen when it needs all the widgets
    * on the screen to be updated and when the widget is first added to the home screen.
    */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        String text = "";
       
        // Adds the onClick action to all instances of the widget
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++)
        {
            int[] appWidgetId = appWidgetIds;
            RemoteViews views=new RemoteViews(context.getPackageName(), R.layout.main);
            Intent clickintent=new Intent("dk.nextsms.android.widget.CLICK");
            PendingIntent pendingIntentClick=PendingIntent.getBroadcast(context, 0, clickintent, 0);
            views.setOnClickPendingIntent(R.id.title, pendingIntentClick);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }

        // Display a warning that the text is updating
        UpdateTextField(context, appWidgetManager, appWidgetIds, "Updating");
        // Get the text to display
        text =  GetText( wStationURLXml);
        // Display the text in the widget
        UpdateTextField(context, appWidgetManager, appWidgetIds, text);

    }

    /**
    * Gets the value from the tag without formatting
    * @param tag    - Name of tag
    * @param doc    - DOM representing the XML
    * @return        - String value
    */
    private static String getTagValue(String tag, Document doc) {
        Element intElement = (Element) doc.getElementsByTagName(tag).item(0);
        return intElement.getChildNodes().item(0).getNodeValue();
    }

    /**
    * Gets the value from the tag with a little padding out of the returned string
    * @param tag    - Name of tag
    * @param doc    - DOM representing the XML
    * @return        - String value
    */
    private static String getTagValueTemp(String tag, Document doc) {
        Element intElement = (Element) doc.getElementsByTagName(tag).item(0);
        String temp = intElement.getChildNodes().item(0).getNodeValue();
        if (temp.length() == 4){ temp = " " + temp;}
        return temp;
    }

    /**
    * Updates the text displayed in the widget
    * @param context            - Context of the widget and its environment on the home screen.
    * @param appWidgetManager    - widget manager.
    * @param appWidgetIds        - ID's of any instance of the widget on the home screens
    * @param text                - Text to display.
    */
    private static void UpdateTextField(Context context,AppWidgetManager appWidgetManager, int[] appWidgetIds, String text){
        // Change the text in the widget
        RemoteViews updateViews = new RemoteViews( context.getPackageName(), R.layout.main);
        updateViews.setTextViewText(R.id.text, text);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
    }

   
    /**
    * Gets the XML response from the server and formats it for display
    * @param siteUrl    - URL of server.
    * @return            - Returns text string.
    */
    private static String GetText( String siteUrl){
        String one = "";
       
        String text = "";
        Boolean success = true;

        Log.d("NextSMS Widget" ,"Text in" + text);
       
        try {
            // Get the xml from the server specified in siteUrl
            URL url = new URL(siteUrl);
           
            // Create a factory that will take the xml and turn it into
            //a DOM (Document Object Model)
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
           
            // Parse the stream of xml returned from the server to create the DOM in doc
            Document doc = dBuilder.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();
           
            // Get the contents of the tags we want to display
            one = getTagValue("main", doc);
           

        } catch (Exception e){
            // There's a lot that can go wrong here with the internet connection
            // so we catch exceptions and add them to the system log.
            // This is viewable while the Android device is connected to the
            // pc using the ddms tool supplied with the sdk.
            success = false;
            Log.d("NextSMS widget" ,e.toString());
            return e.toString();
        }
       
        // Build the text string to display
        if (success){
            Log.d("NextSMS WIdget" ,"Succses got xml, changing text");
            text = one;
           
        } else {
            text = "Unable to update";
       
        }
        Log.d("NextSMS Widget" ,"Text out" + text);
        // Return the text
        // If the fetch of the xml was unsuccessful keep the old text contents
        return text; // Return the text
    }

}

Jeg vil gerne have så den tjekker om filen eksisterer / indeholder et telefonnummer. Ellers skal den komme med en "Indtast nummer" side, og så gemme i filen. Ellers skal den hente indholdet i filen, og gemme i en variabel. Men kan ikke få det til at virke.. :(
Avatar billede kentora Nybegynder
11. december 2010 - 13:14 #7
Lukker...
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester