passing file name to intent - java

I'm new to android and trying to create an app which has a file picker and plays a particular file. I have been able to create the intent to open files; however I'm not able to pass the file path from the file picker to the intent to open that same particular file. Code given below. Appreciate any help. thanks.
EDIT Adding lines I missed___
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
public String root = "/mnt/usbhost0";
public TextView myPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView) findViewById(R.id.path);
getDir(root);
}
public void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
File file;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if (file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
} else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select")
.setMessage("Select " + file.getName() + " to play ?") //Send fileurl from here //
.setPositiveButton("Select", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new DecryptTask().execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
void decrypt() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
File videoFile2Play = new File(//to here);
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "video/m4v");
startActivity(i);
}
public class DecryptTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
decrypt();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
EDIT July 27, 2018
Updated my code as per #miguelarc's suggestion, but still unable to pass the name. Any suggestions or mistakes pointed out?
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
public String root = "/mnt/usbhost0";
public TextView myPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView) findViewById(R.id.path);
getDir(root);
}
public void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
File file;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final File file = new File(path.get(position));
if (file.isDirectory())
{
if (file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
} else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select")
.setMessage("Select " + file.getName() + " to play ?")
.setPositiveButton("Select", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new DecryptTask(file.getAbsolutePath()).execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
void decrypt(String filePath) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
File extStore = Environment.getExternalStorageDirectory();
File videoFile2Play = new File(file.getAbsolutePath());
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "video/*");
startActivity(i);
}
public class DecryptTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
String filePath;
public DecryptTask(String filePath){
this.filePath = filePath;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Loading your video");
pd.show();
}
#Override
protected String doInBackground(String... params) {
try {
decrypt(this.filePath);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
}
}
}

You should pass the filePath to your DecryptTask. Add a constructor to it, and add the filePath, so you can initialize your videoFile2Play with the valid path. At the moment, your file is not initializing anything, that's why the intent is not starting/showing anything.
Add a constructor like so:
public class DecryptTask extends AsyncTask<String, String, String> {
String filePath;
public DecryptTask(String filePath){
this.filePath = filePath;
}
#Override
protected String doInBackground(String... params) {
try {
decrypt(this.filePath); //<--- Add filePath as param of decrypt method
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
then, use the filePath you got inside the decrypt() method.

Related

Volley POST to send multiple JSON

I have a problem with a volley to send multiple JSON with StringRequest, I think the problem is in the hashmap un getParms()
public class MainActivity extends AppCompatActivity {
private static final String TAG = "ENCUESTA";
private static final String VERSION = "2.0.0.3";
private int totalEncuestas=0;
private Encuestador encuestador;
Button btnRutEncuestador;
Button btnEmisivo;
Button btnReceptivo;
Button btnEnvioData;
EditText txtRut;
EditText txtDV;
EditText txtDebug;
TextView lblVersion;
private JSONObject itemEnviar;
private int contador;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
encuestador = new Encuestador();
btnRutEncuestador = (Button) findViewById(R.id.btnRutEncuestador);
btnEmisivo = (Button) findViewById(R.id.btnEmisivo);
btnReceptivo = (Button) findViewById(R.id.btnReceptivo);
btnEnvioData = (Button) findViewById(R.id.btnEnvioData);
txtRut = (EditText) findViewById(R.id.txtRut);
txtDV = (EditText) findViewById(R.id.txtDV);
lblVersion = (TextView) findViewById(R.id.lblVersion);
//DEBUG
//btnReceptivo.setEnabled(true);
//btnEmisivo.setEnabled(true);
lblVersion.setText(Util.getVersion());
//region SIN USO
/*ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
if(!Util.leerArchivo(MainActivity.this, "data.txt").isEmpty()) {
if(Util.verificaConexion(MainActivity.this)) {
Log.d(TAG, "Enviando información");
RequestQueue MyRequestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.inicial.cl/android/set.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.isEmpty() && response.equalsIgnoreCase("success")) {
Log.d(TAG, "success, elimina data local");
Util.vaciarEncuesta(MainActivity.this);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onError: " + error);
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
try {
MyData.put("data", Util.leerArchivo(MainActivity.this, "data.txt"));
} catch (Exception e) {
Log.e(TAG, "Error al enviar: " + e.getMessage());
}
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}else{
Log.d(TAG, "Sin internet");
}
}else{
Log.d(TAG, "Sin data");
}
}
}, 0, 5, TimeUnit.MINUTES);*/
/*txtRut.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
String txt = Util.getTextFromEditText(txtRut);
if(!txt.isEmpty() && txt.equalsIgnoreCase("123123"))
{
txtDebug.setVisibility(View.VISIBLE);
txtDebug.setText(Util.leerArchivo(MainActivity.this, "data.txt"));
}else
{
txtDebug.setVisibility(View.GONE);
txtDebug.setText("");
}
}
});*/
//endregion
//region btnRutEncuestador
btnRutEncuestador.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strRut = txtRut.getText().toString();
String strDV = txtDV.getText().toString();
if (strRut.isEmpty()) {
Toast.makeText(getApplicationContext(), "Debe ingresar rut", Toast.LENGTH_SHORT).show();
return;
}
if (strDV.isEmpty()) {
Toast.makeText(getApplicationContext(), "Debe ingresar DV", Toast.LENGTH_SHORT).show();
return;
}
Boolean existeEncuestador = false;
for (Encuestador e : Encuestador.getAllEncuestadores()) {
Log.d(TAG, "RutIngresado=" + strRut + "-" + strDV + " RutBase:" + e.getRut() + "-" + e.getDv());
if (strRut.equalsIgnoreCase(e.getRut()) && strDV.equalsIgnoreCase(e.getDv())) {
encuestador = new Encuestador();
encuestador.setRut(strRut);
encuestador.setDv(strDV);
btnReceptivo.setEnabled(true);
btnEmisivo.setEnabled(true);
existeEncuestador = true;
break;
} else {
existeEncuestador = false;
}
}
if (!existeEncuestador) {
Util.alertDialog(MainActivity.this, "El Rut ingresado no esta habilitado para realizar encuestas",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
}
});
//endregion
//region btnEmisivo
btnEmisivo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), EmisivoActivity.class);
intent.putExtra("ENCUESTADOR", encuestador);
startActivity(intent);
}
});
//endregion
//region btnReceptivo
btnReceptivo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ReceptivoActivity.class);
intent.putExtra("ENCUESTADOR", encuestador);
startActivity(intent);
}
});
//endregion
//region btnEnvioData
btnEnvioData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnEnvioData.setEnabled(false);
if (!Util.leerArchivo(MainActivity.this, "data.txt").isEmpty()) {
if (Util.verificaConexion(MainActivity.this)) {
Log.d(TAG, "Enviando información");
try {
JSONArray list = new JSONArray(Util.leerArchivo(MainActivity.this, "data.txt"));
totalEncuestas = list.length();
setContador(0);
for (int i = 0; i < list.length(); i++) {
Log.d(TAG, "DATA:"+list.getJSONObject(i));
setItemEnviar(list.getJSONObject(i));
sendRequest();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Sin internet");
Util.alertDialog(MainActivity.this, "Error, no hay conexión a internet",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
}
} else {
Log.d(TAG, "Sin data");
Util.alertDialog(MainActivity.this, "Sin encuestas que enviar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
}
}
});
//endregion
}
public void sendRequest()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.inicial.cl/android/set.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.isEmpty() && response.equalsIgnoreCase("success")) {
setContador(getContador() + 1);
if(getContador() == totalEncuestas) {
Util.alertDialog(MainActivity.this, "Encuestas enviadas exitosamente!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
Util.vaciarEncuesta(MainActivity.this);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onError: " + error);
btnEnvioData.setEnabled(true);
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
try {
MyData.put("data"+Integer.toString(getContador()), getItemEnviar().toString().replaceAll("\n", ""));
Log.e(TAG, "enviados: " + getItemEnviar().toString());
} catch (Exception e) {
Log.e(TAG, "Error al enviar: " + e.getMessage());
btnEnvioData.setEnabled(true);
}
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
MyRequestQueue.getCache().clear();
}
public JSONObject getItemEnviar() {
return itemEnviar;
}
public void setItemEnviar(JSONObject itemEnviar) {
this.itemEnviar = itemEnviar;
}
public int getContador() {
return contador;
}
public void setContador(int contador) {
this.contador = contador;
}
}
The problem is when I get the data to send, in the for the JSON for send are ok, but in the getparms() this only set the last JSON for send, and send many times of the total array

not able to play next song on clicking a button

I am new to android development.I created an audio player app for playing songs from SD card,its working fine and song is being played but when I click next button, song doesn't change and same track keeps playing.Button is clickable but song doesn't change on clicking it.How do I fix it ? any kind of help is appreciated,thanks.
public class PlayListActivity extends Activity {
private String[] mAudioPath;
private MediaPlayer mMediaPlayer;
private String[] mMusicList;
int currentPosition = 0;
private List<String> songs = new ArrayList<>();
MediaMetadataRetriever metaRetriver;
byte[] art;
ImageView album_art;
TextView album;
TextView artist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_list);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv(path);
abc();
cde();
}
public void acv(String path) {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path);
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
album.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
artist.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
album.setText("Unknown Album");
artist.setText("Unknown Artist");
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.coverart1);
album = (TextView) findViewById(R.id.Album);
artist = (TextView) findViewById(R.id.artist_name);
}
public void abc() {
ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
btnPlay1.setBackgroundColor(Color.TRANSPARENT);
btnPlay1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
}
public void cde() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext); //this is the button for playing next song.
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
currentPosition=currentPosition+1;
playSong(path + songs.get(currentPosition));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
Try this code :
public void next() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
btnNext.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
temp = temp + 1;
try {
playSong(mAudioPath[temp]);
} catch (Exception er) {
er.printStackTrace();
}
}
}
);
}
Dont forget to declare next() method in playsong()

why do i get th java.lang.RuntimeException: Unable to start activity ComponentInfo

Hi guys im making a auto update after following a tutorial online then editing the code to suit my needs.. but im getting this error in my logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.Homescreen}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.UpdateService}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
can some one please help me
this is my service class
public class UpdateService extends Service {
public UpdateService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = "<MY Link for version>";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
boolean resp = response.contains("<div class='post-body entry-content' id='post-body-6791062644900393367' itemprop='description articleBody'>\n" +
"1.1.8\n" +
"<div style='clear: both;'></div>");
if (!resp) {
//Dialog to show update
Intent intent1 = new Intent(UpdateService.this, UpdateDialog.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
} else {
Toast.makeText(UpdateService.this, "No New Update Found..", Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(stringRequest);
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
then this is my dialog class
public static Button btn;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Update";
public static File Dir = new File(path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidAuthSession session = buildSession();
dropboxAPI = new DropboxAPI<AndroidAuthSession>(session);
Dir.mkdir();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setTitle("update");
alertDialog.setMessage("New update Available...");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadFromDropboxFromPath(path + "downloadFileFromDropbox", "Update/Myupdate.apk");
}
});
alertDialog.show();
}
static DropboxAPI<AndroidAuthSession> dropboxAPI;
private static final String APP_KEY = "********* **** ** **";
private static final String APP_SECRET = "XXX XX X X XX X";
private static final String ACCESSTOKEN = "xx x x xxx x x x x";
private DropboxAPI.UploadRequest request;
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
session.setOAuth2AccessToken(ACCESSTOKEN);
return session;
}
static final int UploadFromSelectApp = 9501;
static final int UploadFromFilemanager = 9502;
public static String DropboxUploadPathFrom = "";
public static String DropboxUploadName = "";
public static String DropboxDownloadPathFrom = "";
public static String DropboxDownloadPathTo = "";
private void UploadToDropboxFromPath(String uploadPathFrom, String uploadPathTo) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final String uploadPathF = uploadPathFrom;
final String uploadPathT = uploadPathTo;
Thread th = new Thread(new Runnable() {
public void run() {
File tmpFile = null;
try {
tmpFile = new File(uploadPathF);
} catch (Exception e) {
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(tmpFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
dropboxAPI.putFileOverwrite(uploadPathT, fis, tmpFile.length(), null);
} catch (Exception e) {
}
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
private void UploadToDropboxFromSelectedApp(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Upload from ..."), UploadFromSelectApp);
}
private void UploadToDropboxFromFilemanager(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, UploadFromFilemanager);
}
private void DownloadFromDropboxFromPath(String downloadPathTo, String downloadPathFrom) {
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
UpdateDialog.dropboxAPI.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == UploadFromFilemanager) {
final Uri currFileURI = intent.getData();
final String pathFrom = currFileURI.getPath();
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
UploadToDropboxFromPath(pathFrom, "/db-test/" + DropboxUploadName + pathFrom.substring(pathFrom.lastIndexOf('.')));
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
if (requestCode == UploadFromSelectApp) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final Uri uri = intent.getData();
DropboxUploadPathFrom = getPath(getApplicationContext(), uri);
if (DropboxUploadPathFrom == null) {
DropboxUploadPathFrom = uri.getPath();
}
Thread th = new Thread(new Runnable() {
public void run() {
try {
final File file = new File(DropboxUploadPathFrom);
InputStream inputStream = getContentResolver().openInputStream(uri);
dropboxAPI.putFile("/db-test/" + DropboxUploadName + file.getName().substring(file.getName().lastIndexOf("."),
file.getName().length()), inputStream, file.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
return 100;
}
#Override
public void onProgress(long arg0, long arg1) {
}
});
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
super.onActivityResult(requestCode, resultCode, intent);
}
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Audio.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public UpdateDialog getMain() {
return this;
}
}
then finally i call it in my homescreen class. with an intent
Intent intent = new Intent(Homescreen.this, UpdateService.class);
startActivity(intent);
UpdateService is a Service. It is not an Activity. To start a service, you call startService(), not startActivity().
As UpdateService is a service you have to start it by startService() method like #CommonsWare mentioned above. Also don't forget to add your service in Manifest file.
UpdateService is not an activity, It's a class that is extending services.
I think u r a very beginner.
Please go to Udacity and learn the concepts before tingling with android, otherwise, u will waste lot of your time in finding a copy-paste solution.

Android Java progressdialog from Baseadapter

On my android app, I have my own BaseAdapter, in this I have a click button listener with the following code:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
final String id = videoIDs[position];
videoActions = new VideoActions();
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
String downloadResult = videoActions.downloadToShare(token, activity, id, videoPathURL[position], finalVideoName);
if (downloadResult.equalsIgnoreCase("POST_FAILURE") || downloadResult.equalsIgnoreCase("FAILURE_102")) {
Toast.makeText(
activity,
activity.getString(R.string.someErrorOccurred),
Toast.LENGTH_SHORT).show();
}
/*if(hfu.Download_File_To_Share(finalVideoName, videoPathURL[position])){
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
} else {
Toast.makeText(activity, "ERRO", Toast.LENGTH_LONG).show();
}*/
}
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
} catch (Exception e) {
pDialog.dismiss();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
Now here you have the function downloadToShare from the class VideoActions:
public String downloadToShare(String token, Activity activity, String videoID, String videoPath, String videoName) {
this.token = token;
this.activity = activity;
this.videoId = videoID;
this.videoPath = videoPath;
this.videoName = videoName;
DownloadToShareClass downloadAction = new DownloadToShareClass();
try {
return downloadAction.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
} // Close download
And now the downloadToShare class:
class DownloadToShareClass extends AsyncTask<String, String, String> {
String response = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
HttpFileUpload hfu = new HttpFileUpload(videoPath, token);
hfu.Download_File_To_Share(videoName, videoPath);
return "SUCESSFULLY";
}
} // Close DownloadClass
Now the download_file_to_share:
boolean Download_File_To_Share(String fileName, String urlToDownload) {
boolean downloadResult;
try {
downloadResult = DownloadFileToShare(fileName, urlToDownload);
return downloadResult;
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
And for the last the DownloadFileToShare:
// Download video
boolean DownloadFileToShare(String filename, String urlToDownload)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL url = new URL(urlToDownload);
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
System.out.println(count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
return true;
}
My Problem is as you can see on my BaseAdapter code, I'm showing a progress dialog, but it only is shown after all the rest finish (the video download). What is the problem here ? I want that the progressDialog shows when the video is being downloaded...
Thanks in advance
I've found a solution to my own problem. From my BaseAdapter I changed my click listener code to the following and it's working perfectly now:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getResources().getString(R.string.preparingVideoToShare));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
final File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
(new Thread(new Runnable() {
#Override
public void run() {
final String a = hfu.Download_File_To_Share(finalVideoName, videoPathURL[position]);
activity.runOnUiThread(new Runnable() {
public void run() {
if (!a.equalsIgnoreCase("ok")){
pDialog.dismiss();
Toast.makeText(activity,
activity.getResources().getString(R.string.someErrorOccurred),
Toast.LENGTH_LONG).show();
} else {
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
}
});
}
})).start();
} else {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
} catch (Exception e) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
e.printStackTrace();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
I hope it can help someone too.
Can you add code to show progressbar in onPreExecute in class DownloadToShareClass which extends AsyncTask ?
Please refer to http://developer.android.com/reference/android/os/AsyncTask.html
From the above link --
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
class DownloadToShareClass extends AsyncTask<String, String, String> {
private ProgressDialog mdialog;
public DownloadToShareClass(yourActivity activity) {
mdialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
mdialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mdialog.isShowing()) {
mdialog.dismiss();
}
}
}

How can I fix my save function? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have an file list and when a file is clicked its contents are displayed in an EditText. That file is set as currentFile. If the user tries to open a new file before saving the old one they are shown a save dialog. The OK button on the dialog should save the current working file but instead saves it as the file the user is trying to open. Where is the problem in my code that's causing the currentfile to be saved over the new one trying to be opened.
public boolean exists;
public File currentFile;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
et = (EditTextLineNumbers) findViewById(R.id.ide);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
File dir = new File(Environment.getExternalStorageDirectory() + "/My Webs");
currentDirectory = dir;
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
changed = false;
}
#Override
public void afterTextChanged(Editable s) {
changed=true;
}
});
changed=false;
if(dir.isDirectory()) {
browseToRoot();
}else{
dir.mkdir();
}
}
private void openFile(File aFile){
String nullChk = et.getText().toString();
exists = true;
currentFile = aFile;
if(!changed || nullChk.matches("")){
try {
et.setText(new Scanner(aFile).useDelimiter("\\Z").next());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save first?");
alert.setMessage("(Will be saved in the current working directory)");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String temptxt = et.getText().toString();
if(exists){
saveFile(currentFile.getPath(), temptxt);
}else{
saveAs();
}
}
});
final File tempFile = aFile;
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
et.setText(new Scanner(tempFile).useDelimiter("\\Z").next());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
changed=false;
}
});
alert.show();
}
}
private void saveFile(String sFileName, String sBody){
//Toast.makeText(this, exists +"", Toast.LENGTH_SHORT).show();
if (exists) {
try {
File tempfile = new File(sFileName);
FileWriter writer = new FileWriter(tempfile);
writer.write(sBody);
writer.flush();
writer.close();
changed=false;
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
}
}else{
Toast.makeText(this, "Save as", Toast.LENGTH_SHORT).show();
saveAs();
}
}
private void saveAs(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save as");
alert.setMessage("(Will be saved in the current working directory)");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
String tmpText = et.getText().toString();
try {
File tempfile = new File(currentDirectory, value);
FileWriter writer = new FileWriter(tempfile);
writer.write(tmpText);
writer.flush();
writer.close();
changed=false;
//itla.notifyDataSetChanged();
fill(currentDirectory.listFiles());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
/**
* This function browses up one level
* according to the field: currentDirectory
*/
private void upOneLevel(){
if(this.currentDirectory.getParent() != null && !this.currentDirectory.getPath().equals("/sdcard/My Webs")){
this.browseTo(this.currentDirectory.getParentFile());
}else{
//Do nothing
}
}
private void browseTo(final File aDirectory){
// On relative we display the full path in the title.
if(this.displayMode == DISPLAYMODE.RELATIVE)
this.setTitle(aDirectory.getAbsolutePath() + " :: " +
getString(R.string.app_name));
if (aDirectory.isDirectory()){
this.currentDirectory = aDirectory;
fill(aDirectory.listFiles());
}else{
openFile(aDirectory);
}
changed=false;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String selectedFileString = this.directoryEntries.get(position)
.getText();
if (selectedFileString.equals(getString(R.string.current_dir))) {
// Refresh
this.browseTo(this.currentDirectory);
} else if (selectedFileString.equals(getString(R.string.up_one_level))) {
this.upOneLevel();
} else {
File clickedFile = null;
switch (this.displayMode) {
case RELATIVE:
clickedFile = new File(this.currentDirectory
.getAbsolutePath()
+ this.directoryEntries.get(position)
.getText());
break;
case ABSOLUTE:
clickedFile = new File(this.directoryEntries.get(
position).getText());
break;
}
if (clickedFile != null)
currentFile=clickedFile;
this.browseTo(clickedFile);
}
}
}
Third line of openFile(): you change currentFile before you conditionally ask the user if he wants to save currentFile before opening the new file. Change currentFile when you actually open another file, rather than before, and you won't have this problem even accidentally.

Categories

Resources