I have scoured SE and google and found what I thought were decent examples of how to implement putExtra() in tandem with getStringExtra().
The trouble I seem to be unable to resolve is that my putExtra data never appears to be getting retrieved from my getStringExtra call in the target activity.
I've tried numerous SE examples where others have asked this question countless times and yet it never seems to get me closer to a working base to expand on.
My primary activity's put is as follows;
(First, I tried this with no luck)
// Click handler for group list items
lvGroups.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int gid = groupIds.get(arg2);
Intent intent = new Intent(RadSMS_Activity.this, RadSMS_CreateGroup.class);
intent.putExtra("SELECTED_GROUP_ID", gid);
startActivity(intent);
finish();
}
});
(Then, I tried this. Also with no luck.)
// Click handler for group list items
lvGroups.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int gid = groupIds.get(arg2);
Intent target = new Intent();
target.putExtra("SELECTED_GROUP_ID", gid);
Intent intent = new Intent(RadSMS_Activity.this, RadSMS_CreateGroup.class);
startActivity(intent);
finish();
}
});
My target activity that I want to extract the value from is the following;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.creategroup);
String strGID = getIntent().getStringExtra("SELECTED_GROUP_ID");
selectedGID = new Long(strGID);
// ... additional code would be here
}
Function truncated for brevity's sake.
So, according to everything I've seen so far, it appears I'm doing it right, but when I put a breakpoint at the line where selectedGID gets assigned its value, strGID is always null. This is really beginning to make me crazy.
Can anyone please tell me if I have done something incorrect?
gid is an int.
You are putting an int.
You appear to be trying to retrieve a string.
Consider:
int gid= getIntent().getIntExtra("SELECTED_GROUP_ID",-1);
You are putting an integer value while getting it as a string. It will always return null. Use intent.getExtras().getInt() instead of intent.getStringExtra().
Related
this is my first post here so be gentle :p
Here is the thing, I'm facing a really though issue and after several research i did not manage to figure out a clean solution. Let me explain:
I'm actually developing an android app for restaurant management.
In activity A, i'm able to create some articles with different parameters (picture, name, price ..).
I can also create a menu in which i indicate which articles are included. To do so i run Activity B that contains a dynamic list of the available articles (the ones i created) to be chosen. After picking up some of them the customised chosen objects are sent to Activity A through Parcel. And the chosen article list is updated in the menu.
But here is the thing, as far as i know, using Parcels create another instance of the object. As a result, if i modify or delete an article, the article list included in the menu does not change, and obviously i would like the list in the menu to be automatically updated.
Is there a way to simply pass customised objects through activities by reference?
What could be a clean solution to make the article list in the menu dynamic?
Here is some code:
In Activity A, in the menu interface i click + button to add an article, which run Activity B (the extras is the list of articles already included in the menu before, so in the beginning it's empty).
//Add article
FloatingActionButton addArticleButton = (FloatingActionButton)parentActivity.findViewById(R.id.addArticleButton);
addArticleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMenuDetails(menuListView,menuAdapter,currentMenu);
parentActivity.startActivityForResult(new Intent(parentActivity.getApplicationContext(),ChooseArticleActivity.class).putParcelableArrayListExtra("menuArticleList",currentMenu.getArticles()),PICK_ARTICLES);
}
});
In activity B: I select Articles in a list of available Articles (the ones i created). After picking up i press OK button to put the list of chosen articles in result Intent as Parcelable Extras
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_article_layout);
initializeLists();
this.resultIntent = new Intent();
}
private void initializeLists(){
final ListView articleToChoose = (ListView)findViewById(R.id.articleToChoose);
final ListView articleChosen = (ListView)findViewById(R.id.articleChosen);
final ArrayList<Article> articleToChooseList = (ArrayList<Article>)MainActivity.model.getArticleList().getArticleList().clone();
final ArrayList<Parcelable> articleChosenListParcelable = (ArrayList<Parcelable>)this.getIntent().getParcelableArrayListExtra("menuArticleList");
final ArticleAdapter articleToChooseAdapter = new ArticleAdapter(getApplicationContext(), articleToChooseList);
articleToChoose.setAdapter(articleToChooseAdapter);
ArrayList<Article> articleChosenListTemp = new ArrayList<>();
ArrayList<Article> articleToRemove = new ArrayList<>();
for(Parcelable a:articleChosenListParcelable){
articleChosenListTemp.add((Article)a);
for(Article article:articleToChooseList){
if(article.getName().equals(((Article) a).getName())){
articleToRemove.add(article);
}
}
}
articleToChooseList.removeAll(articleToRemove);
articleToChooseAdapter.notifyDataSetChanged();
final ArrayList<Article> articleChosenList = articleChosenListTemp;
final ArticleAdapter articleChosenAdapter = new ArticleAdapter(getApplicationContext(),articleChosenList);
articleChosen.setAdapter(articleChosenAdapter);
articleChosen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Article articleClicked = articleChosenAdapter.getItem(position);
articleChosenList.remove(articleClicked);
articleToChooseList.add(articleClicked);
articleChosenAdapter.notifyDataSetChanged();
articleToChooseAdapter.notifyDataSetChanged();
}
});
articleToChoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Article articleClicked = articleToChooseAdapter.getItem(position);
if(!articleChosenList.contains(articleClicked)){
articleChosenList.add(articleClicked);
articleToChooseList.remove(articleClicked);
articleToChooseAdapter.notifyDataSetChanged();
articleChosenAdapter.notifyDataSetChanged();
}
}
});
Button okButton = (Button)findViewById(R.id.okButton);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chosenArticleListAttr = articleChosenList;
resultIntent.putParcelableArrayListExtra("articleList",chosenArticleListAttr);
setResult(RESULT_OK,resultIntent);
finish();
}
});
Button cancelButton = (Button)findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
In activity A, in onActivityResult i catch the result and update the list, but the added Articles here are not the same instance as the article list in the model
if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();
ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
gestionMenusLayout.getCurrentMenu().getArticles().clear();
for(Parcelable a:chosenArticleList){
gestionMenusLayout.getCurrentMenu().addArticle((Article)a);
}
articleAdapter.notifyDataSetChanged();
}
For debugging purpose only, I suggest that you use a public static List<Article> articleList and call it directly from whether activity A or B
A better but take-alittle-more-effort solution is that you store the list in a database, and every updates, queries, ... come through it.You can use the server's database (where people usually get articles from), or a offline database like Realm here
I figured it out with a quite easy and simple solution finally.
I keep passing my Article objects through intents by parcels.
But as it creates a new instance, instead of adding this instance i add the original one (the one from the model) after an equality key check (the name of the article). By doing so i keep the reference on my Article.
Thank you for helping!
Edit:
Here is the code:
if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();
ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
gestionMenusLayout.getCurrentMenu().getArticles().clear();
ArrayList<Article> modelArticles = MainActivity.model.getArticleList().getArticleList();
for(Parcelable a:chosenArticleList){
for(Article modelArticle:modelArticles){
if(((Article)a).getName().equals(modelArticle.getName())){
gestionMenusLayout.getCurrentMenu().addArticle(modelArticle);
}
}
}
articleAdapter.notifyDataSetChanged();
}
Can someone help me with this error that I keep getting?
The program that I'm trying to make is online streaming radio.
I need to return the value "value" so i can use it in another java class.
ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ch);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public int onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), mPlayer.class);
i.putExtra("name", ch.get(position));
int value = listView.getItemAtPosition(position);
startActivity(i);
return value;
}
}
The problem occurs in this line:
int value = listView.getItemAtPosition(position);
getItemAtPosition() returns an Object, so you must convert it to an int before assigning it to an int variable. You should do this only if you're sure that your listView contains integers, otherwise you'll get a ClassCastException. Do it like this:
int value = (int)listView.getItemAtPosition(position);
Also, if you startActivity() before using the value anywhere, then it does not make much sense in getting it. Use putExtra to pass it to your next activity if you wish to use it there.
I want to use this line of code I've seen in several examples:
lvRadios.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = (Cursor) lvRadios.getItemAtPosition(position);
int idRadio = cursor.getInt(cursor.getColumnIndex("ID"));
Log.i("ID", String.valueOf(idRadio));
ShowResults(position, view);
}
});
But I get the following error:
java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor
I'm using Android 6.0 with Android Studio 2.1.2
I hope you can help me.
Regards.
Your error is telling you that you're trying to turn a string into a cursor. For the operation you're performing, you wouldn't get a cursor. You would get a UI element or something tied to a UI element.
Comment out what you already have inside of the onItemClick and replace it with:
String radioString = (String) lvRadios.getItemAtPosition(position);
//Debug: Show a toast to see what information you're getting
Toast.makeText(getApplicationContext(), radioString, Toast.LENGTH_LONG);
Then, you can do what you want once you know the result.
When I tried to pass a String extra over to the next activity, It works fine. When I try to pass a int like the following codes, it crashs and throws Resources$NotFoundException. I've been playing around it for few hours so I thought I can get some guidance with this.
This is the code from the activity that is passing the values with putExtra()
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent cP = new Intent("com.example.loldb.championscreen");
int x = arg2 + 1;
System.out.println(x);
cP.putExtra("champNo", x);
startActivity(cP);
}
and here's the code of the receiving activity trying to getIntExtra() the data
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_champion_screen);
Intent intent = getIntent();
TextView cName = (TextView) findViewById(R.id.cname);
int temp = intent.getIntExtra("champNo", 0);
//int champNo = Integer.parseInt(temp);
cName.setText(temp);
}
If possible I would like to get an explanation on this matter, so I can understand it a little more.
Thanks in advance.
Change to
cName.setText(String.valueOf(temp));
setText will take charactersequence. There is one that takes int value which is a resource. If not found you end up getting ResourceNotFoundException.
public final void setText (int resid)
Takes resid which is a int.
What you need
public final void setText (CharSequence text)
Added in API level 1
Sets the string value of the TextView. TextView does not accept HTML-like formatting, which you can do with text strings in XML resource files. To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.
Propose again my question. Sorry for the repetition.
I have a ListView where there are all the applications installed on the device. At the click on the item, part of the uninstall. So far everything works fine, the problem is that once the application is uninstalled, then it is no longer on the device, it remains in the list. Obviously this is not good and therefore I wrote this code to try to remove it once it has been uninstalled.
int position;
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
int requestCode = 1;
app = appInfoArrayList.get(position);
Uri packageUri = Uri.parse("package:"+app.packagename);
//In theory i should put
//this.position=position;
//But Eclipse says "position cannot be resolved or is not a field"
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageUri);
startActivityForResult(uninstallIntent, requestCode);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
String msg = "MyApp: ";
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
{
try {
packageInfo = getPackageManager().getApplicationInfo(app.packagename, 0);
}
catch (PackageManager.NameNotFoundException e) {
Log.v("Catch",msg );
appInfoArrayList.remove(position);
adapter.notifyDataSetChanged();
}
}
else {
}
Log.v(msg, String.valueOf(resultCode)+", "+String.valueOf(requestCode));
}
In the LogCat i read: MyApp: Catch 0 (resultCode) , 1 (requestCode) So this means that enters correctly in the catch, but despite this, even if the application has been uninstalled is still on the list. Ideas on how I can fix this? Thanks in advance.
Adapter declaration
AppAdapter adapter;
The position in appInfoArrayList.remove(position); is uninitialized make sure that you assign value to it.
You should redraw the list, call the adapter.notifyDataSetChanged() after renewing the adapter data source, this should solve the problem if you use the same ArrayList to store and to show the data
You are using this on exception
appInfoArrayList.remove(position);
adapter.notifyDataSetChanged();
This should get called correctly to reflect the changes , check the data