(Java) Declare ArrayList to use in other class - java

I have following code which is as a final result giving me list of images from Android device larger than 500 KB:
package com.click;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.widget.LinearLayout;
import android.widget.TextView;
public class SkanerActivity extends Activity {
private File root;
private ArrayList<File> fileList = new ArrayList<File>();
private LinearLayout view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skaner);
//TEST
view = (LinearLayout) findViewById(R.id.view);
//getting SDcard root path
root = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
getfile(root);
for (int i = 0; i < fileList.size(); i++) {
TextView textView = new TextView(this);
textView.setText(fileList.get(i).getName());
textView.setPadding(5, 5, 5, 5);
System.out.println(fileList.get(i).getName());
if (fileList.get(i).isDirectory()) {
textView.setTextColor(Color.parseColor("#FF0000"));
}
view.addView(textView);
}
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
// Zakomentowane aby nie dodawac do listy folderów
// fileList.add(listFile[i]);
getfile(listFile[i]);
} else if (listFile[i].length() >= 500 * 1024) {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif"))
{
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
}
Now I would like to create new class to process further with new operations on this list of images - in new class.
My question is: how can I handle and declare fileList as a variable (Object) to be used in other class (new Java class)? I know, that in Java there isn't such method as "Global variable", but for sure is there any method to use result of script in other place (Class) in Application.
Can you please help me with my issue? Many thanks in advance for your help!

If by new class you mean new Activity then you can pass data using
Intent intent = new Intent(getBaseContext(), NewClass.class);
intent.putExtra("imageList", fileList);
startActivity(intent);
But prior to that you need to get reference to this List in the current class
fileList = getfile(root);
But if you simply mean need a new Class for processing. Simply create a new class. Define a constructor/method that takes ArrayList<File> argument. Create an object of this new class from your current class passing the list of files as argument and call the method in it for your further processing logic.
class ImagesProcessorClass {
List<File> imageList;
public ImagesProcessorClass (List<file> imageList) {
this.imageList = imageList;
}
public void processsImages(){
//do processing on imageList
}
}
and in your present class do
public class SkanerActivity extends Activity {{
//your present code
protected void onCreate(Bundle savedInstanceState) {
//your present code
fileList = getfile(root);
ImagesProcessorClass imageProcessor = new ImagesProcessorClass (fileList);
imageProcessor.processsImages();
}
}

If you want to use it in another activity, you can use something like that
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("List", fileList);
startActivity(intent);
And in AnotherActivity have to do this
Intent data = getIntent();
List<File> files = (List<File>)data.getSerializableExtra("List");
Also you can make this list static and create method to get it;

Make fileList a private member of the class. Then add accessor methods to access it from outside the class . You will of course need to create an object of SkanerActivity to do so.
class SkanerActivity{
...
private ArrayList<File> fileList = new ArrayList<File>();
public getFileList(){
return fileList;
}
...
}
Class Access{
void function1(){
SkanerActivity obj = new SkanerActivity();
List fileList = obj.getFileList();
..
}

Related

Displaying Images Dynamically

I am using the following code to display images from drawable folder.
But now i want to display pictures dynamically.Every time a new image is added to the drawable folder i don't want go again in the code and add it in the array it should automatically increment and get displayed.
Any Idea how should I go about this.Just started working on Android.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.widget.ImageView;
import android.app.Service;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private static ImageView imgView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
final int[] images=images{R.drawable.ic_launcher,
R.drawable.ic_launcher1,R.drawable.ic_launcher2,etc..};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run() {
imgView.setImageResource(images[i]);
i++;
if(i>images.length-1)
{
i=0;
}
handler.postDelayed(this,5000); //for interval...
}
};
handler.postDelayed(runnable, 5000); //for initial delay..
}
if you want to add the image Dynamically you can Naming the image File like this : Image1.png; Image2.png; and so on.
And then you dont need to call all of them in the array, instead you can using lopp to get the name of the image in resource.
and then get the id using the code below :
public int getID(String resourceName,Context context){
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(resourceName, "drawable",
context.getPackageName());
return resourceId;
}
Note : after adding the image don't forget to increament the loop. hope it helps.
please keep variable i as static
i.e static int i=0;
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
imgView.setImageResource(images[i]);
i++;
if(i>images.length-1)
{
i=0;
}
handler.postDelayed(this,5000); //for interval...
}
};
handler.postDelayed(runnable, 5000); //for initial delay..
change the handle code as follow
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
imgView.setImageResource(images[i]);
if(i>images.length-1)
{
i=0;
}
else
{
i++;
}
handler.postDelayed(this,5000); //for interval...
}
};
handler.postDelayed(runnable, 5000); //for initial delay..

Calling values from an array in the string.xml file in an Android app

I have built a fortune cook app that previously currently has values hardcoded into an array
FortuneActivity.java
package juangallardo.emofortunecookie;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
package juangallardo.emofortunecookie;
import java.util.Random;
public class FortuneBox {
public String[] mFortunes = {
"What is the point?",
"Sometimes it is best to just sleep in.",
#98 other fortunes...
};
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
The problem is that now I want to add a Spanish version. So I realize that i should add that array into the strings.xml.
I looked up string resources on the Android developer page. and it gave me the idea to add this to my code
strings.xml
<string-array name="emo_fortunes">
<item>What is the point?</item>
<item>Sometimes it is best to just sleep in.</item>
</string-array>
But now I am stuck on where to add this part that has the part about Resources, etc.
I followed along to a tutorial from Treehouse about strings but my app kept crashing.
Basically the change that I made was to make the original array into
FortuneBox.java
# above unchanged from previous code
public String[] mFortunes;
# below unchanged from previous code
FortuneActivity.java
# same imports as before
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
Resources resources = getResources();
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
These were my errors, but not sure where to go from here as I am new to Android and I have not touched Java since college.
log
FortuneActivity.java
FortuneBox.java
Mikki has the right answer, but it is a little confusing. In your code above, you are using the same name for two different variables: mFortuneBox. This is the root of your trouble:
private FortuneBox mFortuneBox = new FortuneBox();
...
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Change the second one to a different name, like this, and the errors go away:
final String[] fortunes = resources.getStringArray(R.array.emo_fortunes);
However, you still aren't using these fortunes from the array anywhere. You can actually delete fortunes from your Activity and move it to your FortuneBox class instead. This is slightly tricky, though, as you need to know what the context is to get a string array resource in your other class. The context is the Activity, so you need to pass this along as a parameter when you create your FortuneBox object.
I'd recommend a slight restructuring. Below are the two files that should work for you:
FortuneActivity.java
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
mFortuneBox = new FortuneBox(this);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
public class FortuneBox {
public String[] mFortunes;
public FortuneBox(Context context) {
Resources resources = context.getResources();
mFortunes = resources.getStringArray(R.array.emo_fortunes);
}
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
Your problem is simple. You can not access a non-final from an inner class (in this case your OnClickListener).
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Try just changing the line to look like this one above.
Hope it helps.
The mFortuneBox variable in the previous way you have used is an object of FortuneBox class and hence this call mFortuneBox.getFortune() works.
In the later changed code, you have made mFortuneBox variable a reference to an Array of strings. But still tried calling mFortuneBox.getFortune(). 'getFortune()' is a method of FortuneBox class right, so you can call it with an object of Forune Box class itself.
Try doing this:
final String[] fortuneArray = resources.getStringArray(R.array.emo_fortunes);
and
private FortuneBox mFortuneBox = new FortuneBox();
Now call mFortuneBox.getFortune(fortunearray) sending it this array to the getfortune method.
Now let the getFortune() method randomly pick one from this array passed and return the random string picked

How to put AlertDialog in static method

How to show Alert Dialog in static method, i am trying to put a condition, in which i am checking for the folder inside the SD Card, if exist then listing Items, otherwise i want to show AlertDialog - with message no folder found with Church Name
public static List <String> fromSDCard()
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}else{
// here i want to put AlertDialog
}
return listChurchWall;
}
Pass your app context to the static method.
public static List <String> fromSDCard(Context context)
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}else{
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
// 4. Show the dialog
dialog.show()
}
return listChurchWall;
}
If calling from your activity.
public MyActivity extends Activity
{
....
private void Method()
{
List<String> list = fromSdCard(this);
}
....
}
public static List<String> fromSDCard(Context mContext) {
List<String> listChurchWall = new ArrayList<String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File(string + name + "/");
if (f.exists()) {
files = f.listFiles();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
int imageResource = android.R.drawable.stat_sys_warning;
Drawable image = mContext.getResources().getDrawable(imageResource);
builder.setTitle("title").setMessage("your Message").setIcon(image).setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
return listChurchWall;
}
Try the following way--
public static List <String> fromSDCard(Activity a, String title, String message)
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}
else
{
AlertDialog.Builder dialog = new AlertDialog.Builder(a);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setNeutralButton("OK", null);
dialog.create().show();
}
return listChurchWall;
}
Then in your class do---
public MyActivity extends Activity
{
....
private Method()
{
List<String> list = fromSdCard(this, "Your Title", "Your message");
}
....
}
UPDATE:
You get a NullPointerException because something is null that shouldn't be. It happens while sorting the array, so perhaps one of the array elements is null. Take a look at how you assign values to your array.
Perhaps at the top of it, see if any of the objects Object o1 or Object o2 themselves are null.

Getting Media Title from a File

I used import java.io.File; to import all music files from my sdcard,
Now i want the Title's of the files using Mediastore but how do I do that?
This is the code I Use now.
public class ListFiles extends ListActivity {
private List<String> directoryEntries = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
File directory = new File(i.getStringExtra("directory"));
if (directory.isDirectory()){
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2) {
return -Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
this.directoryEntries.clear();
for (File file : files) {
this.directoryEntries.add(file.getName());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,R.layout.file_row, this.directoryEntries);
this.setListAdapter(directoryList);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File clickedFile = new File(this.directoryEntries.get(position));
Intent i = getIntent();
i.putExtra("clickedFile", clickedFile.toString());
setResult(RESULT_OK, i);
finish();
}
}
Thanks.
I have done that for Video files using MediaStore : Class Overview - The Media provider contains meta data for all available media on both internal and external storage devices.
You can refer these two example to understand the use of MediaStore
List Video and List Audio

Problem with ArrayList

I am fairly new to Java programming and was following a tutorial located here: http://coenraets.org/blog/android-samples/androidtutorial/
Where I copied the code I am having a problem with here: http://code.google.com/p/androidtutorial/source/browse/trunk/%20androidtutorial/EmployeeDirectory6/src/samples/employeedirectory/EmployeeDetails.java
EDIT: Thank You all. Thanks to #adamcodes for pointing out I totally missed that link where he put out the source code. It looks like he forgot to include that link in the step by step tutorial.
At about 25 lines down I'm getting an error at
protected ArrayList<EmployeeAction> actions;
which says "EmployeeAction cannot be resolved to a type" My question is does the class EmployeeAction have to be created
actions = new ArrayList<EmployeeAction>();
Even if I put "actions = new ArrayList();" in my code? If so what should the class contain?
package samples.employeedirectory;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class EmployeeDetails extends ListActivity {
protected TextView employeeNameText;
protected TextView titleText;
protected ArrayList<EmployeeAction> actions;
protected EmployeeActionAdapter adapter;
protected int employeeId;
protected int managerId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.employee_details);
employeeId = getIntent().getIntExtra("EMPLOYEE_ID", 0);
SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT emp._id, emp.firstName, emp.lastName, emp.title, emp.officePhone, emp.cellPhone, emp.email, emp.managerId, mgr.firstName managerFirstName, mgr.lastName managerLastName FROM employee emp LEFT OUTER JOIN employee mgr ON emp.managerId = mgr._id WHERE emp._id = ?",
new String[]{""+employeeId});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
employeeNameText = (TextView) findViewById(R.id.employeeName);
employeeNameText.setText(cursor.getString(cursor.getColumnIndex("firstName")) + " " + cursor.getString(cursor.getColumnIndex("lastName")));
titleText = (TextView) findViewById(R.id.title);
titleText.setText(cursor.getString(cursor.getColumnIndex("title")));
actions = new ArrayList<EmployeeAction>();
String officePhone = cursor.getString(cursor.getColumnIndex("officePhone"));
if (officePhone != null) {
actions.add(new EmployeeAction("Call office", officePhone, EmployeeAction.ACTION_CALL));
}
String cellPhone = cursor.getString(cursor.getColumnIndex("cellPhone"));
if (cellPhone != null) {
actions.add(new EmployeeAction("Call mobile", cellPhone, EmployeeAction.ACTION_CALL));
actions.add(new EmployeeAction("SMS", cellPhone, EmployeeAction.ACTION_SMS));
}
String email = cursor.getString(cursor.getColumnIndex("email"));
if (email != null) {
actions.add(new EmployeeAction("Email", email, EmployeeAction.ACTION_EMAIL));
}
managerId = cursor.getInt(cursor.getColumnIndex("managerId"));
if (managerId>0) {
actions.add(new EmployeeAction("View manager", cursor.getString(cursor.getColumnIndex("managerFirstName")) + " " + cursor.getString(cursor.getColumnIndex("managerLastName")), EmployeeAction.ACTION_VIEW));
}
cursor = db.rawQuery("SELECT count(*) FROM employee WHERE managerId = ?",
new String[]{""+employeeId});
cursor.moveToFirst();
int count = cursor.getInt(0);
if (count>0) {
actions.add(new EmployeeAction("View direct reports", "(" + count + ")", EmployeeAction.ACTION_REPORTS));
}
adapter = new EmployeeActionAdapter();
setListAdapter(adapter);
}
}
public void onListItemClick(ListView parent, View view, int position, long id) {
EmployeeAction action = actions.get(position);
Intent intent;
switch (action.getType()) {
case EmployeeAction.ACTION_CALL:
Uri callUri = Uri.parse("tel:" + action.getData());
intent = new Intent(Intent.ACTION_CALL, callUri);
startActivity(intent);
break;
case EmployeeAction.ACTION_EMAIL:
intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{action.getData()});
startActivity(intent);
break;
case EmployeeAction.ACTION_SMS:
Uri smsUri = Uri.parse("sms:" + action.getData());
intent = new Intent(Intent.ACTION_VIEW, smsUri);
startActivity(intent);
break;
case EmployeeAction.ACTION_REPORTS:
intent = new Intent(this, DirectReports.class);
intent.putExtra("EMPLOYEE_ID", employeeId);
startActivity(intent);
break;
case EmployeeAction.ACTION_VIEW:
intent = new Intent(this, EmployeeDetails.class);
intent.putExtra("EMPLOYEE_ID", managerId);
startActivity(intent);
break;
}
}
class EmployeeActionAdapter extends ArrayAdapter<EmployeeAction> {
EmployeeActionAdapter() {
super(EmployeeDetails.this, R.layout.action_list_item, actions);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
EmployeeAction action = actions.get(position);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.action_list_item, parent, false);
TextView label = (TextView) view.findViewById(R.id.label);
label.setText(action.getLabel());
TextView data = (TextView) view.findViewById(R.id.data);
data.setText(action.getData());
return view;
}
}
}
Java is statically typed, and everything you want to refer to at compile time needs to exist. So yes - you have to create the EmployeeAction, if you need it. (And you need to import it with import yourpackage.EmployeeAction; at the top of the class)
The type definition if the list <EmployeeAction> is there to enforce compile time safety for the elements of the list. It means "you can only put instances of EmployeeAction in this collection". This is useful when later you access the collection - the compiler can guarantee that the list contains only EmployeeAction instances
Yes it definitly have to exists (EmployeeAction class). For what it should contains, I'd say probably a constructor that take parameters like these : (String location, String phone, EmployeeAction.ACTION*) and then setters and getters for these values.
EmplyeeAction is a not Java known class. Then, it could be imported (if it exists) or created.
The list is irrelevant here. A few lines down, your code says:
actions.add(new EmployeeAction("Call office", officePhone, EmployeeAction.ACTION_CALL));
Yes, you do need a class EmployeeAction to compile that code. It's probably introduced in a part of the tutorial you overlooked or skipped.
you have to have a EmployeeAction class.
since you say that you are new to java it will be good if go through this tutorial

Categories

Resources