Listview and adapter for dummies - android

I seen through all previous question about this topic but cannot get my head around it.It is tested on a Samsung Galaxy S4. This is from my activity_main.xml.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/llListe"
android:orientation="vertical"
>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lstListe"
android:layout_gravity="center"
android:background="#bcffb9" />
</LinearLayout>
This is the MainActivity.java. I have tested the result from the speechRecognizer and it return the spoken word. The problem is to add this string to a ListView. I'm quit new at this so please forgive. WHAT AM I DOING WRONG?
public class MainActivity extends Activity implements View.OnClickListener {
protected static final int REQUEST_OK = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnSpeek).setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,"en-US");
try {
startActivityForResult(intent,REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Unable to initialize speech engine.", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ListView lv;
ArrayList<String> inputString = new ArrayList<String>();
ArrayAdapter<String> adapter;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
inputString = (data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS));
//Toast.makeText(this,"You said "+inputString.get(0), Toast.LENGTH_SHORT).show();
lv = (ListView) findViewById(R.id.lstListe);
adapter = new ArrayAdapter(this,R.id.lstListe,inputString);
lv.setAdapter(adapter);
}
}
}

I think you should put this line super.onActivityResult(requestCode, resultCode, data); in the else condition of the onActivityResult method, so that you're sure your code is executed when the request code is REQUEST_OK.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ListView lv;
ArrayList<String> inputString = new ArrayList<String>();
ArrayAdapter<String> adapter;
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
inputString = (data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS));
//Toast.makeText(this,"You said "+inputString.get(0), Toast.LENGTH_SHORT).show();
lv = (ListView) findViewById(R.id.lstListe);
adapter = new ArrayAdapter(this,R.id.lstListe,inputString);
lv.setAdapter(adapter);
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}

Related

In Multi Image Selector OnActivityResult() method is not getting called in Fragment

I am trying to make image selector for application.For that i am using multi-image-selector library which is perfeclty works when used in activity ,but here i want to use it in fragment.so in fragment OnActivityResult() method is not getting called.Can anyone help me to solve this?
Here's my code:
MainActivity.java:(My Main Activity)
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.frame, new Image_Selecter()).commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Utilz.printLog("Parentactivity", "onActivityResult");
Log.e("hererererer", "hererererer");
if (requestCode == REQUEST_IMAGE) {
new Image().onActivityResult(requestCode, resultCode, data);
}
}
}
Image:(My Fragment)
public class Image extends Fragment {
private ArrayList<String> mSelectPath;
private static final int REQUEST_IMAGE = 2;
ArrayList<Uri> mMedia = new ArrayList<Uri>();
Uri uri;
ImageView img;
protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_image, container, false);
img = (ImageView) view.findViewById(R.id.img);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickImage();
}
});
return view;
}
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getActivity());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getActivity(), REQUEST_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == getActivity().RESULT_OK) {
mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
mMedia.clear();
for (String p : mSelectPath) {
Uri uri = Uri.parse(p);
mMedia.add(uri);
}
uri = mMedia.get(0);
Log.e("uri", " " + uri);
if (!uri.toString().contains("content://")) {
uri = Uri.fromFile(new File(uri.toString()));
Log.e("in if", " uri = " + uri);
}
try {
Glide.with(this)
.load(uri)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(img);
} catch (Exception e) {
Log.e("Exceptionn", " " + e);
}
}
}
}
Try this in your activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Parentactivity", "onActivityResult");
if (requestCode == REQUEST_IMAGE) { //use request code as REQUEST_IMAGE while starting intent for camera
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);//calling fragments onActivityResult here
}
}
IIRC onActivityResult doesn't get called on a Fragment, it gets called on your parent Activity. You would need to catch this in the Activity and forward the result on to the fragment.
There are two methods which looks same but behaves little bit different.
If method is called by from activity, its not going to give callback to fragment unless called from fragment.
Activity.startActivityForResult()
Fragment.startActivityForResult()
Check out the library if there is way to calling it from fragment.
I dont know the library, just imaging if you can pass fragment to
MultiImageSelector selector = new MultiImageSelector(getActivity()); or selector.start(getActivity(), REQUEST_IMAGE);
Good luck
Emre
you have to call it with intent
public void pickImage() {
Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
startActivityForResult(intent, REQUEST_IMAGE);
}
if you were doing getActivity().startActivityForResult(intent, REQUEST_IMAGE);
the on OnActivityResult() will happen on activity instead of fragment. The way you are using it is like that, so you need to use the intent way.
also that maybe will make your code to work
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getContext());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getContext(), REQUEST_IMAGE);
}

Multiple Activities, launching and passing data

I am attempting to create a list of users in an android app. The list is on the MainActivity, with a button which redirects to AddMember. AddMember will take input for one member. I am trying to pass the information back to MainActivity, however it fails before I even get to the AddMemberActivity, when testing. It stops after the button click on the MainActivity.
Trie implementation
The error message is:
java.lang.NullPointerException: Attempt to invoke virtual method 'char java.lang.String.charAt(int)' on a null object reference
at attendance.Trie.get(Trie.java:117)
at attendance.Trie.get(Trie.java:113)
at attendance.MainActivity$1.onClick(MainActivity.java:49)
line 49 is
if (trie.get(name) != null) {
public class MainActivity extends AppCompatActivity {
private Button button;
private ListView list;
private Trie trie;
private ArrayAdapter<String> adapter;
private int count = 0;
private static final int REQUEST_CODE = 100;
private String name;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if(resultCode == RESULT_OK) {
name = data.getStringExtra("name");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.addBtn);
list = (ListView) findViewById(R.id.memberList);
trie = new Trie();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddMember.class);
startActivityForResult(intent, REQUEST_CODE);
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.content_list_items,R.id.list_content, trie.traverse());
list.setAdapter(adapter);
//check that member was added
if (trie.get(name) != null) {
// <- look for item!
//made an alert to show member already exists
} else {
trie.put(name.toLowerCase(), count++);
adapter.add(name);
}
adapter.notifyDataSetChanged();
}
});
}
}
public class AddMember extends AppCompatActivity {
//Array of options --> ArrayAdapter --> ListView
//ListView :{views, items.xml}
private static final int REQUEST_CODE = 100;
private Button button;
private EditText name;
private EditText phone;
private EditText email;
private ArrayAdapter<Member> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_member);
button = (Button) findViewById(R.id.uploadMember);
name = (EditText) findViewById(R.id.edit_name);
//add member button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("name", name.getText());
setResult(RESULT_OK, intent);
finish();
}
});
}
}
It is clear from crash log that you are attempting to get character from null string .
java.lang.String.charAt(int)' on a null object reference at attendance.Trie.get(Trie.java:117)
Reason : You are passing null value in get method. You never assign the name string and by default it is assigned with null. And you pass it with trie.get(name).
Check your get method of Trie class and put a check of null. If name is not null then get the character from string otherwise return null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if(resultCode == RESULT_OK) {
name = data.getStringExtra("name");
if(adapter == null){
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.content_list_items,R.id.list_content, trie.traverse());
list.setAdapter(adapter);
}
//check that member was added
if (trie.get(name) != null) {
// <- look for item!
//made an alert to show member already exists
} else {
trie.put(name.toLowerCase(), count++);
adapter.add(name);
}
adapter.notifyDataSetChanged();
}
}
}
Remove adapter code from onClick method
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddMember.class);
startActivityForResult(intent, REQUEST_CODE);
});

Android ArrayAdapter for ListView method .notifyDataSetChanged() issue

I am trying to update ListView after another activity finish()'es with result. Initialization (works correctly):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(this);
objects = databaseHelper.selectObjects();
objectsListView = (ListView) findViewById(R.id.LIST_VIEW_OBJECTS);
objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, objects);
objectsListView.setAdapter(objectArrayAdapter);
}
Problem occurs only when Im trying update ListView:
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == SECOND_ACTIVITY_REQUEST) {
if (resultCode == RESULT_OK) {
objects = databaseHelper.selectObjects();
objectArrayAdapter.notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.TOAST_ERROR_RESULT_CANCELED), Toast.LENGTH_LONG).show();
}
}
}
But this code works just fine:
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == SECOND_ACTIVITY_REQUEST) {
if (resultCode == RESULT_OK) {
objects.add(newObject);
objectArrayAdapter.notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.TOAST_ERROR_RESULT_CANCELED), Toast.LENGTH_LONG).show();
}
}
}
This code also works fine:
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == SECOND_ACTIVITY_REQUEST) {
if (resultCode == RESULT_OK) {
objects = databaseHelper.selectObjects();
objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, objects);
objectsListView.setAdapter(objectArrayAdapter);
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.TOAST_ERROR_RESULT_CANCELED), Toast.LENGTH_LONG).show();
}
}
}
My question is: why first method doesn't work as expected? Second and third seems to be a work round isn't it?
In your first example, you are giving the information to questionnaires variable, which I don't see being related to your listview. onNotifyDataSetChanged() has the same data as before from what I can tell.
The second one works because you are directly changing the objects variable which is connected to your adapter.
EDIT:
"For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter."
notifyDataSetChanged example

onActivityResult not being called in custom Fragment or anywhere else attempted

There have been many successful answers to this question, but there's still something I'm not understanding or that I'm doing incorrectly. One answer is implementing onActivityResult in the host Activity, but I guess I don't know which one that is or I'm following it wrong.
And no, I'm not calling getActivity.startActivityForResult(), just startActivityForResult().
Depending on a selection made in FirstActivity, one or more other selections are possible, created using Fragments. One Fragment is ButtonFragment, which when selected, starts OptionsActivity, like so:
public class ButtonFragment extends Fragment
{
.....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != Activity.RESULT_CANCELED)
{
if(requestCode == OPTIONS_REQUEST_CODE)
{
Bundle extras = data.getExtras();
if (extras != null) {
String selection = (String) extras.get("optionsSelection");
data.setText(selection);
}
}
}
}
private void openOptionsActivity()
{
Intent intent = new Intent(getActivity(), OptionsActivity.class);
intent.putExtra("optionsArray", options);
startActivityForResult(intent, OPTIONS_REQUEST_CODE);
}
}
This fragment is being added in BaseActivity:
public class BaseActivity extends FragmentActivity
{
.....
fm.beginTransaction().add(
R.id.FragmentContainer, frag).commitAllowingStateLoss();
fm.executePendingTransactions();
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
finish();
}
}
Inside OptionsActivity:
public class OptionsActivity extends BaseSpinnerActivity
{
.....
private class OptionsAdapter extends BaseSpinnerAdapter
{
public OptionsAdapter(Context context, Object[] values)
{
super(context, values);
}
protected void fillRow(ViewHolder holder, int position)
{
String option = options[position];
if(option != null) {
holder.text.setText(option);
}
}
protected void onRowSelect(View v)
{
Intent returnIntent = new Intent();
String optionSelection = (String)v.getTag();
returnIntent.putExtra("optionSelected", optionSelection);
setResult(RESULT_OK, returnIntent);
finish();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
finish();
}
}
The same thing is done inside BaseSpinnerActivity, which extends from ListActivity. (I know, should use FragmentActivity, but I haven't had a chance to convert it yet.)
None of these onActivityResult()'s are being called.
What am I missing or doing wrong? Any help is appreciated!

onActivityResult not getting string out of Intent

I need some help with my android app. I have two activities, first starts the second one with startActivityForResult(). When the second one closes it sends the intent as it should, however when i want to access extra from onActivityResult() i get a null instead of what I put in.
I also tried using bundle with
Bundle b = getIntent().getExtras();
b.getString(AddTable.EXTRA_NAME);
but it resulted in RuntimeException and failure delivering result.
Here's my code:
public class RunnerApp extends Activity {
private ListView listView;
private static ArrayList<String> values = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private Intent newTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_app);
listView = (ListView) findViewById(R.id.mylist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
public void addTable(View v){
newTable = new Intent(this, AddTable.class);
startActivityForResult(newTable, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null){
data = getIntent();
Log.d("add", "got intent");
String newName = data.getStringExtra(AddTable.EXTRA_NAME);
Log.d("add", "string " + newName); //always prints string null
values.add(newName);
Log.d("add", "added to list");
}
}
#Override
public void onResume(){
super.onResume();
setContentView(R.layout.activity_runner_app);
adapter.notifyDataSetChanged();
}
}
Second activity started by startActivityForResult()
public class AddTable extends Activity {
public final static String EXTRA_NAME = "com.example.runnerapp.NAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_table);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_add_table, menu);
return true;
}
public void addThisTable(View v) {
Intent addTable = new Intent(this, RunnerApp.class);
EditText editText = (EditText) findViewById(R.id.addTableField);
String name = editText.getText().toString();
addTable.putExtra(EXTRA_NAME, name);
Log.d("intenyt", name);
setResult(Activity.RESULT_OK, addTable);
this.finish();
}
}
In your first activity your code reads
data = getIntent();
But the actual data you want is in
data.getData()
use this in the onActivityResult function..
data.getStringExtra(EXTRA_NAME)

Categories

Resources