Android code basic rules for developers

read write file from to assets, sdcard,, internal directory, read bytes array,
open save file to sdcard or internal directory,
get file path,
write bytes array, dir reading, dir create,
for while calculation, read input , write output

android-example-code-rules
Download project bla.zip

public class MainActivity extends Activity {
	private TextView mTextView;
	private EditText mEditNumber;
	private EditText mEditText;
  private Button mButtonOK;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
 
		mTextView = (TextView)findViewById(R.id.textView1);
		mEditNumber = (EditText)findViewById(R.id.editTextNumber);
		mEditText = (EditText)findViewById(R.id.editTextText);
		mButtonOK = (Button)findViewById(R.id.buttonOK);
		mButtonOK.setOnClickListener(myhandler);
 
 
	}
 
 
 
  View.OnClickListener myhandler = new View.OnClickListener() {
    public void onClick(View v) {
    	if(mEditNumber.getText().toString().length()==0
    			|| mEditText.getText().toString().length()==0){
    		mTextView.setText("Put number and text to fields");
    		return;
    	}
 
    //variables and calculation
    	final String ROWEND = "\n";
    	int a=2;
    	int b=3;
    	int c=Integer.parseInt(mEditNumber.getText().toString());
    	mTextView.setText("");//  vymazat predchozi udaje
    	StringBuilder sOutput= new StringBuilder();
    	sOutput.append("Input number is: "+c+ROWEND);
    	sOutput.append(a+" * "+b+" = "+(a*b));
    	sOutput.append(ROWEND);
    	sOutput.append("a^3 = "+Math.pow(a,b));
    	sOutput.append(ROWEND);
 
    	//array
    	int[] arrayOfInt=new int[10];
    	arrayOfInt[0]=3;
    	arrayOfInt[1]=5;
    	sOutput.append("Count of elements "+arrayOfInt.length+"; 1 + 2 element of array "
         +(arrayOfInt[0]+arrayOfInt[1]));
    	sOutput.append(ROWEND);
 
    	// Strings
    	String txt="Quick red fox";
    	String txt2=mEditText.getText().toString();
    	sOutput.append("Input text: "+txt2);
    	sOutput.append(ROWEND);
    	String[] pocet_slov=txt.split(" ");
    	sOutput.append("Length: "+txt.length()+" Count of words "+pocet_slov.length);
    	sOutput.append(ROWEND);
    	sOutput.append(txt +" -> "+txt.replace("red","brown"));
    	sOutput.append(ROWEND);
    	sOutput.append("First 5 letters of string: "+ txt.substring(0,5));
    	sOutput.append(ROWEND);
 
    	//for a if
    	for(int i=0; i<5;i++){
    		if(i==3)sOutput.append("i is equal "+i);
    		}
    	sOutput.append("\n");
 
    	// prace se souborem
 
 
 
      try {
				// raw folders / read only
				// Resources res = getResources();
				// InputStream in = res.openRawResource(R.raw.myFile);
 
      	// if file is in assets folder / only read file
				AssetManager am = getApplicationContext().getAssets();
				InputStream in = am.open("soubor.txt");
				InputStreamReader is = new InputStreamReader(in);
 
				BufferedReader br = new BufferedReader(is);
				String read = br.readLine();
				while (read != null) {
					sOutput.append(read);
					sOutput.append("\n");
					read = br.readLine();
 
				}
 
 
				// internal app data folder / write file from  bytes array
				String FILENAME = "hello_file";
				String string = "hello world!\n diacritic ěščřžý";
 
				FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
				fos.write(string.getBytes());
				fos.close();
 
				 FileInputStream inp = openFileInput(FILENAME);
			    InputStreamReader inputStreamReader = new InputStreamReader(inp);
			    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			    StringBuilder sb = new StringBuilder();
			    String lineRead;
			    while ((lineRead = bufferedReader.readLine()) != null) {
			        sOutput.append(lineRead);
			        sOutput.append("\n");
			    }				
				// Returns the absolute path to the directory on the filesystem where 
			  // files created with openFileOutput(String, int) are stored.
        String sDir =  getFilesDir().getAbsolutePath(); // /data/data/com.example.bla/files
        sOutput.append(sDir+"\n");
 
      	// SDCARD
        File sdcard = Environment.getExternalStorageDirectory();
				// ///////////////
				// write to any temp file on sdcard
				// make permision in AndroidManifest.xml
				// <uses-permission
				// android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
				// <uses-permission
				// android:name="android.permission.READ_EXTERNAL_STORAGE" />
        Boolean canWrite =	Environment.getExternalStorageDirectory().canWrite() ;
        if(canWrite){
            File dir = new File (sdcard.getAbsolutePath() + "/mydir"); 
            // create dir on sdcard /storage/sdcard/mydir
           if(! dir.mkdirs()) sOutput.append("\nDir don't created\n"); // maybe exist
           // create temp file
            String SAMPLE_PREFIX = "tmp";
						String SAMPLE_EXTENSION = ".txt";
						File mSampleFile = File.createTempFile(SAMPLE_PREFIX,SAMPLE_EXTENSION, dir); 
            sOutput.append(mSampleFile.getAbsolutePath()); // /storage/sdcard/mydir/tmp567407.txt
            sOutput.append("\n");
 
           // FileOutputStream f = new FileOutputStream(mSampleFile);
            FileWriter fw = new FileWriter(mSampleFile);
            fw.append("My file\nSome text\nNext line");
            fw.close();
 
            if(mSampleFile.exists()){
            	br.close();
              br = new BufferedReader(new FileReader(mSampleFile));  
            	String line;   
            	while ((line = br.readLine()) != null) {
            		sOutput.append(line);
            		sOutput.append('\n');
            	} 
            	br.close();
            } else
            	sOutput.append("\nTemp file dont exist.\n");
 
            ////////////////////////////////
            // DIR
            ////////////////////////////////
 
            String[] fileNames = dir.list();
            if(dir.exists())
            	sOutput.append("\n"+"Name of first file in \"mydir\": "+fileNames[0]);
            else sOutput.append("\n"+"Dir dont exist");
 
        } else sOutput.append("\nCan't write to sdcard");     
      }
      catch (IOException e) {
          e.printStackTrace();
          System.out.println("hello");           
 
      }
 
 
    	//funkce
    	int vysledek = secti(3,5);
    	sOutput.append("\n"+"Result of function: "+vysledek);
    	sOutput.append(ROWEND);
 
    	mTextView.setText(sOutput);
    }
 
  };
 
///////////////
//nova funkce secti - samostatny blok za funkci main
public static int secti(int a, int b){
return (a+b);
}
 
 
 
 
 
 
 
	@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;
	}
 
}
This entry was posted in Android Examples Code and tagged , , , , , . Bookmark the permalink.


Comments are closed.



3,584 views