简体   繁体   中英

Java application reading name from a file

I am stuck trying to reading from a .txt file a name and last name into a java application, I have tryed on first method with AssetManager but my application Crash when I enter it.

The second method is with inputstream but I get 3 errors:

Description Resource    Path    Location    Type
ByteArrayOutputStream cannot be resolved to a type  MainActivity.java   /MyInfo/src/com/example/myinfo  line 64 Java Problem
ByteArrayOutputStream cannot be resolved to a type  MainActivity.java   /MyInfo/src/com/example/myinfo  line 64 Java Problem
dummytext cannot be resolved or is not a field  MainActivity.java   /MyInfo/src/com/example/myinfo  line 55 Java Problem

MainActivity.java

package com.example.myinfo;

import java.io.IOException;
import java.io.InputStream;

import android.os.Bundle;
import android.content.res.AssetManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    /*  
        TextView name = (TextView) findViewById(R.id.name);
        AssetManager assetManager = getAssets();



        InputStream input;
        try {

            input = assetManager.open("info.txt");

             int size = input.available();
             byte[] buffer = new byte[size];
             input.read(buffer);
             input.close();

             // byte buffer into a string
             String text = new String(buffer);

             nume.setText(text);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        */
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }


        TextView dummytext = (TextView) findViewById(R.id.dummytext);
        dummytext.setText(readText());



    }

    private String readText() {
        InputStream inputStream = getResources().openRawResource(R.raw.dummytext);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int i;
        try {
            i = inputStream.read();
            while(i!=-1){
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return byteArrayOutputStream.toString();

        }

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

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

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {



        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);

            return rootView;
        }
    }


}

and my XML is this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.myinfo.MainActivity$PlaceholderFragment" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="87dp"
        android:text="Adauga Fisier" />

    <TextView
        android:id="@+id/dummytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nume"
        android:layout_below="@+id/nume"
        android:layout_marginTop="29dp"
        android:text="Prenume"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/button1"
        android:layout_marginRight="14dp"
        android:layout_marginTop="65dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

I don't understand what I did wrong. When I run the code that is now in Comments I notice that I get in Logcat NullPointerException.

LogCat:

04-07 10:06:11.298: I/dalvikvm(275): Could not find method android.content.pm.PackageManager.getActivityLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.298: W/dalvikvm(275): VFY: unable to resolve virtual method 318: Landroid/content/pm/PackageManager;.getActivityLogo (Landroid/content/ComponentName;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.298: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x008b
04-07 10:06:11.308: I/dalvikvm(275): Could not find method android.content.pm.ApplicationInfo.loadLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.308: W/dalvikvm(275): VFY: unable to resolve virtual method 314: Landroid/content/pm/ApplicationInfo;.loadLogo (Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.308: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x0099
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x008e-0092 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x009c-00a0 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.488: D/AndroidRuntime(275): Shutting down VM
04-07 10:06:11.488: W/dalvikvm(275): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-07 10:06:11.498: E/AndroidRuntime(275): FATAL EXCEPTION: main
04-07 10:06:11.498: E/AndroidRuntime(275): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myinfo/com.example.myinfo.MainActivity}: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.os.Looper.loop(Looper.java:123)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-07 10:06:11.498: E/AndroidRuntime(275):  at java.lang.reflect.Method.invokeNative(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275):  at java.lang.reflect.Method.invoke(Method.java:521)
04-07 10:06:11.498: E/AndroidRuntime(275):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-07 10:06:11.498: E/AndroidRuntime(275):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-07 10:06:11.498: E/AndroidRuntime(275):  at dalvik.system.NativeStart.main(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275): Caused by: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275):  at com.example.myinfo.MainActivity.onCreate(MainActivity.java:42)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-07 10:06:11.498: E/AndroidRuntime(275):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-07 10:06:11.498: E/AndroidRuntime(275):  ... 11 more
04-07 10:06:18.688: I/Process(275): Sending signal. PID: 275 SIG: 9

use this code

`InputStream input;
 AssetManager assetManager = getAssets();
  try {
   input = assetManager.open("helloworld.txt");

   int size = input.available();
   byte[] buffer = new byte[size];
   input.read(buffer);
   input.close();

   // byte buffer into a string
   String text = new String(buffer);

   dummytext.setText(text);
  } catch (IOException e) {
      e.printStackTrace();
  }
`

This code open an InputStream for the file from assets manager, get size from file content, allocate byte buffer with this size and read file in this buffer, after this create new string from buffer and set this string to your textview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM