Choose where to save a file in android [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have an object("jsonized" to a string) and I want to save it in a file.
Also, I want that a dialogbox shows up allowing the user to pick up the folder where the file will be saved.
(I was writing this question when, suddenly, the solution hit me. Just sharing my solution to get feedback of better ways to do this)

When the "Save File" button is clicked, it launches "selectFolder()" function
Activity.java
public void selectFolder(){
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Chain together various setter methods to set the dialog characteristics
builder.setTitle("Choose folder to save profile");
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_selectfolder, null);
ListView lvDirectories = (ListView) dialogView.findViewById(R.id.lvDirectories);
String path = Environment.getExternalStorageDirectory().toString();
((TextView) dialogView.findViewById(R.id.tvJamesBond)).setText(path);
final ArrayList<String> items = listFolders(path);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
lvDirectories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String dest = ((ListView) dialogView.findViewById(R.id.lvDirectories)).getItemAtPosition(i).toString().trim();
String path;
if(dest.compareTo("...")==0){
int lastSlash = ((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString().lastIndexOf("/");
path = ((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString().substring(0,lastSlash);
}
else{
path = ((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString() + "/" + dest;
}
items.clear();
items.addAll(listFolders(path));
((TextView) dialogView.findViewById(R.id.tvJamesBond)).setText(path);
adapter.notifyDataSetChanged();
}
});
lvDirectories.setAdapter(adapter);
adapter.notifyDataSetChanged();
builder.setView(dialogView);
// Add the buttons
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
saveProfile(((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString());
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast toast = Toast.makeText(getApplicationContext(), "Nothing saved", Toast.LENGTH_SHORT);
toast.show();
}
});
// Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
public ArrayList<String> listFolders(String path){
ArrayList<String> result = new ArrayList<String>();
File f = new File(path);
File[] files = f.listFiles();
Log.d("TEST PATH1", path);
Log.d("TEST PATH1", Environment.getExternalStorageDirectory().toString());
if(path.compareTo(Environment.getExternalStorageDirectory().toString())!=0){
result.add("...");
}
for (File inFile : files) {
if (inFile.isDirectory()) {
result.add(inFile.getName());
}
}
return result;
}
public void saveProfile(String folder){
String fileName = "default.txt";
try{
String ob = new Gson().toJson(((MyApplication)getApplication()).getProfile());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(folder+"/"+fileName));
outputStreamWriter.write(ob);
outputStreamWriter.close();
}
catch(IOException ex){
Log.e("SAVE_FILE", ex.toString());
}
Toast toast = Toast.makeText(getApplicationContext(), "Profile saved to file '"+fileName+"'", Toast.LENGTH_SHORT);
toast.show();
}
dialog_selectfolder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvDirectories"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"
android:text="New Text"
android:id="#+id/tvJamesBond"
android:layout_gravity="center_horizontal" />
</LinearLayout>

Related

Converting JSON Array into Java Objects and attaching to ListView

I'm relatively new to Android development and I've been stuck on this for a couple of weeks.
I'm working with a JSON Array and I've been able to log that I am returning the JSON Array with an API call and that it is breaking up the array into separate JSON Objects.
Hero JSON {"PrimaryName":"Abathur","ImageURL":"Abathur","AttributeName":"Abat","Group":"Specialist","SubGroup":"Utility","Translations":"Abatur,АБАТУР,아바투르,阿巴瑟"}
Hero JSON {"PrimaryName":"Alarak","ImageURL":"Alarak","AttributeName":"Alar","Group":"Assassin","SubGroup":"Ambusher","Translations":"亞拉瑞克,阿拉纳克,알라라크,Аларак"}
etc...
From what it appears it is converting those JSON Objects into Java Objects.
hotsbuddy.HeroDataModel#f27ef8a
hotsbuddy.HeroDataModel#db939fb
etc...
When I changed the Log to return the Hero Name, Hero Image and Hero Group from my
public static HeroDataModel fromJson(JSONObject jsonObject)
method I get this:
03-24 18:44:53.828 30539-30539/com.timfreebernii.hotsbuddy D/HoTS: Hero Abathur Abathur Specialist
03-24 18:44:53.828 30539-30539/com.timfreebernii.hotsbuddy D/HoTS: Hero Alarak Alarak Assassin
03-24 18:44:53.828 30539-30539/com.timfreebernii.hotsbuddy D/HoTS: Hero Alexstrasza Alexstrasza Support
So I can see that I am getting Java Objects back.
These logs are being placed in my HeroDataModel class. However, I'm having an issue attaching these Java Objects to my ListView and ListView Adapter.
When I log my ArrayList creation in my API call I am getting Java Objects returned.
Array [com.timfreebernii.hotsbuddy.HeroDataModel#f27ef8a,
com.timfreebernii.hotsbuddy.HeroDataModel#db939fb, etc...]
These objects are not showing up in App View. I'm not getting a list just a blank white background with the blue bar with my app name from the Main Layout.
I've been using these guides from CodePath but I'm just not quite able to finish off this feature.
https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView#row-view-recycling
https://guides.codepath.com/android/Converting-JSON-to-Models#bonus-setting-up-your-adapter
I know I'm using a different type of Adapter but I was kind of following along from a couple simple apps I built from a Udemy course I completed.
Here is the API I'm working with:
https://api.hotslogs.com/Public/Data/Heroes
My GitHub repo:
https://github.com/tfreebern2/hotsbuddy
Here is my HeroDataModel code:
public class HeroDataModel {
private String mHeroName;
private String mHeroImage;
private String mHeroGroup;
public String getHeroName() {
return this.mHeroName;
}
public String getHeroImage() {
return this.mHeroImage;
}
public String getHeroGroup() {
return this.mHeroGroup;
}
public static HeroDataModel fromJson(JSONObject jsonObject) {
HeroDataModel h = new HeroDataModel();
try {
h.mHeroName = jsonObject.getString("PrimaryName");
h.mHeroImage = jsonObject.getString("ImageURL");
h.mHeroGroup = jsonObject.getString("Group");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return h;
}
public static ArrayList<HeroDataModel> fromJson(JSONArray jsonObjects) {
JSONObject heroJson;
ArrayList<HeroDataModel> heroes = new ArrayList<HeroDataModel> . ();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
heroJson = jsonObjects.getJSONObject(i);
// Log.d("HotS", "Hero JSON " + heroJson);
} catch (JSONException e) {
e.printStackTrace();
continue;
}
HeroDataModel hero = HeroDataModel.fromJson(heroJson);
// Log.d("HoTS", "Hero " + hero);
if (hero != null) {
heroes.add(hero);
}
}
// Log.d("HoTS", "Heroes Array" + heroes);
return heroes;
}
}
My HeroListAdapter:
public class HeroListAdapter extends ArrayAdapter<HeroDataModel> {
public HeroListAdapter(HeroListActivity context, ArrayList<HeroDataModel> heroes) {
super(context, 0, heroes);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HeroDataModel currentHero = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.hero_list_item, parent, false);
}
TextView heroNameView = convertView.findViewById(R.id.hero_name);
TextView heroImageView = convertView.findViewById(R.id.hero_image);
TextView heroGroupView = convertView.findViewById(R.id.hero_group);
heroNameView.setText(currentHero.getHeroName());
heroImageView.setText(currentHero.getHeroImage());
heroGroupView.setText(currentHero.getHeroGroup());
return convertView;
}
}
My HeroListActivity:
public class HeroListActivity extends AppCompatActivity {
final String HEROES_URL = "https://api.hotslogs.com/Public/Data/Heroes";
ArrayList<HeroDataModel> heroes;
HeroListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hero_list);
heroListAPI(HEROES_URL);
ListView listView = (ListView) findViewById(R.id.lvHeroes);
heroes = new ArrayList<HeroDataModel>();
adapter = new HeroListAdapter(this, heroes);
listView.setAdapter(adapter);
}
private void heroListAPI(String url) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
ArrayList<HeroDataModel> heroes = HeroDataModel.fromJson(response);
heroes.clear(); // clear existing items if needed
heroes.addAll(HeroDataModel.fromJson(response)); // add new items
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable e, JSONArray response) {
Log.e("HoTS", "Fail " + e.toString());
Log.d("HoTS", "Status code " + statusCode);
Toast.makeText(HeroListActivity.this, "Request Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
My Hero_List Layout File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rlLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lvHeroes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
My Hero_List_Item Layout File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.timfreebernii.hotsbuddy.HeroActivity">
<TextView
android:id="#+id/hero_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hero Name"
/>
<TextView
android:id="#+id/hero_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hero Image"
/>
<TextView
android:id="#+id/hero_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hero Group"
/>
</LinearLayout>
Use Gson Library or retrofit to convert json objects into model class
Well I found a solution with some help.
My HeroListActivity is where I was making the API call and trying to convert the Json into Java Objects.
Here I declared my adapter in the HeroListActivity class outside of my onCreate method and removed the declaration of the ArrayList. I created a new HeroListAdapter using 'this' and 'new' ArrayList() as parameters. Then I attached the adapter to my ListView.
public class HeroListActivity extends AppCompatActivity {
final String HEROES_URL = "https://api.hotslogs.com/Public/Data/Heroes";
HeroListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hero_list);
heroListAPI(HEROES_URL);
ListView listView = (ListView) findViewById(R.id.lvHeroes);
adapter = new HeroListAdapter(this, new ArrayList<HeroDataModel>());
listView.setAdapter(adapter);
}
... more code
}
In my onSuccess method I created an ArrayList named 'myHeroes' with my renamed fromJsonToModelList.
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
ArrayList<HeroDataModel> myHeroes = HeroDataModel.fromJsonToModelList(response);
adapter.clear();
adapter.addAll(myHeroes);
adapter.notifyDataSetChanged();
}
I clear the adapter of any previous data, add all objects to the adapter and notify the adapter of any changes.
Some of the changes were just refactoring suggestions.
Ultimately, I wasn't passing the data to my adapter correctly nor do I think creating it correctly in my onCreate method.

Displaying a list of folders in one directory as items using Base Adapter

I have an issue here. I got an app that adds folder in the app's directory itself using mkdir in a secondary activity.
fun createFolder (v: View){
//Make folder
val folderName = addFolderField.text.toString()
val dir1 = this.getDir("picture", Context.MODE_PRIVATE) //this is to make directory as well
File(dir1, folderName).mkdir()
finish()
Assuming that I have multiple folders created. How then do I display a the list of folders using Base Adapter in my Main Activity
Create a activity_list_files.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView android:id="#android:id/list" android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And a ListFileActivity
public class ListFileActivity extends ListActivity {
private String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_files);
// Use the current directory as title
path = "/";
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
setTitle(path);
// Read all files sorted into the values-array
List values = new ArrayList();
File dir = new File(path);
if (!dir.canRead()) {
setTitle(getTitle() + " (inaccessible)");
}
String[] list = dir.list();
if (list != null) {
for (String file : list) {
if (!file.startsWith(".")) {
values.add(file);
}
}
}
Collections.sort(values);
// Put the data into the list
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_2, android.R.id.text1, values);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String filename = (String) getListAdapter().getItem(position);
if (path.endsWith(File.separator)) {
filename = path + filename;
} else {
filename = path + File.separator + filename;
}
if (new File(filename).isDirectory()) {
Intent intent = new Intent(this, ListFileActivity.class);
intent.putExtra("path", filename);
startActivity(intent);
} else {
Toast.makeText(this, filename + " is not a directory", Toast.LENGTH_LONG).show();
}
}
}
Where path is the complete directory path where you are creating your folders. The activity displays all files within this path. If we switch the path, we switch to a new activity displaying all files within the given directory.
Also make sure you are adding uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" in your manifest.

Listening For Touch In Padding Area Between Elements of An AlertDialog

I have onTouchListeners for the (custom) title area and for the message area of my AlertDialog.
I'm trying to have my dialog set up in such a way that the user can mindlessly tap in the top right 1/4th of the AlertDialog to toggle the whether background music plays or not since just having the speaker as the tappable area would result in too small of a hit box/area.
My problem is: the area in between the message and title marked in red isn't handling ontouchlistener events
Most people would suggest creating a custom dialog, but the thing is I really like the way this dialog looks (it has a very stock material design aesthetic) and already jumped through a lot of hoops to get it to look exactly the way I like (drawing leaderboard over an invisible neutral button, custom title area). I don't want to make a custom dialog unless I can make it look absolutely identical to what I have now (so hard to mimic the look of stock material dialogs, trust me i've tried and did a lot of research/wasted a lot of time trying that).
I'm assuming the on touch events for the custom title area and message area don't encompass or account for the margins or padding in between.
Pardon the disgusting code!! I'm just trying to hack everything together and tidy it up later.
Thanks in advance!
The linear layout for my custom title area of the alertdialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0px"
android:paddingTop="0px"
android:paddingLeft="0px"
android:paddingRight="0px"
android:paddingBottom="0px"
android:orientation="horizontal"
android:id="#+id/st"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="24dp"
android:paddingTop="20dp"
android:paddingRight="5dp"
android:src="#drawable/ic_pause"/>
<TextView
android:id="#+id/leaderboard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#800080"
android:textSize="22sp"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.DialogWindowTitle"
android:layout_gravity="center"
android:paddingTop="18dp"
android:layout_weight="1"
android:text="Paused"
/>
<ImageView
android:id="#+id/soundtoggle"
style="?android:attr/panelTextAppearance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="24dp"
android:paddingTop="20dp"
android:paddingRight="?android:dialogPreferredPadding"
android:gravity="right"/>
</LinearLayout>
My android code
AlertDialog.Builder ad = new AlertDialog.Builder(new ContextThemeWrapper(AndroidLauncher.this, android.R.style.Theme_Material_Light_Dialog))
.setMessage(msg)
.setCustomTitle(myLayout)
.setCancelable(false)
.setNegativeButton("End Game", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pauseInterface.end();
dialog.cancel();
}
})
.setNeutralButton(" ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//startSignInIntent();
showLeaderboard();
dialog.cancel();
}
})
.setPositiveButton("Resume", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pauseInterface.resume();
dialog.cancel();
}
});
alertDialog = ad.create();
int titleId = getResources().getIdentifier("alertTitle", "id", "android");
if (titleId > 0) {
TextView dialogTitle = (TextView) alertDialog.findViewById(titleId);
}
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
Drawable drawable = getResources().getDrawable(R.drawable.ic_leaderboard);
drawable.setBounds((int) 0,
0, (int) (drawable.getIntrinsicWidth() * 1),
drawable.getIntrinsicHeight());
button.setCompoundDrawables(drawable, null, null, null);
}
});
alertDialog.show();
final ImageView soundToggle = (ImageView) alertDialog.findViewById(R.id.soundtoggle);
if (tetrisgame.getMusicState()) {
if (tetrisgame.getMusicState()) {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_on, getApplicationContext().getTheme()));
} else {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, getApplicationContext().getTheme()));
}
TextView tv = (TextView) alertDialog.findViewById(android.R.id.message);
tv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent m) {
if (m.getAction() == MotionEvent.ACTION_DOWN && (m.getX() >= (v.getRight() - (v.getWidth() / 4)))) {
Log.println(Log.ERROR, "Ken", "Popular Pothead");
if (tetrisgame.toggleMusic()) {
String uri = "#drawable/music_on"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
soundToggle.setImageDrawable(res);
// soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, alertDialog.findViewById(android.R.id.message).getTheme()));
} else {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, null));
}
}
return true;
}
});
final LinearLayout as = (LinearLayout) alertDialog.findViewById(R.id.st);
as.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent m) {
if (m.getAction() == MotionEvent.ACTION_DOWN) {
Log.println(Log.ERROR, "Ken", "Tweed");
if (tetrisgame.toggleMusic()) {
String uri = "#drawable/music_on"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
soundToggle.setImageDrawable(res);
// soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, alertDialog.findViewById(android.R.id.message).getTheme()));
} else {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, null));
}
}
return true;
}
});

NullPointerException:Attempt toget length of null array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i need to create playlist from sdcard when i run my application it generate null pointer exception attempt get length of null array. because it could not read file from sdcard. But i have song files in emulator sdcard folder.Here is the code i have tried but it not work please help me to fix the problem.
class Mp3Filter implements FilenameFilter{
public boolean accept(File dir,String name) {
return (name.endsWith(".mp3"));
}
}
public class Audio extends ListActivity{
private MediaPlayer mp=new MediaPlayer();
private final String SD_PATH=new String("/sdcard/");
private List<String> songs=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
updatePlaylist();
Button stpbtn =(Button) findViewById(R.id.stpbtn);
stpbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.release();
}
});
}
private void updatePlaylist()
{
try
{
File home = new File (SD_PATH);
if(home.listFiles(new Mp3Filter()).length > 0)
{
for(File file:home.listFiles(new Mp3Filter()))
{
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(Audio.this,R.layout.song_item,songs);
setListAdapter(songList);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
here is my audio.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/android:list"
android:layout_width="match_parent"
android:layout_height="401dp" >
</ListView>
<Button
android:id="#+id/stpbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/stpbtn" />
</LinearLayout>
here is song_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="#+id/text1" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
From the JavaDoc for File.listFiles(FileFilter):
The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
So you need to check this explicitly.
File home = new File (SD_PATH);
File[] listOfFiles = home.listFiles(new Mp3Filter());
if(listOfFiles != null && listOfFiles.length > 0) {
...
}
And/Or work in a check that the file is in fact a directory:
File home = new File (SD_PATH);
if(!home.isDirectory()) {
// Error case, handle it.
}

How to Add multiple choice checkboxes in alert Dialog in Android?

I have created menu "Sync" in android app. when we click on "Sync" alert open a 4 checkboxes layout. what I want is to have them in function like when I click on 15 minutes then other option unclicked automatically.
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_settings:
alertDialog = new AlertDialog.Builder(HomePage.this).create(); //Read Update
LayoutInflater adbInflater = this.getLayoutInflater();
View checkboxLayout = adbInflater.inflate(R.layout.sync_layout, null);
defaultchkbox = (CheckBox)checkboxLayout.findViewById(R.id.defaultchkbox);
after15mint = (CheckBox)checkboxLayout.findViewById(R.id.after15mint);
after30mint = (CheckBox)checkboxLayout.findViewById(R.id.after30mint);
after45mint = (CheckBox)checkboxLayout.findViewById(R.id.after45mint);
alertDialog.setView(checkboxLayout);
alertDialog.setTitle("Synchronization");
alertDialog.setMessage("Choose");
alertDialog.setButton(Dialog.BUTTON_POSITIVE,"Save changes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
boolean checkBoxResult = false;
if(after15mint.isChecked())
{
Toast.makeText(getApplicationContext(), "15 Minute checked", Toast.LENGTH_LONG).show();
checkBoxResult = true;
}
else if(after30mint.isChecked())
{
Toast.makeText(getApplicationContext(), "30 Minute checked", Toast.LENGTH_LONG).show();
checkBoxResult = true;
}
else if(after45mint.isChecked())
{
Toast.makeText(getApplicationContext(), "45 Minute checked", Toast.LENGTH_LONG).show();
checkBoxResult = true;
}
else{
Toast.makeText(getApplicationContext(), "Default", Toast.LENGTH_LONG).show();
}
}
});
alertDialog.setButton(Dialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.dismiss();
}
});
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
But I am little bit confused over working of check boxes in alert. Suggestions will be great help. Thank you. :)
It looks like you need to work with Radio Buttons which are nested within a RadioGroup. It will then only allow you to select one option at a time.
For more information on RadioGroup look at:
http://developer.android.com/reference/android/widget/RadioGroup.html
For more information on creating Radio Buttons look at:
http://developer.android.com/reference/android/widget/RadioButton.html
in particular to your code you will have to define RadioButtons within a RadioGroup in your R.layout.sync_layout like for example
<RadioGroup
android:id="#+id/syncGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/defualt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Default"
android:checked="true" />
<RadioButton
android:id="#+id/minute15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "15 Minute" />
<RadioButton
android:id="#+id/minute30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "30 Minute" />
<RadioButton
android:id="#+id/minute45"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "45 Minute" />
</RadioGroup>
See this link.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color);
.setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}

Categories