So I'm trying to pass some data via Intent extras to the second activity. This code worked fine with ListView, but now when I switched to RecyclerView it doesn't show any text, text area is blank.
Here's the code: (starting in onBindViewHolder())
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passData();
}
});
}
private void passData() {
Todo item = new Todo();
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());
c.startActivity(i);
}
And this is how I get in in second activity:
Bundle extras = getIntent().getExtras();
String naslov = extras.getString("nazivTodoa");
String datum = extras.getString("datumTodoa");
textViewNazivTodoaDetails.setText(naslov);
textViewDatumTodoaDetails.setText(datum);
What am I doing wrong?
What you are doing wrong, is you are not getting the current object that is clicked on. You do that by getting your object from the arraylist you use in your adapter. Do it like that:
Arraylist<Item> yourlist = new Arraylist();
#Override
public void onClick(View v) {
// position = pass the current position of the object you want
passData(int position);
}
});
}
private void passData(int position) {
Todo item = new Todo();
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", yourlist.get(position).getTitle());
i.putExtra("datumTodoa", yourlist.get(position).item.getRecordDate());
i.putExtra("idTodoa", yourlist.get(position).item.getItemId());
c.startActivity(i);
}
Like dymmeh said, you need to pass the item in the list to the new activity. You are currently passing a newly created empty object.
Instead of
Todo item = new Todo();
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());
You should have
Todo item = listData.get(itemPosition);
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());
Related
I need to know how to do that?
I have two views
ActivityMain.java
FilmActivity
In MainActivity, I created an intent to get some information from the second view:
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
simpleGrid.setAdapter(customGridviewAdapter);
simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), FilmActivity.class);
intent.putExtra("FilmBoster", filmList.get(position).getBackdrop_path())
.putExtra("FilmImage", filmList.get(position).getPoster_path())
.putExtra("FilmName", filmList.get(position).getTitle())
.putExtra("FilmDate", filmList.get(position).getRelease_date())
.putExtra("FilmDisc", filmList.get(position).getOverview())
.putExtra("isFavFilm", filmList.get(position).getIsLiked());
startActivityForResult(intent, 2);
}
});
}
Second view :
private void sendDataToMainActivity(String isPressed) {
Intent intent = new Intent();
intent.putExtra("isPressed" , isPressed);
setResult(1 , intent);
finish();
}
I have used AsyncTask In MainActivity. The second activity sent the data in onActivityResult but ( onActivityResult ) execute After AsyncTask and in AsyncTask, I set some data on DB. So that the data that returned from the Second Activity is equal to null.
Some codes to help
#NonNull
private String convertToString(InputStream in) {
String res = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sd = new StringBuilder();
try {
while ((res = reader.readLine()) != null) {
sd.append(res).append("/n");
}
} catch (IOException e) {
e.printStackTrace();
}
parseString(sd.toString());
db.userDao().updateFilmList(filmList);
return sd.toString();
}
private void parseString(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject filmObject = jsonArray.getJSONObject(i);
Film film = new Film(filmObject.getString("title")
,filmObject.getString("overview")
, filmObject.getString("poster_path")
, filmObject.getString("release_date")
,db.userDao().getIsFave());
filmList.add(film);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is two methods inside AsyncTask that save data to db
What should I do if I want the data return on AsyncTask and set it on DB?
Do the following up in your onCreate or onResume methods in your MainActivity class:
// filmList should be an empty array at this point
CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
simpleGrid.setAdapter(customGridviewAdapter);
simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), FilmActivity.class);
intent.putExtra("FilmBoster", filmList.get(position).getBackdrop_path())
.putExtra("FilmImage", filmList.get(position).getPoster_path())
.putExtra("FilmName", filmList.get(position).getTitle())
.putExtra("FilmDate", filmList.get(position).getRelease_date())
.putExtra("FilmDisc", filmList.get(position).getOverview())
.putExtra("isFavFilm", filmList.get(position).getIsLiked());
startActivityForResult(intent, 2);
}
});
Then, in your postExecute method, you just need to do this (assuming you have repopulated your filmList in the Async Task):
CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
simpleGrid.setAdapter(customGridviewAdapter);
The onItemClicked handler will send the item clicked on to the FilmActivity.java class activity. In the onCreate of that activity, you need to read the data passed to it from the MainActivity:
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.film_activity_layout);
FilmName = (String) getIntent().getExtra("FilmName");
...
}
You need to show the onActivityResult code from the MainActivity
Do you have to use Async Task? I would suggest to use RxJava instead.
However, you can create a class that extends AsyncTask and send the Context in the constructor in order to setResult and finish the current activity in onPostExecute.
Example : https://stackoverflow.com/a/16921076/12009871
I have a news article app that has a gridview of all articles then you can select the full article. I want the user to receive a notification when a new news article has been posted. It just has to be really simple, the app logo and some text 'new article posted!' and then when they click on the notification the app is opened. Here is my code below, i'm not sure what you need to see though so let me know if you need anything else.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
newsListView.setAdapter(adapter);
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
}
};
}
I am not 100% sure about when new article is posted.
If I am right, after adapter.notifyDataSetChanged() notify user with notificatoins by below code:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Replace ResultActivity.class to your result notification class.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// first element (0) allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
How can i sort the arraylist if the user inputs values himself. For example if user adds: Ben, Tom, Jack. And then presses play it opens a new activity and shows the name Jack. if you press back, Tom. And then Ben. I want it to be the other way around. I tried collections.sort() but had no luck with it. Any other ideas?
The array:
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
The way user adds names:
public void onClick(View v) {
String input = mYrasytiVarda.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}else{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Klaida:");
alertDialog.setMessage("Blogai yrašytas vardas");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
}
Here I get the names and send them to the other activity:
#Override
public void onClick(View v) {
// count items
int i;
for (i = 0; i < adapter.getCount(); i++) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
}
Here I display them:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
//get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList");
//show the player list
mZaidejas = (TextView)findViewById(R.id.ZaidejoVardas);
mZaidejas.setText(myVal);
}
});
}
In this loop:
for (i = 0; i < adapter.getCount(); i++) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
... you create the activity once for each item in the list, in the order they are stored in the ArrayAdapter. You could just iterate through the items in the reverse order.
Eg:
#Override
public void onClick(View v) {
for (int i = adapter.getCount()-1; i >= 0; i--) {
String item = adapter.getItem(i);
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", item);
startActivity(pradetiZaidima);
}
}
I create an activity with dynamic buttons in a loop. I get a list and create a button for each element in the list. The buttons go to the same activity afterward, but with each button I want to pass different string.
I did this in the loop:
tour_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TourListActivity.this,
TourMenuActivity.class);
String info = tour.toString();
intent.putExtra(TOUR_INFO, info);
startActivity(intent);
}
});
But at the end, all the buttons get the same string (the string of the last button).
========================================
full code:
try {
JsonObject respObject = jsonParser.parse(response).getAsJsonObject();
JsonArray tourListArray = respObject.getAsJsonArray("tours");
System.out.println("tourListArray: " + tourListArray.toString());
for(int i = 0; i < tourListArray.size(); i++){
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
tour = tourListArray.get(i).getAsJsonObject();
String tourCode = tour.get("tourcode").getAsString();
Button tour_button = new Button(this);
tour_button.setText("Tour Code: " + tourCode);
tour_button.setGravity(Gravity.LEFT);
tour_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TourListActivity.this,
TourMenuActivity.class);
String info = tour.toString();
intent.putExtra(TOUR_INFO, info);
startActivity(intent);
}
});
ll.addView(tour_button);
LinearLayout yourLL = (LinearLayout) findViewById(R.id.Tours_List);
yourLL.setOrientation(LinearLayout.VERTICAL);
yourLL.addView(ll);
}
} catch (JsonIOException e) {
e.printStackTrace();
}
When you create the button you can:
button.setTag(someString);
and then in the onClick you can:
public void onClick(View v) {
Intent intent = new Intent(TourListActivity.this,
TourMenuActivity.class);
String info = tour.toString();
intent.putExtra(TOUR_INFO, ((Button)v).getTag());
startActivity(intent);
}
The variable tour is defined outside the loop, so each button share the same variable.
At each iteration, you just change the reference stored by this variable.
You could to create a final variable inside your loop, and use it inside the OnClickListener:
for (int i = 0; i < tourListArray.size(); i++) {
...
final String tourInfo = tour.info;
tour_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(
TourListActivity.this,
TourMenuActivity.class
);
intent.putExtra(TOUR_INFO, tourInfo);
startActivity(intent);
}
});
...
}
This is the ArrayList page that opens as a result page after update and save. I guess I would need to somehow refresh so that it reflects the changes on the UI. I've tried to call notifyDataSetChanged() but no luck with my level of experience. Could someone kindly show how to implement it please?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_requests);
requestsList = new ArrayList<HashMap<String, String>>();
new LoadAllRequests().execute();
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String request_id = ((TextView) view.findViewById(R.id.request_id)).getText().toString();
Intent in = new Intent(getApplicationContext(),
ViewRequestActivity.class);
in.putExtra(TAG_ID, request_id);
startActivityForResult(in, 100);
}
});
}
// Response from ViewRequestActivity when delete a request reload this page again
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllRequests extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_requests, "GET", params);
Log.d("All Requests: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
requests = json.getJSONArray(TAG_REQUESTS);
for (int i = 0; i < requests.length(); i++) {
JSONObject c = requests.getJSONObject(i);
String request_id = c.getString(TAG_ID);
String request_title = c.getString(TAG_TITLE);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, request_id);
map.put(TAG_TITLE, request_title);
requestsList.add(map);
}
} else {
Intent i = new Intent(getApplicationContext(),
NewRequestActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
You need to create an adapter for your ListView. The adapter is what feeds data to it for displaying. I would recommend you reading through this tutorial:
http://www.vogella.com/articles/AndroidListView/article.html
So once you have created your adapter and then called lv.setAdapter(<adapter>), you can then call <adapter>.notifyDataSetChanged(). This will tell the adapter that it needs to refresh itself.
You can use notifyDataSetChanged() method for your adapter.Wherever you want to update your listview you can use in following manner.
adapter.notifyDataSetChanged();