Im starting to work with Honeycomb, and im trying to make a simple fragmented layout with the list of file on the left side, and the details of the file on the right (when a file is selected). Well, it was going well until I actually tried to list the files, and now I just get a "/" slash, and thats it. Nothing else. I set up a log to track the number of files in the directory im in, and it sees 26, but it wont list them. Heres my code
package com.bv.dual_fragments;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class fragment_one extends ListFragment{
private File currentDirectory = new File("/");
private List<String> directoryEnteries = new ArrayList<String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.fragment_one,container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
//Inflate the layout for this fragment
super.onCreate(savedInstanceState);
//Browse to root directory
browseTo(new File("/"));
}
private void upOneLevel() {
if (this.currentDirectory.getParent() !=null) {
this.browseTo(this.currentDirectory.getParentFile());
}
}
private void browseTo(final File aDirectory) {
//if we want to browse directory
if (aDirectory.isDirectory()){
this.currentDirectory = aDirectory;
Integer fileLength = aDirectory.listFiles().length;
Log.i("File",fileLength.toString() );
File[] files = new File[fileLength];
for (File file : files) {
Log.i("File", file.getAbsolutePath());
}
fill(aDirectory.listFiles());
//set the titlemanger text
TextView titleManager = (TextView)getView().findViewById(R.id.titlemanager);
titleManager.setText(aDirectory.getAbsolutePath());
} else {
//if we want o open file, show this dialog:
//listener when Yes button clicked
OnClickListener okButtonListener = new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//intent to navigate file
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("file://" + aDirectory.getAbsolutePath()));
startActivity(i);
}
};
OnClickListener cancelButtonListener = new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
};
//create dialog
new AlertDialog.Builder(getActivity())
.setTitle("Dialog Title")
.setMessage("File Name " + aDirectory.getName() + "?")
.setPositiveButton("Ok", okButtonListener)
.setNegativeButton("No", cancelButtonListener)
.show();
}
}
private void fill(File[] files) {
//clear the list
this.directoryEnteries.clear();
if (this.currentDirectory.getParent() != null)
this.directoryEnteries.add("..");
//add every file in the list
for (File file : files) {
this.directoryEnteries.add(file.getAbsolutePath());
}
//create array adapter to show everything
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(getActivity(), R.layout.row, directoryEnteries);
this.setListAdapter(directoryList);
}
}
So, it runs, I got my fragments to layout,but it wont list the files. Any help would be appreciated. Oh, when I try to put in a for loop to add each name of the files to my log, it gives a nullpoint exception
Edit: I think I have chased it down to the resource file for the Row that its actually using, which is R.layout.row, but I dont see whats wrong. Heres the layout for that file
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="40sp"
android:padding="5dip"
android:background="#color/white"
android:gravity="center_vertical"/>
Add the follow after the call to
//Browse to root directory
browseTo(new File("/"));
ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setCacheColorHint(Color.TRANSPARENT);
Related
I have a listview in a fragment that is populated with a list of events. I have a heart icon on these list items that allows the user to click and favorite the items. I am currently saving the event id in sharedprefs when the item is Favorited.
This is working properly, and saves the favorited item across user sessions. I now need to populate these favorited items in the favorites listview. The old developer tried a JSON implementation from an api, but it never worked. I now just want to populate this list from the sharedprefs. Heres my favorites fragment code...
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import com.appsflyer.AppsFlyerLib;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import lakeviewlabs.ticketliquidator.api.delete_favorites.DeleteFavoritesApi;
import lakeviewlabs.ticketliquidator.api.delete_favorites.DeleteFavoritesApiOut;
import lakeviewlabs.ticketliquidator.api.get_favorites.GetFavoritesApi;
import lakeviewlabs.ticketliquidator.api.get_favorites.GetFavoritesApiOut;
import static com.urbanairship.UAirship.getApplicationContext;
public class FavoritesFragment extends Fragment implements GetFavoritesApiOut, DeleteFavoritesApiOut {
View rootView;
ProgressDialog pDialog;
FavoritesAdapter adapter;
Boolean checkState = false;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Map<String, Object> eventValue = new HashMap<String, Object>();
AppsFlyerLib.getInstance().trackEvent(getActivity().getApplicationContext(), "View Favorites",eventValue);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " +
entry.getValue());
if (entry.getKey().matches("[0-9]+") && entry.getValue().equals(true)) {
Log.d("using values",entry.getKey() + ": " +
entry.getValue());
// performersList.add(entry.getKey().);
}
}
rootView = inflater.inflate(R.layout.fragment_favorites, container, false);
GetFavoritesApi api = new GetFavoritesApi(getContext(), this);
rootView.findViewById(R.id.delete_favorites).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteFavorites();
}
});
showLoadingMessage();
api.get();
return rootView;
}
private void deleteFavorites() {
ArrayList<String> ids = new ArrayList<String>();
ListView listView = (ListView) rootView.findViewById(R.id.favorites);
DeleteFavoritesApi api = new DeleteFavoritesApi(getContext(), this);
for (int i = 0; i < listView.getCount(); i++){
View view = listView.getChildAt(i);
CheckBox check = (CheckBox)view.findViewById(R.id.favorite_select);
if(check.isChecked()){
ids.add(view.getTag().toString());
}
}
if(ids.isEmpty()){
onDeleteFavoritesSuccess();
return;
}
api.delete(android.text.TextUtils.join(",", ids));
}
private void showLoadingMessage(){
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Getting favorite performers...");
pDialog.show();
}
#Override
public void onGetFavoritesSuccess(JSONArray favorites) {
ListView listView = (ListView) rootView.findViewById(R.id.favorites);
ArrayList<JSONObject> performersList = new ArrayList<JSONObject>();
for(int i = 0; i < favorites.length(); i++) {
JSONObject performer = null;
try {
performer = favorites.getJSONObject(i);
performersList.add(performer);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new FavoritesAdapter(getContext(), performersList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(checkState) {
CheckBox check = (CheckBox)view.findViewById(R.id.favorite_select);
check.setChecked(!check.isChecked());
}else{
Intent intent = new Intent(getContext(), PerformerActivity.class);
intent.putExtra("performer_id", view.getTag().toString());
startActivity(intent);
}
}
});
pDialog.dismiss();
}
#Override
public void onGetFavoritesError(JSONObject errors) {
}
#Override
public void onGetFavoritesUnexpectedError() {
}
public void showCheckboxes() {
checkState = !checkState;
rootView.findViewById(R.id.delete_favorites).setVisibility(checkState ? View.VISIBLE : View.INVISIBLE);
ListView listView = (ListView) rootView.findViewById(R.id.favorites);
for (int i = 0; i < listView.getCount(); i++){
View view = listView.getChildAt(i);
CheckBox check = (CheckBox)view.findViewById(R.id.favorite_select);
check.setVisibility(checkState ? View.VISIBLE : View.GONE);
check.setChecked(false);
// view.animate()
// .translationX(150)
// .setDuration(300)
// .setListener(new AnimatorListenerAdapter() {
// #Override
// public void onAnimationEnd(Animator animation) {
//
// }
// });
}
//
}
#Override
public void onDeleteFavoritesSuccess() {
GetFavoritesApi api = new GetFavoritesApi(getContext(), this);
showLoadingMessage();
showCheckboxes();
api.get();
}
}
I've tried parsing all the sharedprefs and Im able to log the ones that are needed. I just cant get them to display in the favorites list.
You can store the object of the item as JSON string in the Shared Preferences and whenever new item is added to favorites append the JSON object for that item to the JSON string and in the Favorites list read and parse the json string from Shared Preferences. I'm assuming you get the results in JSON array from the API. I would suggest store the JSON string in the same format as received so that you can reuse the same POJOs for favorites list.
Hope this helps.
You should not store your preferences like that. Storing your event using their ids as a key creates a big mess in your Shared Preferences.
Instead:
Store a list of event id. As you can't store a list in the Shared Preferences, use Gson to convert your list into a Json string. Then store the string. Use Gson again to regenerate the list from the stored string.
The other (better) option, is to use a local database. It's gonna be easier, and cleaner. You will be able to store more information easily. Like that you can store the entire event (and not the id only) and request them back to populate your ListView of favourite events
Note: You could store the entire events in the Shared Preferences as suggested by #Varun_Ramani but it's not recommended as the purpose of the Shared Preferences is not to replace databases (as explained in the official documentation, see below).
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
I'm writing a DialogFragment for browsing the filesystem, which works really nice by now. I just got one Problem.
The files are shown in an ListView, and when the user selects a file, this event is send to the Activity that has called the Fragment over an OnFileSelectedListener-Interface. This is fine for files, but it feels wrong to send out the directory names to the activity, then destroying and recreating the Fragment, when all that should happen is that the Fragment should show a new Directory. It also makes the whole Fragement disapearing and then reapearing which isn't really nice and smooth.
Furthermore every Activity using the Fragment has to use the logic for recreating the Fragment, which is far from "don't repeat yourself".
So, in short, is there a way to do a changeout of the Listview within the Fragment? Calling the AlertDialog.Builder more than once sadly doesn't work.
Heres my DialogFragment. I hope it's ok to post the whole thing:
package de.fusionsystems.firmenlaufmonitor;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FileChooserFragment extends DialogFragment {
private OnFileSelectedListener mCallback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return createDialog();
}
private AlertDialog createDialog(){
// Create the AlertDialog object and return it
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
ArrayList<File> files = getFilesInDir(options.getString("BaseDir", ""));
ArrayList<ListEntry> fileEntries = new ArrayList<ListEntry>();
if (!isBaseDir(options.getString("BaseDir", ""))){
fileEntries.add(new ListEntry("..", getResources().getDrawable( R.drawable.ic_folder)));
}
for (File file : files){
if (file.isDirectory()){
fileEntries.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_folder)));
}else{
if (file.getName().endsWith(".kml")){
fileEntries.add(new ListEntry(file.getName(),getResources().getDrawable( R.drawable.ic_file)));
}
}
}
final FileAdapter adapter = new FileAdapter(getActivity(), fileEntries);
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String path;
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (adapter.getItem(which).name.equals("..")){
//navigate back
path = options.getString("BaseDir", "/");
path=path.substring(0, path.length());
path=path.substring(0,path.lastIndexOf("/"));
path = !path.equals("")?path:("/");
}else {
path = options.getString("BaseDir", "");
path += ((path.equals("/"))?(""):("/"))+adapter.getItem(which).name;
}
Log.d("Path", path);
Editor editor = options.edit();
File dirTest = new File(path);
if (dirTest.isDirectory()){
editor.putString("BaseDir", path);
editor.commit();
//mCallback.onFileSelected("");
//createDialog();
//*******************DO THE RIGHT THING HERE***********************
}else{
mCallback.onFileSelected(path);
}
}
};
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setAdapter(adapter, clickListener)
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
builder.setTitle("Datei wählen");
return builder.create();
}
private ArrayList<File> getFilesInDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.e("FileBrowser","Something's really fishy");
}
}
ArrayList<File> fileList = new ArrayList<File>(Arrays.asList(folder.listFiles()));
return fileList;
}
private boolean isBaseDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.e("FileBrowser","Something's really fishy");
}
}
File baseDir = new File("/");
if (folder.equals(baseDir)){
return true;
}else{
return false;
}
}
// Container Activity must implement this interface
public interface OnFileSelectedListener {
public void onFileSelected(String file);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFileSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
class ListEntry {
public String name;
public Drawable item ;
public ListEntry(String name, Drawable item) {
this.name = name;
this.item = item;
}
}
class FileAdapter extends ArrayAdapter<ListEntry>{
public FileAdapter(Context context, ArrayList<ListEntry> fileEntry) {
super(context, R.layout.filechooser_list_item,fileEntry);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ListEntry entry = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.filechooser_list_item, parent, false);
}
// Lookup view for data population
TextView filechooserEntry = (TextView) convertView.findViewById(R.id.filechooser_entry);
// Populate the data into the template view using the data object
filechooserEntry.setText(entry.name);
filechooserEntry.setCompoundDrawablesWithIntrinsicBounds(entry.item, null, null, null);
// Return the completed view to render on screen
return convertView;
}
}
}
Here's my solution for a Filebrowser as a DialogFragment. It turns out there are methods to add() remove() and clean() items to the adapter, so the answer to the initial question was real simple. The tricky part was to prevent the Dialog from closing after selecting a List item. This answer helped a lot: https://stackoverflow.com/a/15619098/3960095. Here's my working code for future visitors:
package de.yourCompany.yourProject;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FileChooserFragment extends DialogFragment{
private OnFileSelectedListener mCallback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Create the AlertDialog object and return it
final FileAdapter adapter = new FileAdapter(getActivity(), new ArrayList<ListEntry>());
adapter.getFiles();
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do nothing here to prevent dismiss after click
}
};
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setAdapter(adapter, clickListener)
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setTitle("Datei wählen");
final AlertDialog theDialog = builder.show();
theDialog.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String path;
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (adapter.getItem(position).name.equals("..")){
//navigate back
path = options.getString("BaseDir", "/");
path=path.substring(0, path.length());
path=path.substring(0,path.lastIndexOf("/"));
path = !path.equals("")?path:("/");
}else {
//get the Slashes right and navigate forward
path = options.getString("BaseDir", "");
path += ((path.equals("/"))?(""):("/"))+adapter.getItem(position).name;
}
Editor editor = options.edit();
File dirTest = new File(path);
if (dirTest.isDirectory()){
editor.putString("BaseDir", path);
editor.commit();
adapter.clear();
adapter.getFiles();
}else{
mCallback.onFileSelected(path);
theDialog.dismiss();
}
}
});
return theDialog;
}
private boolean isBaseDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.wtf("FileBrowser","Something's really fishy");
}
}
File baseDir = new File("/");
if (folder.equals(baseDir)){
return true;
}else{
return false;
}
}
// Container Activity must implement this interface
public interface OnFileSelectedListener {
public void onFileSelected(String file);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFileSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
class ListEntry {
public String name;
public Drawable item ;
public ListEntry(String name, Drawable item) {
this.name = name;
this.item = item;
}
}
class FileAdapter extends ArrayAdapter<ListEntry>{
//show only files with the suffix FILE_SUFFIX, use "*" to show all files;
private static final String FILE_SUFFIX = ".kml";
public FileAdapter(Context context, ArrayList<ListEntry> fileEntry) {
super(context, R.layout.filechooser_list_item,fileEntry);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ListEntry entry = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.filechooser_list_item, parent, false);
}
// Lookup view for data population
TextView filechooserEntry = (TextView) convertView.findViewById(R.id.filechooser_entry);
// Populate the data into the template view using the data object
filechooserEntry.setText(entry.name);
filechooserEntry.setCompoundDrawablesWithIntrinsicBounds(entry.item, null, null, null);
// Return the completed view to render on screen
return convertView;
}
private FileAdapter getFiles() {
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
ArrayList<File> files = getFilesInDir(options.getString("BaseDir", ""));
if (!isBaseDir(options.getString("BaseDir", ""))){
this.add(new ListEntry("..", getResources().getDrawable( R.drawable.ic_folder)));
}
for (File file : files){
if (file.isDirectory()){
this.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_folder)));
}else{
if (file.getName().endsWith(FILE_SUFFIX)||FILE_SUFFIX.equals("*")){
this.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_file)));
}
}
}
return this;
}
private ArrayList<File> getFilesInDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.wtf("FileBrowser","Something's really fishy");
}
}
ArrayList<File> fileList;
if (folder.listFiles()!=null){
fileList = new ArrayList<File>(Arrays.asList(folder.listFiles()));
}else{
fileList = new ArrayList<File>();
}
return fileList;
}
}
}
and in your Activity:
public class YourActivity extends Activity implements FileChooserFragment.OnFileSelectedListener{
#Override
public void onFileSelected(String file) {
//Do whatever you want to do with the files
}
// And whereever you want to start the Fragment:
FileChooserFragment fileFragment = new FileChooserFragment();
fileFragment.show(getFragmentManager(), "fileChooser");
This is my first app and my first time posting so bear with me.
I'm trying to make it so the user can choose the background color of the entire app from a Change Skins screen. However with what I have now it only changes the color of the activity until it goes back to the main activity.
Here is the code for the Change Skins screen
package cs.pacificu.mypace;
import android.R.layout;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Skin extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
final String[] SKINS = new String[] {"Light", "Dark"};
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
final ListView listView = (ListView) findViewById (R.id.playlists);
listView.setAdapter(new ArrayAdapter<String> (this,R.layout.single_list_item,SKINS));
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
//
View layout = findViewById(R.layout.activity_main);
String selectedFromList = (listView.getItemAtPosition(position).toString ());
if (SKINS [0] == selectedFromList)
{
listView.setBackgroundColor(Color.CYAN);
//layout.setBackgroundColor(android.R.color.darker_gray);
}
else if (SKINS[1] == selectedFromList)
{
listView.setBackgroundColor(Color.BLACK);
//layout.setBackgroundColor(android.R.color.black);
}
//
finish();
}
});
}
}
And here is the main activity code
package cs.pacificu.mypace;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
/*import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater;*/
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
startPlaylists(null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item)
{
switch (item.getItemId()) {
case R.id.skin:
changeSkin();
return true;
case R.id.action_settings:
settingsList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void startPlaylists (View view)
{
Intent intentPlaylists = new Intent();
intentPlaylists.setClassName("cs.pacificu.mypace", "cs.pacificu.mypace.Playlist");
intentPlaylists.setAction("#strings/action_playlists");
startActivity(intentPlaylists);
}
public void changeSkin ()
{
Intent intentSkin = new Intent();
intentSkin.setClassName("cs.pacificu.mypace", "cs.pacificu.mypace.Skin");
intentSkin.setAction("#strings/action_skin");
startActivity(intentSkin);
}
public void settingsList ()
{
Intent intentSettings = new Intent();
intentSettings.setClassName("cs.pacificu.mypace", "cs.pacificu.mypace.Settings");
intentSettings.setAction("#strings/action_settings");
startActivity(intentSettings);
}
}
Thank you!
Put this on your xml
android:background="#025cd8"
Depending on your choice of color.
what you can do is set a SharedPreferences value to what the user selects, and at the start of each of your activities, set that value to the background colour of your layout. That is the best way I see to solving this.
So in all of your activities, you would set them to the value from the SharedPreferences and if not set use your default one. As for storing the possible values, you can either use the XML file or just hard code the values in one global class, although the former is preferable.
Look here and see what they did (Android-page-about-data-storage)
Edit:
If you are going to keep it simple like that, just background colour, then you can do something like this:
|- Keep these somewhat global, maybe in a class and access them as needed,
// Make sure to maintain the connection
String[] SKINS = {"Light", "Dark"};
int[] COLOURS = {Color.CYAN, Color.BLACK};
|- For the onItemClick(),
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// You may wish to make these two variables class-global
SharedPreferences settings = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("mskin", COLOURS[position]);
editor.commit();
// For on the spot changes
listView.setBackgroundColor(COLOURS[position]);
// Your other code, as you wish, before or after, depends on how you need it.
|- As for your other activities, or at the onCreate() of all activities,
SharedPreferences settings = getPreferences(MODE_PRIVATE);
listView.setBackgroundColor(settings.getInt("mskin", COLOURS[0]));
I've created a file manager that I will use in my other program, however I am having problems with it. It displays a list of files on my android phone, and I can click through one folder deep, however going more than one it stops working. Mainly I think because of "if(K.getAbsoluteFile().isDirectory()==true)", if I get rid of this line though it simply crashes. So it seems to only allow me to go one folder deep, can anyone figure out what I've done wrong here?
Also any guides or what have you on this topic would be appreciated, its kind of a mangling of random code I've found.
package book.BouncySquare;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FileManager extends ListActivity {
public File clickedFile = null;
private List<String> directoryEntries = new ArrayList<String>();
//private List<String> directoryEntries = new ArrayList<String>();
private File currentDirectory = new File("/");
#Override
public void onCreate(Bundle icicle) {
Log.d("startx", "start");
super.onCreate(icicle);
browseToRoot();
}
public void browseToRoot() {
Log.d("Browse", "browse"+currentDirectory.getAbsoluteFile());
browseTo(new File("/"));
}
private void browseTo(File file) {
Log.d("mew", "too");
if(file.isDirectory()){
Log.d("check", "it");
fill(file); }
}
private void browse(String x) {
Log.d("created", "newfile");
final File K=new File(x);
Log.d("broke", "ass");
if(K.getAbsoluteFile().isDirectory()==true){
Log.d("Z"+K.getAbsoluteFile(), "directory");
fill(K.getAbsoluteFile());}
else{
Log.d("X"+K.getName(), "NotADirectoryOrHidden");
Log.d("A"+K.getAbsoluteFile(), "directory");
}
}
private void fill(File files) {
File[] meow=null;
this.directoryEntries.clear();
meow= files.listFiles();
Log.d("sss", "sss");
this.directoryEntries.add(getString(R.string.current_dir));// directoryentries is an arraylist that holds our Directories names
this.directoryEntries.add(getString(R.string.up_one_level));
for (File file : meow) {
this.directoryEntries.add(file.getName()); //fill our string array directoryentries with each files getName, then we pass it to arrayAdapter to populate
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,R.layout.file_row, this.directoryEntries); //our context,layout, and array of directories is created
this.setListAdapter(directoryList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String clickedEntry =this.directoryEntries.get((int) id);
Log.d("clickedID="+id, "clickedPosition="+clickedEntry);
browse(clickedEntry);
}
}
Try prepending your current directory to what you are wanting to list.
private void browse(String x) {
Log.d("created", "newfile");
final File K=new File(currentDirectory, x);
Log.d("broke", "ass");
if(K.getAbsoluteFile().isDirectory()==true){
Log.d("Z"+K.getAbsoluteFile(), "directory");
currentDirectory = K.getAbsoluteFile();
fill(K.getAbsoluteFile());}
else{
Log.d("X"+K.getName(), "NotADirectoryOrHidden");
Log.d("A"+K.getAbsoluteFile(), "directory");
}
}
I am creating an intent to play videos stored in the sdcard. It happens that I play the first one, everything is OK. But when I play another one, it just plays everytime the first one I played. Here is my code:
package com.remote;
import java.io.File;
import java.io.IOException;
import com.remote.R.drawable;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.VideoView;
public class MyVideos extends Activity{
private String path="/sdcard/Movies/Telmex";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myvideos);
createLinks(new File(path));
}
public void createLinks(File path)
{
LinearLayout layout = (LinearLayout) findViewById(R.id.myvideoslayout);
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++)
{
if(files[i].getName().toString().charAt(0)!='.')
{
String videoName;
Button video=new Button(this);
video.setBackgroundColor(2);
video.setTextSize(23);
video.setCompoundDrawablesWithIntrinsicBounds(0,0,drawable.videoicon,0);
videoName=new String(files[i].getName());
video.setText(videoName);
createListener(video,videoName);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
layout.addView(video,p);
}
}
}
}
public void createListener(Button video, final String name)
{
video.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
videoPlayer(path,name,true);
}
});
}
public void videoPlayer(String path, String fileName, boolean autoplay)
{
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse(path+"/"+fileName);
intent.setDataAndType(data, "video/mp4");
startActivity(intent);
}
}
Rewrite
I did some digging and wrote the code below, if this has the same problem then it is your external video player not you app.
public class ExampleActivity extends Activity {
// Change this path
private final String path = Environment.getExternalStorageDirectory() + "/android/data/com.example/files/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File dir = new File(path);
List<String> files = new ArrayList<String>();
Collections.addAll(files, dir.list());
Collections.sort(files);
while(files.get(0).startsWith("."))
files.remove(0);
ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String uri = path + ((TextView) view).getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(uri), "video/*");
startActivity(intent);
}
});
}
}
Addition
I'm glad the internal video player works. The reason why it resets is that every time you change orientation the OS destroys and rebuilds your app from scratch... It's the same as if you exited the app by pressing the back button and ran it again. If you are using the tutorial from below, you need to save the video's location in onDestroy() to a class variable and in your onCreate() check to see if that variable has a valid location or just start at the beginning of the video.