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
}
Related
Android newbie here.
The scenario
I am using my website's api to populate data for Android ListView
for the first screen it is called GameFragment. Game fragment loads the games from my website url
I was able to successfully list all games. So my next step would be to show all articles related to the game when user clicks on the game. Using my websites api http://www.gamerzwiki.com/api/news.json?game_id=qwert133 (whatever the id of the item is)
Loading Contents from url
try {
JSONArray games = gp.loadGamesFromApi();
ArrayList<Games> listData = new ArrayList<Games>();
if(games != null){
for(int x = 0 ; x<games.length() ; x++){
JSONObject game = games.getJSONObject(x);
try {
Games game1 = new Games();
game1.title=game.getString("title");
game1.id = game.getInt("id");
listData.add(game1);
//free game 1
game1 = null;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ArrayAdapter<Games> adapter = new ArrayAdapter<Games>(getActivity(),android.R.layout.simple_list_item_1, listData);
setListAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
so I have a listener
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Object item = l.getSelectedItem();
Toast.makeText((Context)getActivity(),item.title.toString() , Toast.LENGTH_LONG).show();
Intent intent = new Intent(v.getContext(), NewsActivity.class);
startActivity(intent);
}
but it seems I can't get the attribute of the item
but I don't know how I can do that on my ListView. So I would like to ask your expert advise
what you can do is implement onClick listener on your listview which has all the games:-
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Games game = adapter.getItem(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
intent.putExtra("id",game.id);
startActivity(intent);
}
});
in your other activity retrieve this as:-
String id=getIntent.getStringExtra("id");
and now you can use this id to make webservice call in your activity,here ItemClicked is your model class which your are using to populate your listview with your all games
You can pass data between activities by using putExtra in the intent
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Games item = adapter.getItem(position);
Intent intent = new Intent(v.getContext(), NewsActivity.class);
intent.putExtra("id", item.id);
startActivity(intent);
}
In your receiving activity do this
String id = getIntent().getStringExtra("id");
You can pass basic datatypes through putExtra. If you want to pass custom objects you'll have to implement Parcelable http://developer.android.com/reference/android/os/Parcelable.html
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");
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.
I have a ListView. It contains JSON I pulled from the web. I want each item in the ListView to go to the same activity and the same TextView. That's easy enough on the face of it.
However I want the TextView to show different items depending on what the user clicked on. In fact better make it two TextViews because one of them has a link. There's two lines of text, one is a link.
So if the user presses the first list item, they go to this activity and be presented with information_01. If the same user backs out and then goes to the second list item it should go to the very same activity and show information_02, and so on.
I'll show you what I have so far, it's nothing special:
title.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
switch (position) {
case 0:
Driver p = (Driver) title.getItemAtPosition(position);
Intent i = new Intent(MainActivity.this, DataActivity.class);
i.putExtra("one_id", p.id);
i.putExtra("one_link", p.link);
MainActivity.this.startActivity(i);
case 1:
Driver p1 = (Driver) title.getItemAtPosition(position);
Intent i1 = new Intent(MainActivity.this, DataActivity.class);
i1.putExtra("two_id", p1.id);
i1.putExtra("two_link", p1.link);
MainActivity.this.startActivity(i1);
case 2:
break;
}
Hopefully this is possible because creating a million activities for each list item is a pain in the arse. Like I said one of them is a link which I need to send to another page on my app. So please bare in mind that showing it and clicking on it is needed.
Would great appreciate some help on the matter. Thanks in advance.
EDIT: My DataActivity.class
public class DataActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_list);
//Case 0
Intent intent0 = getIntent();
String link0 = intent0.getStringExtra("one_link");
String id0 = intent0.getStringExtra("one_id");
TextView data0 = (TextView) findViewById(R.id.case0Text);
data0.setText("ID: " + id0 + "\n\n Click here: " + link0);
//Case 1
Intent intent1 = getIntent();
String id1 = intent1.getStringExtra("two_id");
String link1 = intent1.getStringExtra("two_link");
TextView data1 = (TextView) findViewById(R.id.case1Text);
data1.setText("ID: " + id1 + "\n\n Click here: " + link1);
}
}
Try like this
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long arg3) {
Driver driver = (Driver) parent.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, DataActivity.class);
intent.putExtra("one_id", driver.id);
intent.putExtra("one_link", driver.link);
MainActivity.this.startActivity(intent);
}
Hope this will work.
Where are you storing your json data? Store it in an hashmap and retreive it based on the position of itemclick method, you dont have to do this much of things .
Try this
title.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Driver p = (Driver) title.getItemAtPosition(position);
Intent i = new Intent(MainActivity.this, DataActivity.class);
i.putExtra("id", p.id);
i.putExtra("link", p.link);
}
DataActivity.class
public class DataActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_list);
//Case 0
Intent intent0 = getIntent();
String link0 = intent0.getStringExtra("link");
String id0 = intent0.getStringExtra("id");
TextView data0 = (TextView) findViewById(R.id.case0Text);
data0.setText("ID: " + id0 + "\n\n Click here: " + link0);
}
}
You can take two textView in DataActivity's xml, one for id id and one for link and make link's textview clickable, and set a clickListener on it.
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));