String[] urls won't update correctly - java

For my class we have to create an application where we catch an SMS message in a broadcast receiver, get the string (assumed to be a URL), add it dynamically to a string-array which is displayed in a fragmentlist. When the list item is clicked we then have to load it into a webview in a fragment.
Everything works until here.
The problem is that the list doesn't update when I try to add the url_act string to it.
Here's my code:
public class UpdateString extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url_act = "";
Bundle b = getIntent().getExtras();
url_act = b.getString("url");
UrlListFragment uf = (UrlListFragment) getFragmentManager()
.findFragmentById(R.id.listFragment);
String[] urls = getResources().getStringArray(R.array.urls_array);
List<String> list = new ArrayList<String>();
list = Arrays.asList(urls);
ArrayList<String> arrayList = new ArrayList<String>(list);
arrayList.add(url_act);
urls = arrayList.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(UpdateString.this,
android.R.layout.simple_list_item_1, urls);
uf.setListAdapter(adapter);
}
If you need more code for context let me know. Updated

You really should post your logcat output just to be sure, as otherwise we don't know what kind of exception was thrown.
That being said, I bet it is a NullPointerException; findFragmentById() is most likely returning null. This is probably because you never inflate your XML resource to begin with.

Related

How to send an Array list to another activity

I want to send a string array list from my MainActivity to Creating activity via using intent. but it gives me some error
I am dealing with it for some time-_-.
This arraylist is for adding some words. I tried putextra(); and putStringArrayListExtra();
MainActivity
Intent intent = new Intent(getApplicationContext(),creating.class);
intent.putStringArrayListExtra("w",Words);
intent.putStringArrayListExtra("m", Meanings);
startActivityForResult(intent,REQUEST_CODE);
CreatingActivity
private ArrayList<String> Words1;
private ArrayList<String> Meanings1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creating);
Words1 = new ArrayList<String>();
Meanings1 = new ArrayList<String>();
Words1 = intent1.getStringArrayListExtra("w");
Meanings1 = intent1.getStringArrayListExtra("m");
when I click the button to come to this activity, this error appears:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.content.Intent.getStringArrayListExtra(java.lang.String)' on a null object reference
I thing You are missing something it should be like:
Words1 = getIntent().getStringArrayListExtra("w");
Meanings1 = getIntent().getStringArrayListExtra("m");
Right?
And if still you are facing issue try to debug because i think your way is correct.

How to open a file the same name as defined in the String?

I'm creating a lyric app and I need some help in coding the next processes I need.
I created a ListView and added some Strings on it.
public class MainActivity extends AppCompatActivity {
String titles[] = new String [] {"Amazing Grace", "How Great Thou Art",
"King of All Kings", "What A Beautiful Name"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView =(ListView) findViewById(R.id.titlelist);
ArrayAdapter<String> adapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,titles);
listView.setAdapter(adapter);
}
}
Now the next step is to create an OnItemClickListener and let's say
if "Amazing Grace" was selected from the list,
it will look for a file the same name as it is defined in the String.
For example : "Amazing Grace.xml" //even with the space included
so the logic will be like : open filelocation/"title that was selected".xml
I can't use "case" since I will be creating lots of song titles and add more as I update the app.
Thanks for reading, I'd really appreciate any help with this ;)
You should map Your lyrics, so when You click on item with pos = 5 You will know what item's ps correlates with what file(or xml).
Here is the sample how to map ids with filenames:
HashMap<String,Strin> lyricsMap = new HashMap<>();
lyricsMap(0, R.raw.song_lyric0);
lyricsMap(1, R.raw.song_lyric1);
lyricsMap(2, R.raw.song_lyric2);
lyricsMap(3, R.raw.song_lyric3);
lyricsMap(4, R.raw.song_lyric4);
lyricsMap(5, R.raw.song_lyric5);
lyricsMap(6, R.raw.song_lyric6);
//..
Here is the sample how to use OnItemClickListener:
AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
int rawResId = lyricsMap.get(pos);
//here comes the method for returning lyrics for file by it's resource id
//...
}
};
adapter.setOnItemClickListener(onItemClickListener);
P.S I assume You are not working on database items, otherwise You should use id instead of pos value.
To open file:
int selected = 0; // set selected to index of what is selected
File file = new File(Environment.getExternalStorageDirectory(), //folder location where you store the files
titles[selected]+".xml"); //in case of xml files. If other types, you'll need to add case for diff types
Uri path = Uri.fromFile(file);
Intent fileOpenintent = new Intent(Intent.ACTION_VIEW);
fileOpenintent .setDataAndType(path, "application/xml"); //for xml MIME types are text/xml and application/xml
try {
startActivity(fileOpenintent);
}
catch (ActivityNotFoundException e) {
}
Your biggest issue as you explained it was how to handle multiple file names. That's this part of code: titles[selected]+".xml"

How to create dynamic Multidimensional ArrayList?

I'm creating an Android App, and in order to make it work I need to create a Multidimensional ArrayList (2D) dynamically:
I am leaving you the code, in order to make you understand how it's been ordered and so you'll be able to clear it up to add this feature (possibly I'd like not just to have the pieace of code itself, but rather to have an almost detailed explanation of what's in there, I'll appreciate that really!
Anyway I'll also leave you some pictures to look at to focus a little bit more on the project, thank you in advance as always guys!
Java code:
public class MainActivity extends ActionBarActivity {
ArrayList<String> arrayNames = new ArrayList<String>();
ListView listNames;
TextView namesText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating and Printing Lists
listNames = (ListView) findViewById(R.id.listNamesId);
namesText = (TextView) findViewById(R.id.namesTexter);
final ArrayAdapter<String> adapterNames = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, arrayNames);
listNames.setAdapter(adapterNames);
Button buttonPlus = (Button)findViewById(R.id.buttonPlus);
buttonPlus.setOnClickListener(
new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (namesText.getText().toString().isEmpty()){
Context context = getApplicationContext();
CharSequence text = "You cannot add an empty Item!";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
}else if(namesText.getText().toString().trim().isEmpty()){
Context context = getApplicationContext();
CharSequence text = "You cannot add an Item with spaces only!";
int duration = Toast.LENGTH_SHORT;
namesText.setText("");
Toast.makeText(context, text, duration).show();
} else if(namesText.getText().toString() != null && !namesText.getText().toString().isEmpty()) {
arrayNames.add(0, namesText.getText().toString());
adapterNames.notifyDataSetChanged();
namesText.setText("");
}
}
}
);
}
Imgur mages to explain the project:
http://imgur.com/a/aJYoe
You can use ArrayList of ArrayLists.
ArrayList<ArrayList<String>> multiDimensionalArrayList = new ArrayList<ArrayList<String>>();
multiDimensionalArrayList.add(new ArrayList<>());
multiDimensionalArrayList.get(0).add("...");
ArrayLists are always dynamic in Java. If you want to instantiate it at run time, instantiate inside of a nonstatic (dynamic) method. Maybe you should rephrase your question to clarify, as it seems that what you are asking doesn't make a lot of sense.

Google Glass Voice Recognition

What I tried to do:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> voiceResults = getIntent().getExtras()
.getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
Card ShowDataCard = new Card(this);
ShowDataCard.setText(voiceResults);
View ShowDataCardView = ShowDataCard.toView();
setContentView(ShowDataCardView);
}
Failed work-around:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String voiceResults = getIntent().getExtras()
.getString(RecognizerIntent.EXTRA_RESULTS);
Card ShowDataCard = new Card(this);
ShowDataCard.setText(voiceResults);
View ShowDataCardView = ShowDataCard.toView();
setContentView(ShowDataCardView);
}
The String voiceResults is a failed workaround to the fact I cannot .setText to an arraylist string
Actual voice recognition code:
ArrayList<String> voiceResults = getIntent().getExtras()
.getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
Basically I am trying to save this voice recognition (going to use SharedPreferences) but for some reason it is an arraylist string and not just a string. Anybody know how to save it as a String? (or publish an activity with an arraylist string)
Since the results are an ArrayList of strings, you should check that the size() of the list is at least 1 and then call voiceResults.get(0) to get the string.

Android ListView not updating after a call to notifyDataSetChanged

I have an Activity which I start like this:
public class MyProblemsActivity extends ListActivity
{
String[] PROBLEMS = new String[] {"One", "Two", "Three" };
ArrayAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
adapter = new ArrayAdapter<String>(this,R.layout.my_problems, PROBLEMS);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
and that works totally fine.
The problem I run into is after a call to a remote server via a Asynch call, I do this:
#Override
protected void onPostExecute(String result)
{
PROBLEMS = new String[] {"Hello", "Bye", "Hmmmmmm" };
adapter.notifyDataSetChanged();
}
But the screen does not update. What am I doing wrong here and how can I get the screen to update with the new values?
Thanks!!
what's happening is at
PROBLEMS = new String[] {"Hello", "Bye", "Hmmmmmm" };
the PROBLEMS is getting the reference to new string array object...Thus the old reference is remaining as it is(unchanged)..
to correct it, use following :
PROBLEMS.clear();
List<String> newlist = new ArrayList<String>();
newlist.add(..);
..
PROBLEMS.addAll(newlist);
adapter.notifyDataSetChanged();
this way new string(s) will be added only to existing array reference pointed out by PROBLEMS
NOTE: i have mentioned by referencing the use of arraylist of string instead of string[] , to use clear(),addAll() functionalites of it, you can modify it for String[] as per your use..
If you want a simpler answer, you can just change your code to look like this:
#Override
protected void onPostExecute(String result)
{
PROBLEMS = new String[] {"Hello", "Bye", "Hmmmmmm" };
adapter.clear();
adapter.addAll(PROBLEMS);
adapter.notifyDataSetChanged();
}
This changes the ArrayAdapter's contents to have the Strings in your new String[], then notifies the ListView that the ArrayAdapter has new contents. This will cause the ListView to update and show your new Strings.
I read that you updated the list from an asynchronous callback. Same was my case. I went to run that in UI Thread and suddenly it worked as expected! (Usually you get an exception if you don't do that. Here it just doesn't do refresh the list.) For my opinion, the other answers are just work arounds.
So, alter your code like this:
#Override
protected void onPostExecute(String result)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
PROBLEMS = new String[] {"Hello", "Bye", "Hmmmmmm" };
adapter.notifyDataSetChanged();
}
});
};

Categories

Resources