2016-03-16 2 views
-2

Кажется, мой код зацикливается в приложении и, следовательно, застревает. Данные успешно сохраняются в outputstream без проблем, но я почти уверен, что цикл вызывает проблему.Fileinputstream android looping не может загрузить активность данных, застрял

Heres мой XML для входного потока:

< ---------------------- Ланг-XML -------- ------->

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/edit_text_2_1" 
    android:hint="User name is gonna come here" 
    android:textSize="25dp" 
    /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/edit_text_2_2" 
    android:hint="pass name is gonna come here" 
    android:textSize="25dp" 
    android:layout_marginTop="25dp" 
    /> 
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/btn_edit_2_2" 
    android:text="load" 
    /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/btn_edit_2_3" 
    android:text="Go back" 
    /> 

</LinearLayout> 

< ------------- activity_second.java --------------->

package com.example.admin.file_view; 


import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
/** 
* Created by admin on 15-03-2016. 
*/ 
public class activity_second extends Activity{ 

TextView t1,t2; 
Button b1,b2; 
String name, pass; 

FileInputStream fos=null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_second); 
    t1=(TextView)findViewById(R.id.edit_text_2_1); 
    t2=(TextView)findViewById(R.id.edit_text_2_2); 
    b1=(Button)findViewById(R.id.btn_edit_2_2); 
    b2=(Button)findViewById(R.id.btn_edit_2_3); 
    b1.setOnClickListener(new View.OnClickListener() { 
     String temp; 

     int read=-1; 
     @Override 
     public void onClick(View v) { 
      try { 
       fos= openFileInput("haha.txt"); 
       StringBuffer biffer=new StringBuffer(); 

       while(fos.read()!=1) 
       { 
        biffer.append((char)fos.read()); 

       } 
       // char c=(char)fos.read(); 
       //Toast.makeText(getApplicationContext(),c+" is getting read",Toast.LENGTH_LONG).show(); 
     /*  while((read=fos.read())!=-1) 
       { 
       biffer.append((char)read); 
       }*/ 
       name=biffer.substring(0,biffer.indexOf(" ")); 
       pass=biffer.substring(biffer.indexOf(" ")+1); 
       t1.setText(name); 
       t2.setText(pass); 

      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    });}} 

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

< ------------- -MainActivity.java -------------->

package com.example.admin.file_view; 

import android.app.Activity; 
import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 

public class MainActivity extends Activity { 

    TextView t1,t2; 
    Button b1,b2; 
    String name, pass; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     t1=(TextView)findViewById(R.id.edit_txt1); 
     t2=(TextView)findViewById(R.id.edit_txt2); 
     b1=(Button)findViewById(R.id.btn_edit_1); 
     b2=(Button)findViewById(R.id.btn_edit_2); 

     b1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       name= t1.getText().toString(); 
       pass=t2.getText().toString(); 
       FileOutputStream fos= null; 
       try { 
        fos = openFileOutput("haha.txt",MODE_PRIVATE); 
        fos.write(t1.getText().toString().getBytes()); 
        fos.write(pass.getBytes()); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       finally { 
        try { 
         if (fos != null) { 
          fos.close(); 
         } 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 

       Toast.makeText(getApplicationContext(),"data saved successfully",Toast.LENGTH_SHORT).show(); 

      } 
     }); 

     b2.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent=new Intent(getApplication(),activity_second.class); 
       startActivity(intent); 
      } 
     });}} 

< ------------------- выход. XML -------->

<?xml version="1.0" encoding="utf-8"?> 
<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.admin.file_view.MainActivity"> 

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/edit_txt1" 
    android:hint="Enter the username" 
    android:textSize="25dp" 
    /> 

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/edit_txt2" 
    android:layout_below="@+id/edit_txt1" 
    android:hint="Enter pass" 
    android:textSize="25dp" 
    android:layout_marginTop="25dp" 
    /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/edit_txt2" 
    android:id="@+id/btn_edit_1" 
    android:text="save" 
    android:textSize="25dp" 
    /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/edit_txt2" 
    android:id="@+id/btn_edit_2" 
    android:layout_toRightOf="@id/btn_edit_1" 
    android:text="nextpage" 
    android:textSize="25dp" 
    /> 

</RelativeLayout> 


[1]: http://i.stack.imgur.com/bOqgl.png 
+0

Это очень трудно прочитать из-за его форматирования. –

+0

Нам не нужно видеть ваш огромный графический интерфейс пользователя. – EJP

+0

вы должны назвать это основной темой. –

ответ

0
while(fos.read()!=1) 
{ 
    biffer.append((char)fos.read()); 
} 

Этот код просто вздор. Он пропускает каждый байт с нечетным номером. И вы должны использовать FileReader и буфер.

int count; 
char charBuffer = new char[8192]; 
FileReader reader = new FileReader(...); 
while ((count = reader.read(charBuffer)) > 0) 
{ 
    buffer.append(charBuffer, 0, count); 
} 
reader.close(); 
+0

спасибо за всю помощь EJP, но буфера String не является хорошим выбором и вообще что происходит с моим кодом? У меня никогда не было java exp, поэтому видео и некоторые вещи на stackoveflow делают мой день: | –

+0

@ranjanjoishi Я ничего не понимаю. 'StringBuffer' был вашим выбором, а не моим. Это даже не упоминается в моем ответе. Если вам это не нравится, используйте 'StringBuilder'. Ничего общего со мной. И вообще, что происходит с моим кодом? не имеет смысла. Когда вы пробовали это, дайте нам знать. – EJP

+0

haha ​​ok thanks EJP :) –