load content dynamically from listview to another activity - android

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

Related

how can i receive intent on 2 activities?

I want to receive intent on the two activity classes, but not sure how since startActivity can only start one intent to only one activity class
private void populateListView()
{
Log.d(TAG, "Populating listview");
Cursor data = dbManager.getTitle();
final ArrayList<String> listTitle = new ArrayList<>();
while (data.moveToNext())
{
listTitle.add(data.getString(1));
}
final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listTitle);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
String name = adapterView.getItemAtPosition(position).toString();
Cursor data = dbManager.getTitleID(name);
int titleID = -1;
while (data.moveToNext())
{
titleID = data.getInt(0);
}
if (titleID > -1)
{
Intent intent= new Intent(List_Title_Activity.this, MainActivity.class);
//Intent intent2= new Intent(List_Title_Activity.this, ViewListContents.class);
intent.putExtra("id", titleID);
intent.putExtra("title", name);
startActivity(edit);
}
else
{
Toast.makeText(List_Title_Activity.this, "No id associated with that name", Toast.LENGTH_SHORT).show();
}
}
});
MainActivity and ViewListContent:
Intent receiveIntent = getIntent();
selectedID = receiveIntent.getIntExtra("id",-1);
1 Activity is 1 page in android. That is, you can call/view 1 page/Activity at a time. If you want to share same data to multiple pages in use shared preference / Database. Or if you are using 1 activity and multiple fragments in it, use interface.
if you want to send data from one activity to 2nd activity you can use simple intent and pass data from first activity to second . But if you want to send the data first activity to second and get data from second activity to first activity i suggest you to use startActivityForResult. for more see here

Keep changes in activity even after closing it

I have a listview which when clicked on listitem opens a new singleitenview activity
The singleitenm view consists of a button which is used to add the corresponding listitem to favorites activity(if not yet added) and changes the button color to yellow indicating it is added to favoorites or else gray if not in favorites
Till here everything works fine but if i close the singleitemview and reopen it the button color changes back to previous color but still in facvorites
What shall i do to the button color not getting changed
favbtn of singleitemview activity
final Button btn = (Button) findViewById(R.id.singleitemButton1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
products=new ArrayList<Product>();
Bundle extras = getIntent().getExtras();
String jsonObj = extras.getString("selected item");
ObjectMapper mapper = new ObjectMapper();
try
{
Product pro = mapper.readValue(jsonObj, Product.class);
if (checkFavoriteItem(pro)) {
sharedPreference.removeFavorite(SingleItemView.this, pro);
btn.setBackgroundColor(Color.GRAY);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
} else {
sharedPreference.addFavorite(SingleItemView.this, pro);
Toast.makeText(SingleItemView.this,
SingleItemView.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
btn.setBackgroundColor(Color.YELLOW);
}
}
catch (IOException e)
{};
});
onitemclick of my list activity
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ObjectMapper mapper = new ObjectMapper();
Product pro = productListAdapter.getItem(position);
String favimg = ((ImageView) view.findViewById(R.id.imgbtn_favorite)).toString();
try
{
String hi = "this is testint";
String jsonInString = mapper.writeValueAsString(pro);
Intent intent = new Intent(activity.getApplicationContext(), SingleItemView.class);
intent.putExtra("selected item", jsonInString);
;
startActivityForResult(intent, 1);
// startActivity(intent);
}
catch (JsonProcessingException e)
{}
}
In the onCreate() method of your singleitemview activity, after you inflate the view that has the favorite button, you simply need to check if the item is in favorites and set the button's background color accordingly.

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.

Categories

Resources