I have an activity with two variables
int cifracero
and
int cifrauno
I want to pass those variables to a fragment to be shown in some TextViews as the result of the multiplication made in the previous screen...like a "Congratulations, the multiplication was..."
I need to do something like a bundle to pass the variables as arguments of the second screen, in this case a fragment.
And then I have a third variable resultado which is the result of the multiplication of cifracero and cifrauno
This is the activity code
package com.example.aprendelastablasdemultiplicar;
import androidx.activity.ComponentActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.ListFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class quizingresar extends ComponentActivity {
private EditText cifracero;
private EditText cifrauno;
private TextView resultado;
private Button calcular;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizingresar);
cifracero = (EditText) findViewById(R.id.cifracero);
cifrauno = (EditText) findViewById(R.id.cifrauno);
resultado = (TextView) findViewById(R.id.resultado);
calcular = (Button)findViewById(R.id.calcular);
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int multiplicationResult = multiplicarValores();
resultado.setText(Integer.toString(multiplicationResult));
}
#Override
public void afterTextChanged(Editable s) {
}
};
cifracero.addTextChangedListener(textWatcher);
cifrauno.addTextChangedListener(textWatcher);
calcular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCongratulationsCalcular();
}
});
}
private int multiplicarValores() {
final String strnumber0 = cifracero.getText().toString();
final String strnumber1 = cifrauno.getText().toString();
int number0 = 0;
int number1 = 0;
try {
number0 = Integer.parseInt(strnumber0);
} catch (NumberFormatException e) {
}
try {
number1 = Integer.parseInt(strnumber1);
} catch (NumberFormatException e) {
}
return number0 * number1;
}
public void openCongratulationsCalcular(){
Intent intent = new Intent(this, congratulationscalcular.class);
startActivity(intent);
}
}
I need to recover the variables from the previous screen to be shown in the new fragment screen
You can have both of your fragments share the data between them by having them both under the same viewmodel, as shown here.
If you are going to be swapping screens, I think a very efficient solution would be to pass the desired data from one (screen) fragment to another using attributes in your Navigation Graph. Shown here.
Take a look at Data-Binding as well if you'd like, might be useful.
Intent intent = new Intent(this, DisplayMessageActivity.class);
String result = resultado.getText().toString();
intent.putExtra("EXTRA_MESSAGE", result);
startActivity(intent);
to get the message that was passed by the first activity
Intent intent = getIntent();
String message = intent.getStringExtra("EXTRA_MESSAGE");
i am trying to make an android app that searches the phones files and lists it under the search box as the user types in real time. please help in correcting the code, am getting a null pointer exception. all the resources are in place.
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
public class MainActivity extends ListActivity implements TextWatcher {
File[] myfiles;
FilenameFilter filter;
TextWatcher watcher;
String query;
static File file;
EditText eT;
ListView list;
ArrayList<String> myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = new ProgressBar(this);
progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
progressBar.setIndeterminate(true);
list.setEmptyView(progressBar);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(progressBar);
list = (ListView) findViewById(android.R.id.list);
File file = new File("Environment.getExternalStorageDirectory().getPath()");
myfiles = file.listFiles(filter);
Log.d("tag", "files passed");
eT = (EditText) findViewById(R.id.editText1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
query = ((EditText) s).getText().toString();
filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
String lcaseName = filename.toLowerCase();
if(lcaseName.contains(query)) {
return true;
}
else {
return false;
}
}
};
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList));
myList = new ArrayList<String>();
for(int i =0; i < myfiles.length; i++) {
myList.add(myfiles[i].getName());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
list.setEmptyView(progressBar);
// ...
list = (ListView) findViewById(android.R.id.list);
You're using list before it's initialized.
Debugging process pulled from question comment:
See the exception stacktrace in logcat.
Find the corresponding line in your code.
Figure out what could be the reason. Test your theory by fixing the code and testing again.
When posting questions about crashes in your code, always include information from steps 1 and 2.
variable list is not initialized. But after fixing this you will get NullPointerException again becouse you are using filter that is also null.
myfiles = file.listFiles(filter);
In my effort to get a simple address auto complete on android using geocoder, I tried to my patience and finally decided to ask out for help.
original code reference : Geocoder autocomplete in android
So in the below code, all that is happening is trying to auto complete the address as the user types in the autoCompleteTextView. I am calling the function doing the actual work in runOnUiThread,hoping that the UI would not freeze, as the user types in. However the UI freezes after the Threshold (3 characters) and the drop down of the possible addresses appear at it its own pace and not always.
If you guys can tell me where I am going wrong.... thanks in advance
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class AlarmActivity extends Activity implements TextWatcher {
private static final int THRESHOLD = 3;
private String latitude, longitude;
private List<Address> autoCompleteSuggestionAddresses;
private ArrayAdapter<String> autoCompleteAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.hw);
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
autoCompleteAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>());
autoCompleteAdapter.setNotifyOnChange(false);
AutoCompleteTextView locationinput = (AutoCompleteTextView) findViewById(R.id.locationInput);
locationinput.addTextChangedListener(this);
locationinput.setOnItemSelectedListener(this);
locationinput.setThreshold(THRESHOLD);
locationinput.setAdapter(autoCompleteAdapter);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
final String value = arg0.toString();
if (!"".equals(value) && value.length() >= THRESHOLD) {
Thread t = new Thread() {
public void run() {
try {
runOnUiThread(new Runnable() {
public void run() {
notifyResult(value);
}
});
} catch (Exception e) {}
}
};
t.start();
} else {
autoCompleteAdapter.clear();
}
}
#Override
public void afterTextChanged(Editable arg0) {
}
private void notifyResult(String value) {
try {
autoCompleteSuggestionAddresses = new Geocoder(getBaseContext()).getFromLocationName(value, 10);
//notifyResult(autoCompleteSuggestionAddresses);
latitude = longitude = null;
autoCompleteAdapter.clear();
for (Address a : autoCompleteSuggestionAddresses) {
Log.v("Nohsib", a.toString());
String temp = ""+ a.getFeatureName()+" "+a.getCountryName()+" "+a.getPostalCode();
autoCompleteAdapter.add(temp);
}
autoCompleteAdapter.notifyDataSetChanged();
} catch (IOException ex) {
// Log.e(GeoCoderAsyncTask.class.getName(), "Failed to get autocomplete suggestions", ex);
}
}
}
I believe the reason the UI is freezing is because even though you are calling notifyResult from a separate thread, it is still being run on the UI thread. What will fix this is to instead use an AsyncTask
Something like:
private class GetSuggestions extends AsyncTask<String, Void, Void> {
protected Long doInBackground(String... search) {
value = search[0];
try {
autoCompleteSuggestionAddresses = new Geocoder(getBaseContext()).getFromLocationName(value, 10);
//notifyResult(autoCompleteSuggestionAddresses);
latitude = longitude = null;
autoCompleteAdapter.clear();
for (Address a : autoCompleteSuggestionAddresses) {
Log.v("Nohsib", a.toString());
String temp = ""+ a.getFeatureName()+" "+a.getCountryName()+" "+a.getPostalCode();
autoCompleteAdapter.add(temp);
}
} catch (IOException ex) {
// Log.e(GeoCoderAsyncTask.class.getName(), "Failed to get autocomplete suggestions", ex);
}
}
protected void onPostExecute(Long result) {
autoCompleteAdapter.notifyDataSetChanged();
}
}
and then you can start the task by calling new GetSuggestions().execute(value);
I want to search through the list and display the result in the list again
so I used addtextchangelistener, but can't find a way to make it work with listview with subtext
Here's my code:
package com.android;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MyListDemoActivity extends ListActivity {
/** Called when the activity is first created. */
TextView tv;
//** List<String> content;
EditText actv;
List<String> arr_sort;
//** ArrayAdapter<String> adapter;
SimpleAdapter simpleadapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String line = " ";
LineNumberReader linenoreader = null;
StringTokenizer stringtokanixer = null;
//** content = new ArrayList<String>();
List<Map<String,String>> data= new ArrayList<Map<String,String>>();
lv = (ListView) findViewById(android.R.id.list);
try {
InputStream istream = getResources().openRawResource(R.raw.grelist);
InputStreamReader streamreader = new InputStreamReader(istream);
linenoreader = new LineNumberReader(streamreader);
linenoreader.mark(15);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}// try catch ends here
Log.v("getting", "working");
for(int i=0;i<8;i++)
{
Map<String,String> datum= new HashMap<String,String>(2);
try {
line = linenoreader.readLine();
Log.v("item",line);
} catch (IOException e) {
e.printStackTrace();
}
Log.v("getting", line);
stringtokanixer = new StringTokenizer(line);
String st = stringtokanixer.nextToken();
String meaning="";
while (stringtokanixer.hasMoreTokens()) {
meaning +=" " +stringtokanixer.nextToken();
}// for ends
// map is used to add word and meaning
datum.put("word",st);
datum.put("meaning",meaning);
data.add(datum);
//List<String> is usedto add
//** content.add(st);
}
simpleadapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[]{"word","meaning"}, new int[]{android.R.id.text1,android.R.id.text2});
// setListAdapter(adapter);
lv.setAdapter(simpleadapter);
tv = (TextView) findViewById(R.id.textView1);
actv = (EditText) findViewById(R.id.editText1);
/*
actv.addTextChangedListener(new TextWatcher() {
int len = 0;
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
arr_sort = new ArrayList<String>();
len = actv.getText().length();
for (int i = 0; i < content.size(); i++) {
if (len <= content.get(i).length()) {
if (actv.getText()
.toString()
.trim()
.equalsIgnoreCase(
(String) content.get(i).subSequence(0,
len))) {
arr_sort.add(content.get(i));
Log.v("infor loop afterTextChanged", s.toString());
}
}
}
// adapter.notifyDataSetChanged();
adapter = new ArrayAdapter<String>(MyListDemoActivity.this,
android.R.layout.simple_list_item_1, arr_sort);
setListAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
Log.v("beforetextchange","hello here");
}
#Override
public void afterTextChanged(Editable s) {
Log.v("aftertextchange","hello here");
}
}); // text watcher class ends here
*/
}// on create ends here
public void onListItemClick(ListView ls, View v, int position, long id) {
//tv.setText(content.get(position));
// tv.setText(content[position]) // in case of string
}// endsd here onListItemClick(
}
I have answered already in two of the StackOverflow questions itself you can them,
First is using getFilter() that android provides for Filtering using Filterable interface to the Adapter class. You can check it from here.
Second is using an external jar Lambdaj which is the best and efficient way of filtering a huge data from a List. You can check that also from here.
What I understood is:- Simply you want to filter the ListView. Right?
Let me know If I've misunderstood the question!!!
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<EditText android:id="#+id/search" android:layout_width="fill_parent" android:layout_height="wrap_content"
android:inputType="text" />
<ListView android:id="#+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" />
</LinearLayout>
ListViewSearchActivity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListViewSearchActivity extends Activity implements TextWatcher {
private SimpleAdapter simpleAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText search = (EditText) findViewById(R.id.search);
search.addTextChangedListener(this);
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for(int i=0;i<8;i++) {
Map<String,String> map = new HashMap<String, String>(2);
map.put("word", "word " + i);
map.put("meaning", "meaning " + (i + 10));
data.add(map);
}
ListView listView = (ListView) findViewById(R.id.list);
this.simpleAdapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[]{"word","meaning"}, new int[]{android.R.id.text1,android.R.id.text2});
listView.setAdapter(this.simpleAdapter);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
this.simpleAdapter.getFilter().filter(s.toString());
}
}
Here is how I'd change your code to make it work:
1. I would remove the arr_sort variable, and add an other ArrayList of Maps for holding the filtered values:
// List<String> arr_sort;
final ArrayList<Map<String, String>> data =
new ArrayList<Map<String, String>>();
final ArrayList<Map<String, String>> filteredData =
new ArrayList<Map<String, String>>();
I'd also make them final, since there is no point to assign completely new values to them while we can modify their content.
2. The simpleadapter should always display the filtered data, so it has to be modified:
filteredData.addAll(data); // fill up filteredData initially with the whole list
simpleadapter = new SimpleAdapter(this, filteredData,
android.R.layout.simple_list_item_2,
new String[] { "word", "meaning" },
new int[] {android.R.id.text1, android.R.id.text2 });
3. Next I'd move the filtering code from the onTextChanged method to the afterTextChanged method, to perform the filtering based on the whole text entered. Using Regexp is also less resource consuming than all the String manipulations (+ , substring...)
This way your TextWatcher implementation would look like:
actv.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{}
#Override
public void beforeTextChanged(CharSequence s,int start,int count,int after)
{}
#Override
public void afterTextChanged(Editable s)
{
Log.v("MLDA", "afterTextChanged");
// a temporary source list for better performance:
// if it's possible, use the smaller filtered list
final ArrayList<Map<String, String>> tmpSource =
new ArrayList<Map<String,String>>();
tmpSource.addAll(
(filterText.length() > 0 && s.toString().contains(filterText))
? filteredData : data);
filterText = s.toString();
// a temporary result list to fill with the filtered data
final ArrayList<Map<String, String>> tmpResult =
new ArrayList<Map<String,String>>();
if (filterText.length() == 0)
tmpResult.addAll(data); //if no filter, return the base data
else
{
final Pattern pattern =
Pattern.compile("(?i)" + Pattern.quote(s.toString()));
Matcher matcher;
for (final Map<String, String> map : tmpSource)
{
//first match against the "word":
matcher = pattern.matcher(map.get("word"));
if (!matcher.find())
{
//if no matches were found, try to match the "meaning"
matcher = pattern.matcher(map.get("meaning"));
if (!matcher.find())
continue; //if no match, move to the next map
}
tmpResult.add(map); //match found: add to new list
}
}
filteredData.clear();
filteredData.addAll(tmpResult);
simpleadapter.notifyDataSetChanged(); // update display
}
});
Working with temporary lists lets you build up the whole filtered data without gui updates (if removing / adding items to the filteredData list directly, the adapter would trigger update methods).
Also notice, that by examining whether the new filter text contains the old one, we can use the current filteredData list as source.
Similarly, if the filterText is an empty string, there's no point to perform any matches, we can simply return the base list.
ArrayList<String> tempList ;
edtText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (!edtText.getText().toString().equalsIgnoreCase("")){
tempList = new ArrayList<String>();
tempList.clear();
String text = filterText.getText().toString();
for(int i=0 ;i< listname.size();i++){
//if(globalconstant.mosq_list.get(globalconstant.hashformosq.get(globalconstant.tempList.get(i))).name.toUpperCase().toString().contains(text.toUpperCase())){
if(listname.get(i).toUpperCase().toString().contains(text.toUpperCase())){
tempList.add(listname.get(i));
}
}
used changed tempList
}else{
unchaged tempList
}
}
});
}
package com.aviyehuda.test.multithreading;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MultithreadingTest extends Activity {
Button btn;
private Handler myHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.Button01);
}
public void buttonClicked(View v) {
myHandler = new Handler();
MyThread mThread = new MyThread();
mThread.start();
}
class MyThread extends Thread {
#Override
public void run() {
for (int i = 0; i < 30; i++) {
myHandler.post(new NewThreaad(i));
}
}
}
class NewThreaad implements Runnable{
int i;
public NewThreaad(int n) {
i=n;
}
#Override
public void run() {
((TextView) findViewById(R.id.TextView01)).setText("Hello:"+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I have code mentioned above but getting result Hello29 on TextView but i want Hello1,Hello2,hello3.................Hello29 one by one automatically
Please give me hint what I am doing wrong
A couple of things.
First, after changing the text, you should call invalidate on the TextView to force a refresh.
Second, to do operation on the UI, you should run that in the UI thread. Use runOnUiThread
Well, the main problem is that you're not appending you are overwriting. Instead of
((TextView) findViewById(R.id.TextView01)).setText("Hello:"+i);
do
TextView tv = ((TextView) findViewById(R.id.TextView01));
String text = tv.getText().toString();
tv.setText(text + " Hello:" + i);
You need to move the 500 ms delay to your for-loop, between posting of messages. I think you're expecting the messages to execute sequentially one after the other, but they don't, which is the reason you just see the result of the last one.