Passing parameters to another class - android

I have two classes one of them that I pass to sends two parameters which are
1- file URL
2- file name
because I dont want to create this class for every file I have
first class passes the parameters from OnItemClickListener
list.setOnItemClickListener(new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
// pass parameters file name & file url
}
the second class
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
OutputStream output=new FileOutputStream(new File(dir, filename));

you need to create a Bundle and store the URL and file name in it. And then you can pass this bundle in the intent that calls the new activity. In the new class, you extract the information from the bundle using getIntent().getExtras().

You can pass fileName and fileURL from first class like following,
// pass parameters file name & file url
Intent i = new Intent(FirstClass.this,SecondClass.this);
i.putExtra("FileName",fileName);
i.putExtra("FileURL",fileURL);
startActivity(i);
and get from second activity as following,
Bundle b = getIntent().getExtras();
filename = b.getString("fileName");
file_url = b.getString("fileURL");

You can do this by following code :
first class passes the parameters from OnItemClickListener
list.setOnItemClickListener(new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
// pass parameters file name & file url
Intent i = new Intent(FirstClass.this,SecondClass.this);
i.putExtra("FileName",fileName);
i.putExtra("FileURL",fileURL);
startActivity(i);
}
the second class
public void onClick(View v) {
filename = getIntent().getStringExtra("fileName");
file_url = getIntent().getStringExtra("fileURL");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
OutputStream output=new FileOutputStream(new File(dir, filename));

Related

I want to display image from internet from main activity to another activity?

I want to display image from internet from main activity to another activity. But it is not working. What I have done:
// Main Activity
gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current game that was clicked on
Games currentGame = mAdapter.getItem(position);
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri gameUri = Uri.parse(currentGame.getUrl());
// Create a new intent to view the game URI
Intent i = new Intent(GamesActivity.this,PreviewActivity.class);
i.putExtra("value",gameUri);
startActivity(i);
}
});
// Second Activity
public class PreviewActivity extends AppCompatActivity {
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
img = findViewById(R.id.imagePreview);
Uri i = getIntent().getData();
Picasso.with(this).load(i).into(img);
}
}
Intent intent=getIntent();
String i=intent.getStringExtra("value");
Picasso.with(this).load(i).into(img);
And url in string form.

Android onitemclicklistener issues

Dont know if I am even doing this right as I am new to android programming but I have set an OnItemClickListener to respond to the users listitem selection by beginning a new intent.
When the user selects whatever article in the listview they should see the corresponding txt file in the new activity.
So in the new activity I have tried to find a way to open the corresponding file in the subfolder of the Assets Folder ....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Intent i = getIntent();
int position = i.getExtras().getInt("position");
TextView news = (TextView) findViewById(R.id.txtView);
AssetManager as = getAssets();
InputStream is;
try{
is = as.open(""); <----- !!!
int bytes = is.available();
byte[] b = new byte[bytes];
is.read(b);
is.close();
String s = new String (b);
news.setText(s);
}catch (IOException e){
e.printStackTrace();
}
}
.... however i will only succeed in opening a single txt file.
How can I implement this activity to respond to the OnItemClickListener from the previous activity as shown here...
ls = (ListView) findViewById(R.id.bArt);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int position, long id) {
Intent i = new Intent (getApplicationContext(), New_Activity.class );
i.putExtra("id", position);
startActivity(i);
}
});
... to open the correct .txt file from the Assets Folder
I have been stuck on this for a long time now so my Appreciation points (no cash value) to the functional answer will be unending
Much Obliged
Change this
int position = i.getExtras().getInt("id");
Your Id name must same when ever you passing some data between Activity.
Instead of store the position, store the file name inside the intent. Yon can retrieve it with AdapterView.getItemAtPosition
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int position, long id) {
Intent i = new Intent (getApplicationContext(), New_Activity.class );
i.putExtra("id", av.getItemAtPosition(position));
startActivity(i);
}
});
In the other activity retrieve the file name and pass this to the AssetsManager
String fileName = i.getStringExtra("id");
InputStream is;
try{
is = as.open(fileName); <----- !!!
// other code
}

Passing values to Activities with putExtra()

I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");

How to get data from text file onListItemClick in android?

I am currently working on an app to make mods for minecraft. My app has a simple file manager where I want to get the file data and put it in another activity in an EditText, when the user selects a file. I don't know how to get the data and send it to an EditText in another activity.
EDIT:
This is my OpenScript.class which I'm trying to push the data inside the file in a EditText on another activity but I have no clue how to do that.
public class OpenScript extends ListActivity {
private List<String> items =null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scripts_list);
getFiles(new File("/sdcard/ChatoGuy1/ModPE Scripter/Scripts").listFiles());
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
try{
Intent i = new Intent(this, ScriptWriter.class);
i.putExtra("code", /* ? */);
startActivityForResult(i, 1);
}
catch(Exception e){
}
}
private void getFiles(File[] files) {
items = new ArrayList<String>();
for (File file : files) {
items.add(file.getPath());
}
ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.file_list_row, items);
setListAdapter(fileList);
}
}
Second Activity:
public class ScriptWriter extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.code_editor);
final EditText editText = (EditText) findViewById(R.id.codeEditor);
final Button codeSave = (Button) findViewById(R.id.bCodeSave);
//get file
Intent intent = getIntent();
String test = intent.getExtras().getString("code");
//read file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(test));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
Toast.makeText(this, "File does not exist.", Toast.LENGTH_LONG).show();
}
editText.setText(text);
}
}
How to get data from text file onListItemClick in android?
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
try{
TextView tv = v.findViewById(<id_of_infliated_textView_in_your_adapter_class>)
String path - tv.getText().toString();
Intent i = new Intent(this, ScriptWriter.class);
i.putExtra("code", path );
startActivityForResult(i, 1);
}
catch(Exception e){
}
}
The above code works when you use the custom adapter (creating your own adapter class and infiliating layout file).
In your case it is quite simple.
How could I go about doing that? I can't seem to understand on how to
send the URI to my second activity. I know how to read a file from a
given path but not when user selects a file
To get the file path
As you already declare your Array list globally, and using this method in your code.
private void getFiles(File[] files) {
items = new ArrayList<String>();
for (File file : files) {
items.add(file.getPath());
}
ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.file_list_row, items);
setListAdapter(fileList);
}
make one more method saying "getFileAtPosition"
private String getFileAtPosition(int position){
return items.get(position);
}
And call the above function in your onListItemClick method
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
try{
Intent i = new Intent(this, ScriptWriter.class);
i.putExtra("code",getFileAtPosition(position));
startActivityForResult(i, 1);
}
catch(Exception e){
}
}
When the user selects a file on Activity A, you want to open a file and read it's contents and send the contents to Activity B where it will be displayed in an EditText widget. Right?
There's no need to send the file contents to Activity B in an intent. Just send the file URI as part of the intent to Activity B and then do the file read operation there and populate your EditText. That's much cleaner.
HTH.

How to view an image from a list of images Android?

I am working on an application that saves images to a directory and then allows you to view those images. Currently I am able to save images and then view a list of the images within that directory. I want to be able to open an image in an imageview when the user selects the image file from the list. Here is the code I currently have for the list:
public class Test extends ListActivity {
private List<String> fileList = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
String root = Environment.getExternalStorageDirectory().toString();
File mapfiles= new File(root + "/Maps");
ListDir(mapfiles);
}
void ListDir(File f) {
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
//fileList.add(file.getPath());
fileList.add(file.getName());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
setListAdapter(directoryList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
String item=fileList.get(position).toString();
Toast.makeText(Test.this, "You clicked on: "+item, Toast.LENGTH_SHORT).show();
}
}
I used toast just to verify that I could get something to happen when clicking on an item in the list, and that is working. The code I tried to use within the onItemListClick is:
File selected = new File(fileList.get(position));
if(selected.isDirectory()){
ListDir(selected);
} else {
Uri selectedUri = Uri.fromFile(selected);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW, selectedUri);
startActivity(notificationIntent);
}
That causes the app to crash and I'm not sure why. My question is what is incorrect in the above code? Or simply how can I view an image by selecting it from my list?
Thanks.

Categories

Resources