Android OutputStreamWriter not creating file - android

I am trying to write data from EditText fields to a text file. I have verified that the data is being captured for output in an EditText field that I populate after clicking the Add button. The program runs successfully in the Emulator, but no output file is created. I have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" to the Android Manifest xml file. LogCat & Console do not show any errors. I have tried several different methods after reseaching examples here, but no luck. Can anyone point out my issue? Thanks in advance for your help.
package john.BRprogram;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
//import android.graphics.Color;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class BRprogramActivity extends Activity implements OnItemSelectedListener {
private static final String TAG = null;
//
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
Button addButton;
Button editButton;
Button sendButton;
//
Spinner array_spinner;
//
// activate soft Keyboard
this.getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
//
// .csv comma separated values file
//
try {
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.brdata));
//
List<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
String data = (scanner.next()); //read data record
String [] values = data.split(","); //parse data to fields
// String [] values = data.split(",(?=([^\"]\"[^\"]\")[^\"]$)");
if(values.length != 3)
Log.v("Example", "Malformed row: " + data);
else
list.add(values[0] + " " + values[1] + " $" + values[2]);
}
//
array_spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
array_spinner.setAdapter(adapter);
array_spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
//
scanner.close();
//
} catch (Exception e) {
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
//
addButton = (Button) findViewById(R.id.addbutton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
// get customer number,itemnumber,quantity,price
//
String writeCustomer = ((EditText) findViewById(R.id.editText1)).getText().toString().trim();
// itemNumber from list selection
String writeQuantity = ((EditText) findViewById(R.id.editText2)).getText().toString().trim();
String writePrice = ((EditText) findViewById(R.id.editText3)).getText().toString().trim();
//
String newRecord = writeCustomer + "," + writeQuantity + "," + writePrice;
EditText myString = (EditText)findViewById(R.id.editText4);
myString.setText(newRecord);
//
// write seq to output file
//
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("broutput.txt",0));
out.write(newRecord);
out.close();
}catch (Exception e){
Log.v("test", "record written");
}
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "ADD button clicked");
}
});
//
editButton = (Button) findViewById(R.id.editbutton);
editButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Log.v("test", "EDIT button clicked");
}
});
//
sendButton = (Button) findViewById(R.id.sendbutton);
sendButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "SEND button clicked");
}
});
}
// *** http://www.youtube.com/watch?v=Pfasw0bbe_4 ***
//
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//
String selection = parent.getItemAtPosition(position).toString();
String [] priceField = selection.split("\\$"); //parse price field
String [] item = selection.split("_"); //parse item number
String itemNumber = item[0];
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText(priceField[1]);
}
//
public void onNothingSelected(AdapterView<?> arg0) {
//nothing here
}
}

Looks like you need to create and/or specify the directory where you wish to save the file. I didn't see that anywhere in your code. It might look something like this:
if (Environment.getExternalStorageState() == null) {
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}
When you save data from your app, you have to remember that it is running on the Android, and not your computer, so all data is going to be written to your Android, not your comp. You have to pull the data after it is written to view it. Make sure you that you created a local directory on your device and make sure you check for an SD card. The code I listed will show you how to do everything you need.
Hope this helps!

I've actually experienced a problem like this; everything seemed fine, but my code wasn't working. My problem was the characters in the file name I was writing. For example, I tried writing the file name my_file - date 07/11/2012. This caused problems because it treated each / as a cue to begin a new directory! For this reason, I discovered I could not have any / (or :, for some reason) in my file names. Would this be your problem?
If this is your problem, then you could do what I did: perform a newRecord.replace('/', '-'); to replace all / in your file name with a - (if you are fine with having -'s instead).
On a side note, why are you logging "record written" in your the catch of your try/catch statement? If it catches a problem, doesn't that mean it wasn't written?

Related

Generate PDF file and attach to e-mail

first post here.
I have read all similar posts without finding any answer, i'm a newbie at dev in general.
Here is what i'm looking for:
On button click, the code generates a PDF with some info, and i just want to send the created pdf by mail.
First problem is when i choose an email app to send the mail, i got a message "Impossible to attach file".
Second problem is that the created file is not readable on the phone while it's readable on PC.
By searching i found out that it may be in relation with permission. I tried setReadablemethod without result. Android studio makes a hint (result of setReadable is ignored).
Code :
public class VerifList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verif_list);
//Variables
//Strings
final String name;
final String myFormat;
//Others
final Calendar calendar;
final SimpleDateFormat sdf;
final String datePdf;
//Buttons
Button endControlButton;
//TextView
TextView title;
TextView date;
//Edit Text
final EditText oil_TV;
final EditText engine_liquid_TV;
EditText wipers_liquid_TV;
EditText breaks_liquid_TV;
EditText windows_TV;
EditText wipers_TV;
EditText mirrors_TV;
EditText numberplate_TV;
EditText frontTires_TV;
EditText rearTires_TV;
EditText tiresState_TV;
EditText light1_TV;
EditText light2_TV;
EditText light3_TV;
EditText light4_TV;
EditText light5_TV;
EditText light6_TV;
EditText light7_TV;
EditText interiorClean_TV;
EditText exteriorClean_TV;
EditText jacket_TV;
EditText triangle_TV;
EditText strap_TV;
EditText extinguisher_TV;
//Set title text
title = findViewById(R.id.title_TV);
Bundle extras = getIntent().getExtras();
assert extras != null;
name = extras.getString("name");
title.setText(name);
//Display date
date = findViewById(R.id.date_TV);
calendar = Calendar.getInstance();
myFormat = "dd/MM/yy";
sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
date.setText("Date du contrôle : " + sdf.format(calendar.getTime()));
datePdf = calendar.getTime().toString();
//Variables declaration
oil_TV = findViewById(R.id.oil_TV);
engine_liquid_TV = findViewById(R.id.engine_liquid_TV);
wipers_liquid_TV = findViewById(R.id.wipers_liquid_TV);
breaks_liquid_TV = findViewById(R.id.breaks_liquid_TV);
windows_TV = findViewById(R.id.windows_TV);
wipers_TV = findViewById(R.id.wipers_TV);
mirrors_TV = findViewById(R.id.mirrors_TV);
numberplate_TV = findViewById(R.id.numberplate_TV);
frontTires_TV = findViewById(R.id.frontTires_TV);
rearTires_TV = findViewById(R.id.rearTires_TV);
tiresState_TV = findViewById(R.id.tiresState_TV);
light1_TV = findViewById(R.id.light1_TV);
light2_TV = findViewById(R.id.light2_TV);
light3_TV = findViewById(R.id.light3_TV);
light4_TV = findViewById(R.id.light4_TV);
light5_TV = findViewById(R.id.light5_TV);
light6_TV = findViewById(R.id.light6_TV);
light7_TV = findViewById(R.id.light7_TV);
interiorClean_TV = findViewById(R.id.interiorClean_TV);
exteriorClean_TV = findViewById(R.id.exteriorClean_TV);
jacket_TV = findViewById(R.id.jacket_TV);
triangle_TV = findViewById(R.id.triangle_TV);
strap_TV = findViewById(R.id.strap_TV);
extinguisher_TV = findViewById(R.id.extinguisher_TV);
//Création de listes
final ArrayList textViewArray = new ArrayList(24);
//TextViews
textViewArray.add(oil_TV);
textViewArray.add(engine_liquid_TV);
textViewArray.add(wipers_liquid_TV);
textViewArray.add(breaks_liquid_TV);
textViewArray.add(windows_TV);
textViewArray.add(wipers_TV);
textViewArray.add(mirrors_TV);
textViewArray.add(numberplate_TV);
textViewArray.add(frontTires_TV);
textViewArray.add(rearTires_TV);
textViewArray.add(tiresState_TV);
textViewArray.add(light1_TV);
textViewArray.add(light2_TV);
textViewArray.add(light3_TV);
textViewArray.add(light4_TV);
textViewArray.add(light5_TV);
textViewArray.add(light6_TV);
textViewArray.add(light7_TV);
textViewArray.add(interiorClean_TV);
textViewArray.add(exteriorClean_TV);
textViewArray.add(jacket_TV);
textViewArray.add(triangle_TV);
textViewArray.add(strap_TV);
textViewArray.add(extinguisher_TV);
//Déclaration du bouton Fin de controle
endControlButton = findViewById(R.id.end_control_button);
endControlButton.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetWorldReadable")
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
//Création du pdf
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300,600,1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setTextSize(30);
canvas.drawText(name,50,30,paint);
for (int i = 0 ; i<textViewArray.size();i++){
EditText editText = (EditText) textViewArray.get(i);
String editTextDesc = (String) editText.getContentDescription();
String content = editText.getText().toString();
Boolean isEmpty = content.isEmpty();
if (!isEmpty) {
paint.setTextSize(10);
paint.setColor(Color.RED);
canvas.drawText(editTextDesc + " : " + content, 50 , 50 + (20 * i),paint);
} else {
paint.setTextSize(10);
paint.setColor(Color.BLACK);
canvas.drawText(editTextDesc + " : OK",50, 50 + (20 * i),paint);
}
}
document.finishPage(page);
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/ATTM
Vehicules/";
File file = new File(directory_path);
if (!file.exists()){
file.mkdirs();
}
String targetPdf = directory_path + name + datePdf +".pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
Toast.makeText(getApplicationContext(), "Envoyé", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("main", "error "+e.toString());
Toast.makeText(getApplicationContext(), "Erreur" + e.toString(), Toast.LENGTH_LONG).show();
}
document.close();
//Mail
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "email#hotmail.fr" });
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "test ");
shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(targetPdf));
startActivity(shareIntent);
}
});
}
}
Any help would be appreciated. Thanks for reading!
Try the below code in your Activity..
package com.example.pdfshare;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.FileProvider;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintAttributes.Margins;
import android.print.PrintAttributes.Resolution;
import android.print.pdf.PrintedPdfDocument;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity implements Runnable {
private Intent mShareIntent;
private OutputStream os;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** PDF Gen should run in own thread to not slow the GUI */
public void makeAndSharePDF(View buttonSource) {
new Thread(this).start();
}
public void run() {
// Create a shiny new (but blank) PDF document in memory
// We want it to optionally be printable, so add PrintAttributes
// and use a PrintedPdfDocument. Simpler: new PdfDocument().
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new Resolution("zooey", PRINT_SERVICE, 300, 300)).
setMinMargins(Margins.NO_MARGINS).
build();
PdfDocument document = new PrintedPdfDocument(this, printAttrs);
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textArea);
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
// Here you could add more pages in a longer doc app, but you'd have
// to handle page-breaking yourself in e.g., write your own word processor...
// Now write the PDF document to a file; it actually needs to be a file
// since the Share mechanism can't accept a byte[]. though it can
// accept a String/CharSequence. Meh.
try {
File pdfDirPath = new File(getFilesDir(), "pdfs");
pdfDirPath.mkdirs();
File file = new File(pdfDirPath, "pdfsend.pdf");
Uri contentUri = FileProvider.getUriForFile(this, "com.example.fileprovider", file);
os = new FileOutputStream(file);
document.writeTo(os);
document.close();
os.close();
shareDocument(contentUri);
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}
private void shareDocument(Uri uri) {
mShareIntent = new Intent();
mShareIntent.setAction(Intent.ACTION_SEND);
mShareIntent.setType("application/pdf");
// Assuming it may go via eMail:
mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "Here is a PDF from PdfSend");
// Attach the PDf as a Uri, since Android can't take it as bytes yet.
mShareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(mShareIntent);
return;
}
#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;
}
}
The above code is self explanatory with comments.. All the Best..

Can't find method on extension class:

Hi Im making an android native extension in Gamemaker: Studio and when I run the game and try to use the extension i get this error code in the runner command window:
Can't find method on extension class:folderLoader[double, double]
It does not crash the game or throw any other errors, it just can't find my method in the java file. this is how I have it set up:
edit extension package properties-general tab-
name- DirectoryPicker
android checkbox ticked
inject to manifest-
<activity
android:name="${YYAndroidPackageName}.DirectoryPicker"
android:label="DirectoryPicker" />
inject to gradle (to activate my styles.xml)-
compile 'com.android.support:appcompat-v7:+'
edit extension package properties-android tab-
Class name- DirectoryPicker
Permissions- android.permission.WRITE_EXTERNAL_STORAGE
edit extension file properties box-
name- DirectoryPicker.extension.gmx
init function- set to folderLoader
copys to- ticked android and android yyc boxes only
edit extension functions box-
name- folderLoader
external name- folderLoader
help- folderLoader(double FolderOnly, double ShowHidden)
return type box- selected double
key and value box- argument 0 double argument1 double
the calling code for an object's left mouse pressed event:
folderLoader(1.0, 0.0);
the async event in the same object (set to social event):
var type2 = string(async_load[? "type2"])
var data2 = string(async_load[? "folder"])
if type2 == "folderFound"
{
var text = data2;
}
the java file- named DirectoryPicker.java
package ${YYAndroidPackageName};
import ${YYAndroidPackageName}.R;
import ${YYAndroidPackageName}.RunnerActivity;
import com.yoyogames.runner.RunnerJNILib;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class DirectoryPicker extends ListActivity {
private static final int EVENT_OTHER_SOCIAL = 70;
public static final String ONLY_DIRS = "onlyDirs";
public static final String SHOW_HIDDEN = "showHidden";
public static final String CHOSEN_DIRECTORY = "chosenDir";
public static final int PICK_DIRECTORY = 43522432;
private File dir;
private boolean onlyDirs = true;
private boolean showHidden = false;
public void folderLoader(double yesOrNo,double noOrYes)
{
if(yesOrNo == 0.0) onlyDirs = false;
if(yesOrNo == 1.0) onlyDirs = true;
if(noOrYes == 0.0) showHidden = false;
if(noOrYes == 1.0) showHidden = true;
findFolders();
}
public void findFolders() {
Bundle extras = getIntent().getExtras();
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
dir = new File(Root.getAbsolutePath());
}
if (extras != null) {
showHidden = extras.getBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.getBoolean(ONLY_DIRS, true);
}
setContentView(R.layout.chooser_list);
setTitle(dir.getAbsolutePath());
Button btnChoose = (Button) findViewById(R.id.btnChoose);
String name = dir.getName();
if(name.length() == 0)
name = "No folders found";
btnChoose.setText(name);
btnChoose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
returnDir(dir.getAbsolutePath());
}
});
ListView lv = getListView();
lv.setTextFilterEnabled(true);
if(!dir.canRead()) {
Context context = getApplicationContext();
String msg = "Could not read folders.";
Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
toast.show();
return;
}
final ArrayList<File> files = filter(dir.listFiles(), onlyDirs, showHidden);
String[] names = names(files);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, names));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!files.get(position).isDirectory())
return;
String path = files.get(position).getAbsolutePath();
Intent intent = new Intent((RunnerActivity.CurrentActivity), DirectoryPicker.class);
intent.putExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.putExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
(RunnerActivity.CurrentActivity).startActivityForResult(intent, PICK_DIRECTORY);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_DIRECTORY && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
String path = (String) extras.get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
int dsMapIndex = RunnerJNILib.jCreateDsMap(null, null, null);
RunnerJNILib.DsMapAddString( dsMapIndex, "type2", "folderFound" );
RunnerJNILib.DsMapAddString( dsMapIndex, "folder", path );
RunnerJNILib.CreateAsynEventWithDSMap(dsMapIndex, EVENT_OTHER_SOCIAL);
}
}
private void returnDir(String path) {
Intent result = new Intent();
result.putExtra(CHOSEN_DIRECTORY, path);
setResult(RESULT_OK, result);
finish();
}
public ArrayList<File> filter(File[] file_list, boolean onlyDirs, boolean showHidden) {
ArrayList<File> files = new ArrayList<File>();
for(File file: file_list) {
if(onlyDirs && !file.isDirectory())
continue;
if(!showHidden && file.isHidden())
continue;
files.add(file);
}
Collections.sort(files);
return files;
}
public String[] names(ArrayList<File> files) {
String[] names = new String[files.size()];
int i = 0;
for(File file: files) {
names[i] = file.getName();
i++;
}
return names;
}
}
There are 2 related xml files that i put in the layout folder which i put in the res folder, which is in the AndroidSource folder.
I have also downloaded some extensions to see how they did them, and they all have a file in the android source folder called yymanifest.xml, which is generated by gamemaker, this file never gets created in my extension project, I've tried saving, exporting the extension and re importing it but the file is never there, and it's not a file you can make yourself, gamemaker has to produce it when it makes the extension, but how can I get it to do this???
Any ideas or help would be greatly appreciated
Well everything seems fine you need to mention you folder in menifest file.

How to select a file from Android Emulator?

These are the codes which appeared to have no error but activity stops when I clicked on the Select File button. I wish to upload a file to Amazon S3 but I have to choose a file before uploading. The File I wish to upload is from "Downloads" of the emulator.
Anyone know what's wrong?
package sit.nyp.edu.sg.filepicker;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class FilePicker2Activity extends Activity {
/** Called when the activity is first created. */
TextView textFile, textFileName, textFolder;
TextView textFileName_WithoutExt, textFileName_Ext;
private static final int PICKFILE_RESULT_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPick = (Button)findViewById(R.id.buttonpick);
textFile = (TextView)findViewById(R.id.textfile);
textFolder = (TextView)findViewById(R.id.textfolder);
textFileName = (TextView)findViewById(R.id.textfilename);
textFileName_WithoutExt = (TextView)findViewById(R.id.textfilename_withoutext);
textFileName_Ext = (TextView)findViewById(R.id.textfilename_ext);
buttonPick.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_PICK);
intent.setType("file/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
String FilePath = data.getData().getPath();
String FileName = data.getData().getLastPathSegment();
int lastPos = FilePath.length() - FileName.length();
String Folder = FilePath.substring(0, lastPos);
textFile.setText("Full Path: \n" + FilePath + "\n");
textFolder.setText("Folder: \n" + Folder + "\n");
textFileName.setText("File Name: \n" + FileName + "\n");
filename thisFile = new filename(FileName);
textFileName_WithoutExt.setText("Filename without Ext: " + thisFile.getFilename_Without_Ext());
textFileName_Ext.setText("Ext: " + thisFile.getExt());
}
break;
}
}
private class filename{
String filename_Without_Ext = "";
String ext = "";
filename(String file){
int dotposition= file.lastIndexOf(".");
filename_Without_Ext = file.substring(0,dotposition);
ext = file.substring(dotposition + 1, file.length());
}
String getFilename_Without_Ext(){
return filename_Without_Ext;
}
String getExt(){
return ext;
}
}
}
My guess is that, you dont have any file browser apps which can handle get content intent on the emulator, though if you post the log , can come to conclusion clearly.

Storing user input data in Internal Memory

I'm tryin to create a simple app that basically is a tracker that keeps track of no. of classes for each subject for a college student. The app is specific to my college timetable. The idea is tht i have 3 activities: main.java, Sublist.java and editcrap.java. The main.java acts as a splash screen and starts the Sublist activity.
In the Sublist activity the user is displayed with a layout displaying (TextView) (Button) (Counter_TextView) horizontally with respect ot each other. There are 7 of these aligned vertically.
When the menu button is clicked: (Edit Subject Parameters) comes up which wen clicked takes the user to editcrap.java activity where the user input is taken in corresponding EditText boxes asking for subject name for each corresponding (TextView) and total number of classes corresponding to (Counter_TextView) in the Sublist activity. On the click of OK button the data is passed bak to Sublist activity for display and manipulation.
Having done this I needed a way to store the data so tht the next time the app is opened it wud retain its previous string and no. of classes values. This is where I'm running into force close errors or No retention of data error. Here is my code...cud someone please tell me wat m doin wrong? I've been struggling for days with this :) I basically need the app to maintain 2 files one containing Strings and the other Numbers that need to be read from and displayed in Sublist.java activity as we i need any changes done by the app user to be reflected unto the original files as well
//Sublist.java:
package com.shuaib669.bunkrecord;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Sublist extends Activity{
double[] no_of_classes = new double[7];
int count[]= new int[7];
double cutOff = 0.3;
String[] newText = new String[7];
String[] newNum = new String[7];
String countString = null;
TextView subject[] = new TextView[7];
TextView counter[] = new TextView[7]; //sub11 is counter text view label
Button button[] = new Button[7]; //button1 is the increment button
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Assigning Views to objects.
subject[0] = (TextView) findViewById(R.id.textView1);
counter[0] = (TextView) findViewById(R.id.counter1);
button[0] = (Button) findViewById(R.id.button1);
subject[1] = (TextView) findViewById(R.id.textView2);
counter[1] = (TextView) findViewById(R.id.counter2);
button[1] = (Button) findViewById(R.id.button2);
subject[2] = (TextView) findViewById(R.id.textView3);
counter[2] = (TextView) findViewById(R.id.counter3);
button[2] = (Button) findViewById(R.id.button3);
subject[3] = (TextView) findViewById(R.id.textView4);
counter[3] = (TextView) findViewById(R.id.counter4);
button[3] = (Button) findViewById(R.id.button4);
subject[4] = (TextView) findViewById(R.id.textView5);
counter[4] = (TextView) findViewById(R.id.counter5);
button[4] = (Button) findViewById(R.id.button5);
subject[5] = (TextView) findViewById(R.id.textView6);
counter[5] = (TextView) findViewById(R.id.counter6);
button[5] = (Button) findViewById(R.id.button6);
subject[6] = (TextView) findViewById(R.id.textView7);
counter[6] = (TextView) findViewById(R.id.counter7);
button[6] = (Button) findViewById(R.id.button7);
try {
// open the file for reading
DataInputStream in= new DataInputStream(openFileInput(getFilesDir() + "/" + "subject.txt"));
// if file the available for reading
if (in!= null) {
// prepare the file for reading
String line;
int x=0;
// read every line of the file into the line-variable, on line at the time
while(in.readLine() != null) {
// do something with the strings from the file
line=DataInputStream.readUTF(in);
subject[x].setTextColor(Color.BLACK);
subject[x].setText(line);
x+=1;
}
}
// close the file again
in.close();
}
catch (Exception e) {
e.printStackTrace();// do something if the myfilename.txt does not exits
}
button[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[0]>=(no_of_classes[0]*cutOff)){
counter[0].setTextColor(Color.RED);
countString = "" +(++count[0]); //Convert from int to String to set in your textview::
counter[0].setText(countString);
}
else{
countString = "" +(++count[0]); //Convert from int to String to set in your textview::
counter[0].setText(countString);
}
}
});
button[1].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[1]>=(no_of_classes[1]*cutOff)){
counter[1].setTextColor(Color.RED);
countString = "" +(++count[1]); //Convert from int to String to set in your textview::
counter[1].setText(countString);
}
else{
countString = "" +(++count[1]); //Convert from int to String to set in your textview::
counter[1].setText(countString);
}
}
});
button[2].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[2]>=(no_of_classes[2]*cutOff)){
counter[2].setTextColor(Color.RED);
countString = "" +(++count[2]); //Convert from int to String to set in your textview::
counter[2].setText(countString);
}
else{
countString = "" +(++count[2]); //Convert from int to String to set in your textview::
counter[2].setText(countString);
}
}
});
button[3].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[3]>=(no_of_classes[3]*cutOff)){
counter[3].setTextColor(Color.RED);
countString = "" +(++count[3]); //Convert from int to String to set in your textview::
counter[3].setText(countString);
}
else{
countString = "" +(++count[3]); //Convert from int to String to set in your textview::
counter[3].setText(countString);
}
}
});
button[4].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[4]>=(no_of_classes[4]*cutOff)){
counter[4].setTextColor(Color.RED);
countString = "" +(++count[4]); //Convert from int to String to set in your textview::
counter[4].setText(countString);
}
else{
countString = "" +(++count[4]); //Convert from int to String to set in your textview::
counter[4].setText(countString);
}
}
});
button[5].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[5]>=(no_of_classes[5]*cutOff)){
counter[5].setTextColor(Color.RED);
countString = "" +(++count[5]); //Convert from int to String to set in your textview::
counter[5].setText(countString);
}
else{
countString = "" +(++count[5]); //Convert from int to String to set in your textview::
counter[5].setText(countString);
}
}
});
button[6].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[6]>=(no_of_classes[6]*cutOff)){
counter[6].setTextColor(Color.RED);
countString = "" +(++count[6]); //Convert from int to String to set in your textview::
counter[6].setText(countString);
}
else{
countString = "" +(++count[6]); //Convert from int to String to set in your textview::
counter[6].setText(countString);
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu){ // What the MENU button does.
super.onCreateOptionsMenu(menu);
MenuInflater castle = getMenuInflater();
castle.inflate(R.menu.main_menu, menu);
return(true);
}
public boolean onOptionsItemSelected(MenuItem item){ // Opens Options of MENU.
switch(item.getItemId()){
case R.id.editcrap: startActivityForResult((new Intent("com.shuaib669.bunkrecord.EDITCRAP")), 1);
return(true);
}
return(false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case 1: if(resultCode==Activity.RESULT_OK){
newText = data.getStringArrayExtra("com.shuaib669.bunkrecord.thetext");
newNum = data.getStringArrayExtra("com.shuaib669.bunkrecord.thenum");
try {
// open myfilename.txt for writing
DataOutputStream out = new DataOutputStream(openFileOutput(getFilesDir() + "/" + "subject.txt", Context.MODE_PRIVATE));
//newNum = data.getIntArrayExtra("com.shuaib669.thenum");
//for loop to setText in the TextViews of main.xml
for(int x=0;x<7;x++){
subject[x].setTextColor(Color.BLACK);
subject[x].setText(newText[x]);
// write the contents on mySettings to the file
out.writeUTF(newText[x]);
try{
no_of_classes[x]=Integer.parseInt(newNum[x]);
}
catch(Exception nfe){
nfe.printStackTrace();
}
// close the file
out.close();
}
}
catch (Exception e) {
Log.i("Data Input Sample", "I/O Error"); //do something if an Exception occurs.
}
}
break;
}
}
}
//editcrap.java:
package com.shuaib669.bunkrecord;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class editcrap extends Activity{
EditText sub[] = new EditText[7]; //list of subject text edit labels.
Button parambutton1; //OK buttons for edit list.
EditText num[] = new EditText[7]; //list of objects of total no. of classes bunked edit text labels. (boinkers i know)
String theText[] = new String[7];
String theNum[] = new String[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.params);
sub[0] = (EditText) findViewById(R.id.peditText1); //pedittext is the parameter menu edit text label
num[0] = (EditText) findViewById(R.id.pnumText1); //EditText label for takin in total no. of classes for 1 subject
sub[1] = (EditText) findViewById(R.id.peditText2);
num[1] = (EditText) findViewById(R.id.pnumText2);
sub[2] = (EditText) findViewById(R.id.peditText3);
num[2] = (EditText) findViewById(R.id.pnumText3);
sub[3] = (EditText) findViewById(R.id.peditText4);
num[3] = (EditText) findViewById(R.id.pnumText4);
sub[4] = (EditText) findViewById(R.id.peditText5);
num[4] = (EditText) findViewById(R.id.pnumText5);
sub[5] = (EditText) findViewById(R.id.peditText6);
num[5] = (EditText) findViewById(R.id.pnumText6);
sub[6] = (EditText) findViewById(R.id.peditText7);
num[6] = (EditText) findViewById(R.id.pnumText7);
parambutton1 = (Button) findViewById(R.id.parambutton1); //pbutton1 is the ok button to accept the input.
parambutton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
for(int x=0;x<7;x++){
theText[x] = sub[x].getText().toString();
theNum[x] = num[x].getText().toString();
//theNum[x] = Integer.parseInt(num[x].getText().toString());
}
Intent data = new Intent(editcrap.this, Sublist.class);
data.putExtra("com.shuaib669.bunkrecord.thetext", theText);
data.putExtra("com.shuaib669.bunkrecord.thenum", theNum);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
}
Using Shared Preferences
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
following code in onCreate() method
EtUserName=(EditText) findViewById(R.id.EditText01);
EtPassword=(EditText) findViewById(R.id.EditText02);
here you get Preferences value in editText...(if you have previous save Preferences)
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
EtUserName.setText(username);
EtPassword.setText(password);
following code in check box click event...(save Preferences here)
String us,pa;
us=EtUserName.getText().toString();
pa=EtPassword.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, us)
.putString(PREF_PASSWORD, pa)
.commit();
for more information click here.and here

self upgrading own apk via net programmatically on android

We have to port our software to android. One of the main feature of our software should be that the software can download a new version of itself from the net (our own server) and install it's new version too. All this thing should be done programmatically.
I'm new to android, so haven't got any clue how should it be done.
How to create apk? - solved
How to sign apk? - solved
How to download apk? - solved
How to copy the downloaded file overwriting /data/apk/my.software.name.apk? - unsolved
How to restart the software by the running version? - unsolved
File file = new File(dir, "App.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
I had the same problem and after several attempts, it worked for me this way. Previously i got my new apk from a webservice.
You do not have to do this. You just upload the new version of your program on the Android Market, and people see it right away. Users who checked the option "update automatically" for your program upgrade automatically without having to give explicit consent ; others see "upgrade available" and can just click 'upgrade' to upgrade to the new version of your program.
If for some reason you're thinking that you want to force the update on the user with or without their consent though, you just cannot do it. You can download the apk and should be able to hand it to the package manager, which in turn will ask the user to confirm whether they actually want to install it - and then again, for that you need the user to have checked the "allow unknown sources" option in development options, else the package manager will downright refuse to do it. But android will not let you install a new package without the user explicitly requesting it, or explicitly allowing auto-updates through the market.
If you have some backward compatibility issue of some sort and want to disallow running of deprecated versions of your application, you can embed in your application some logic that will check on your server for version information and terminate if it's outdated, with a message "this version is outdated, you need to upgrade to continue using this application" or something. But no upgrading in the back of the user.
Sorry for inconvenience this is code and I also posted the XML permissions required to use it.
package com.SelfInstall01;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.SelfInstall01.SelfInstall01Activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SelfInstall01Activity extends Activity
{
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
//private Drawable icon;
/*private void prettyPrint() {
//Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
}*/
}
public int VersionCode;
public String VersionName="";
public String ApkName ;
public String AppName ;
public String BuildVersionPath="";
public String urlpath ;
public String PackageName;
public String InstallAppPackageName;
public String Text="";
TextView tvApkStatus;
Button btnCheckUpdates;
TextView tvInstallVersion;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Text= "Old".toString();
Text= "New".toString();
ApkName = "SelfInstall01.apk";//"Test1.apk";// //"DownLoadOnSDcard_01.apk"; //
AppName = "SelfInstall01";//"Test1"; //
BuildVersionPath = "http://10.0.2.2:82/Version.txt".toString();
PackageName = "package:com.SelfInstall01".toString(); //"package:com.Test1".toString();
urlpath = "http://10.0.2.2:82/"+ Text.toString()+"_Apk/" + ApkName.toString();
tvApkStatus =(TextView)findViewById(R.id.tvApkStatus);
tvApkStatus.setText(Text+" Apk Download.".toString());
tvInstallVersion = (TextView)findViewById(R.id.tvInstallVersion);
String temp = getInstallPackageVersionInfo(AppName.toString());
tvInstallVersion.setText("" +temp.toString());
btnCheckUpdates =(Button)findViewById(R.id.btnCheckUpdates);
btnCheckUpdates.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
GetVersionFromServer(BuildVersionPath);
if(checkInstalledApp(AppName.toString()) == true)
{
Toast.makeText(getApplicationContext(), "Application Found " + AppName.toString(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Application Not Found. "+ AppName.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}// On Create END.
private Boolean checkInstalledApp(String appName){
return getPackages(appName);
}
// Get Information about Only Specific application which is Install on Device.
public String getInstallPackageVersionInfo(String appName)
{
String InstallVersion = "";
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++)
{
//apps.get(i).prettyPrint();
if(apps.get(i).appname.toString().equals(appName.toString()))
{
InstallVersion = "Install Version Code: "+ apps.get(i).versionCode+
" Version Name: "+ apps.get(i).versionName.toString();
break;
}
}
return InstallVersion.toString();
}
private Boolean getPackages(String appName)
{
Boolean isInstalled = false;
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++)
{
//apps.get(i).prettyPrint();
if(apps.get(i).appname.toString().equals(appName.toString()))
{
/*if(apps.get(i).versionName.toString().contains(VersionName.toString()) == true &&
VersionCode == apps.get(i).versionCode)
{
isInstalled = true;
Toast.makeText(getApplicationContext(),
"Code Match", Toast.LENGTH_SHORT).show();
openMyDialog();
}*/
if(VersionCode <= apps.get(i).versionCode)
{
isInstalled = true;
/*Toast.makeText(getApplicationContext(),
"Install Code is Less.!", Toast.LENGTH_SHORT).show();*/
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
//SelfInstall01Activity.this.finish(); Close The App.
DownloadOnSDcard();
InstallApplication();
UnInstallApplication(PackageName.toString());
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("New Apk Available..").setPositiveButton("Yes Proceed", dialogClickListener)
.setNegativeButton("No.", dialogClickListener).show();
}
if(VersionCode > apps.get(i).versionCode)
{
isInstalled = true;
/*Toast.makeText(getApplicationContext(),
"Install Code is better.!", Toast.LENGTH_SHORT).show();*/
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
//SelfInstall01Activity.this.finish(); Close The App.
DownloadOnSDcard();
InstallApplication();
UnInstallApplication(PackageName.toString());
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("NO need to Install.").setPositiveButton("Install Forcely", dialogClickListener)
.setNegativeButton("Cancel.", dialogClickListener).show();
}
}
}
return isInstalled;
}
private ArrayList<PInfo> getInstalledApps(boolean getSysPackages)
{
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++)
{
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
//newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}
public void UnInstallApplication(String packageName)// Specific package Name Uninstall.
{
//Uri packageURI = Uri.parse("package:com.CheckInstallApp");
Uri packageURI = Uri.parse(packageName.toString());
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);
}
public void InstallApplication()
{
Uri packageURI = Uri.parse(PackageName.toString());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);
// Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.setFlags(Intent.ACTION_PACKAGE_REPLACED);
//intent.setAction(Settings. ACTION_APPLICATION_SETTINGS);
intent.setDataAndType
(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + ApkName.toString())),
"application/vnd.android.package-archive");
// Not open this Below Line Because..
////intent.setClass(this, Project02Activity.class); // This Line Call Activity Recursively its dangerous.
startActivity(intent);
}
public void GetVersionFromServer(String BuildVersionPath)
{
//this is the file you want to download from the remote server
//path ="http://10.0.2.2:82/Version.txt";
//this is the name of the local file you will create
// version.txt contain Version Code = 2; \n Version name = 2.1;
URL u;
try {
u = new URL(BuildVersionPath.toString());
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
//Toast.makeText(getApplicationContext(), "HttpURLConnection Complete.!", Toast.LENGTH_SHORT).show();
InputStream in = c.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; //that stops the reading after 1024 chars..
//in.read(buffer); // Read from Buffer.
//baos.write(buffer); // Write Into Buffer.
int len1 = 0;
while ( (len1 = in.read(buffer)) != -1 )
{
baos.write(buffer,0, len1); // Write Into ByteArrayOutputStream Buffer.
}
String temp = "";
String s = baos.toString();// baos.toString(); contain Version Code = 2; \n Version name = 2.1;
for (int i = 0; i < s.length(); i++)
{
i = s.indexOf("=") + 1;
while (s.charAt(i) == ' ') // Skip Spaces
{
i++; // Move to Next.
}
while (s.charAt(i) != ';'&& (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.'))
{
temp = temp.toString().concat(Character.toString(s.charAt(i))) ;
i++;
}
//
s = s.substring(i); // Move to Next to Process.!
temp = temp + " "; // Separate w.r.t Space Version Code and Version Name.
}
String[] fields = temp.split(" ");// Make Array for Version Code and Version Name.
VersionCode = Integer.parseInt(fields[0].toString());// .ToString() Return String Value.
VersionName = fields[1].toString();
baos.close();
}
catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
}
//return true;
}// Method End.
// Download On My Mobile SDCard or Emulator.
public void DownloadOnSDcard()
{
try{
URL url = new URL(urlpath.toString()); // Your given URL.
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect(); // Connection Complete here.!
//Toast.makeText(getApplicationContext(), "HttpURLConnection complete.", Toast.LENGTH_SHORT).show();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH); // PATH = /mnt/sdcard/download/
if (!file.exists()) {
file.mkdirs();
}
File outputFile = new File(file, ApkName.toString());
FileOutputStream fos = new FileOutputStream(outputFile);
// Toast.makeText(getApplicationContext(), "SD Card Path: " + outputFile.toString(), Toast.LENGTH_SHORT).show();
InputStream is = c.getInputStream(); // Get from Server and Catch In Input Stream Object.
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1); // Write In FileOutputStream.
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file.
// So please Check in DDMS tab and Select your Emulator.
//Toast.makeText(getApplicationContext(), "Download Complete on SD Card.!", Toast.LENGTH_SHORT).show();
//download the APK to sdcard then fire the Intent.
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(), "Error! " +
e.toString(), Toast.LENGTH_LONG).show();
}
}
}

Categories

Resources