AsyncTask in Android (pass ArrayList<Integer>) - android-asynctask

I have a
ArrayList<Integer>
and i want to pass it to
AsyncTask<ArrayList<Integer>, void, void>.
But in
doInBackground(ArrayList<Integer>...params) function,
i can't receive arrayList, which i passed.
Inside doInBackground i use ArrayList<Integer> arr = params[0] then i log(arr.size()) is 0
My code:
class count extends AsyncTask<Void, Integer, ArrayList<Integer>>{
ArrayList<Integer> arr = new ArrayList<Integer>();
ArrayList<Integer> temp = new ArrayList<Integer>();
#SuppressWarnings("unchecked")
#Override
protected ArrayList<Integer> doInBackground(Void... params) {
// TODO Auto-generated method stub
for(int i = 1; i <= 100; i++){
SystemClock.sleep(200);
arr.add(i);
if(i % 10 == 0){
temp = arr;
//Log.d("DEBUG", "Length of temp = "+ temp.size());
arr.clear();
mean task1 = new mean();
task1.execute(temp);
}
publishProgress(i);
}
return arr;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
tvNum.setText(values[0]+"");
}
}
class mean extends AsyncTask<ArrayList<Integer>, Integer, ArrayList<Integer>>{
#Override
protected ArrayList<Integer> doInBackground(
ArrayList<Integer>... params) {
// TODO Auto-generated method stub
ArrayList<Integer> arrL =new ArrayList<Integer>();
arrL= params[0];
Log.d("DEBUG","iNPUT Size = " + arrL.size());
return null;
}
}
Please help me,
Thanks.

If you pass the Arraylist in as the only parameter when you're calling execute(), it should be in params[0]. For example,
YourTask.execute(YourList);
And you would access it inside of the ASyncTask as so:
Arraylist<Integer> myList = params[0];

Easy Example for your understanding. such as
public class MainActivity extends Activity {
List<CalcPrimesTask> taskList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskList = new ArrayList<CalcPrimesTask>();
}
public void onClickStart(View view) {
EditText maximumEditText = (EditText) findViewById(R.id.maximumEditText);
int maxNum = Integer.parseInt(maximumEditText.getText().toString());
CalcPrimesTask task = new CalcPrimesTask(this);
taskList.add(task);
task.execute(maxNum);
Toast.makeText(getApplicationContext(), "New run queued.", Toast.LENGTH_SHORT).show();
}
public void onStopClick(View view) {
for (CalcPrimesTask task : taskList) {
task.cancel(true);
}
Toast.makeText(getApplicationContext(), "All runs cancelled.", Toast.LENGTH_SHORT).show();
}
}
and
public class CalcPrimesTask extends AsyncTask<Integer, String, List<Integer>> {
Activity activity;
public CalcPrimesTask(Activity mainActivity) {
activity = mainActivity;
}
#Override
protected List<Integer> doInBackground(Integer... params) {
int maxNum = params[0];
List<Integer> primeList = new ArrayList<Integer>();
for (int i = 2; i <= maxNum ; i++) {
int maxCalc = (int)Math.sqrt(i);
boolean isPrime = true;
for (int j = 2; j <= maxCalc ; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeList.add(i);
publishProgress("Prime " + i + " found.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
return primeList;
}
#Override
protected void onProgressUpdate(String... values) {
TextView messageView = (TextView) activity.findViewById(R.id.messageText);
messageView.setText(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(List<Integer> result) {
TextView messageView = (TextView) activity.findViewById(R.id.messageText);
messageView.setText("Total of " + result.size() + " primes found.");
super.onPostExecute(result);
}
}
If your hand available time then read Android AsyncTask. Best of Luck!

Related

Geocoder freez application for 3 or 4 seconds when try to search by place name

i create app for location base data i'm using geocoder to fetch places data but its hang for 3 or 4 seconds but after loads data correctly
its android studio java based for getting city name or district from geocoder
after freez its gets results correctly
public void getLocation(String type) {
List<String> items = new ArrayList<>();
Dialog dialog = new Dialog(buyersetting.this, android.R.style.Theme_Light);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.location_dialog);
dialog.show();
ListView listView = (ListView) dialog.findViewById(R.id.listview);
EditText etsearch = dialog.findViewById(R.id.searcchloc);
etsearch.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
Geocoder geocoder = new Geocoder(buyersetting.this, Locale.getDefault());
try {
List<Address> result = geocoder.getFromLocationName(s.toString(), 10);
if ((result == null) || (result.isEmpty())) {
} else {
items.clear();
for (int i = 0; i < result.size(); i++) {
items.add(result.get(i).getLocality());
}
MyArrayAdapter adapter = new MyArrayAdapter(buyersetting.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (type == "city")
bind.city.setText(parent.getItemAtPosition(position).toString());
if (type == "dist") {
bind.dist.setText(parent.getItemAtPosition(position).toString());
}
dialog.dismiss();
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
dialog.show();
}

Spring Error while using filter and wrapper

I'm using the filter to check user rights.
Problem in comparing session value to param value is occurred and resolution load is applied using wrapper.
However, the following error message came out.
List<Map<String,Object>> loginInfo = (List<Map<String,Object>>)session.getAttribute("loginSession");
if loginInfo.get(0).get("user_type").equals("1") || loginInfo.get(0).get("user_type").equals("2"))
{
chain.doFilter(req, res);
}
else
{
RereadableRequestWrapper wrapperRequest = new RereadableRequestWrapper(request);
String requestBody= IOUtils.toString(wrapperRequest.getInputStream(), "UTF-8");
Enumeration<String> reqeustNames = request.getParameterNames();
if(requestBody == null) {
}
Map<String,Object> param_map = new ObjectMapper().readValue(requestBody, HashMap.class);
String userId_param = String.valueOf(param_map.get("customer_id"));
System.out.println(userId_param);
if( userId_param == null || userId_param.isEmpty()) {
logger.debug("error, customer_id error");
}
if (!loginInfo.get(0).get("customer_id").equals(userId_param))
{
logger.debug("error, customer_id error");
}
chain.doFilter(wrapperRequest, res);
}
/////////////////////////
here is my wrapper Code.
private boolean parametersParsed = false;
private final Charset encoding;
private final byte[] rawData;
private final Map<String, ArrayList<String>> parameters = new LinkedHashMap<String, ArrayList<String>>();
ByteChunk tmpName = new ByteChunk();
ByteChunk tmpValue = new ByteChunk();
private class ByteChunk {
private byte[] buff;
private int start = 0;
private int end;
public void setByteChunk(byte[] b, int off, int len) {
buff = b;
start = off;
end = start + len;
}
public byte[] getBytes() {
return buff;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public void recycle() {
buff = null;
start = 0;
end = 0;
}
}
public RereadableRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
String characterEncoding = request.getCharacterEncoding();
if (StringUtils.isBlank(characterEncoding)) {
characterEncoding = StandardCharsets.UTF_8.name();
}
this.encoding = Charset.forName(characterEncoding);
// Convert InputStream data to byte array and store it to this wrapper instance.
try {
InputStream inputStream = request.getInputStream();
this.rawData = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
throw e;
}
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.rawData);
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
#Override
public boolean isFinished() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
#Override
public void setReadListener(ReadListener listener) {
// TODO Auto-generated method stub
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream(), this.encoding));
}
#Override
public ServletRequest getRequest() {
return super.getRequest();
}
#Override
public String getParameter(String name) {
if (!parametersParsed) {
parseParameters();
}
ArrayList<String> values = this.parameters.get(name);
if (values == null || values.size() == 0)
return null;
return values.get(0);
}
public HashMap<String, String[]> getParameters() {
if (!parametersParsed) {
parseParameters();
}
HashMap<String, String[]> map = new HashMap<String, String[]>(this.parameters.size() * 2);
for (String name : this.parameters.keySet()) {
ArrayList<String> values = this.parameters.get(name);
map.put(name, values.toArray(new String[values.size()]));
}
return map;
}
#SuppressWarnings("rawtypes")
#Override
public Map getParameterMap() {
return getParameters();
}
#SuppressWarnings("rawtypes")
#Override
public Enumeration getParameterNames() {
return new Enumeration<String>() {
#SuppressWarnings("unchecked")
private String[] arr = (String[])(getParameterMap().keySet().toArray(new String[0]));
private int index = 0;
#Override
public boolean hasMoreElements() {
return index < arr.length;
}
#Override
public String nextElement() {
return arr[index++];
}
};
}
#Override
public String[] getParameterValues(String name) {
if (!parametersParsed) {
parseParameters();
}
ArrayList<String> values = this.parameters.get(name);
String[] arr = values.toArray(new String[values.size()]);
if (arr == null) {
return null;
}
return arr;
}
private void parseParameters() {
parametersParsed = true;
if (!("application/x-www-form-urlencoded".equalsIgnoreCase(super.getContentType()))) {
return;
}
int pos = 0;
int end = this.rawData.length;
while (pos < end) {
int nameStart = pos;
int nameEnd = -1;
int valueStart = -1;
int valueEnd = -1;
boolean parsingName = true;
boolean decodeName = false;
boolean decodeValue = false;
boolean parameterComplete = false;
do {
switch (this.rawData[pos]) {
case '=':
if (parsingName) {
// Name finished. Value starts from next character
nameEnd = pos;
parsingName = false;
valueStart = ++pos;
} else {
// Equals character in value
pos++;
}
break;
case '&':
if (parsingName) {
// Name finished. No value.
nameEnd = pos;
} else {
// Value finished
valueEnd = pos;
}
parameterComplete = true;
pos++;
break;
case '%':
case '+':
// Decoding required
if (parsingName) {
decodeName = true;
} else {
decodeValue = true;
}
pos++;
break;
default:
pos++;
break;
}
} while (!parameterComplete && pos < end);
if (pos == end) {
if (nameEnd == -1) {
nameEnd = pos;
} else if (valueStart > -1 && valueEnd == -1) {
valueEnd = pos;
}
}
if (nameEnd <= nameStart) {
continue;
// ignore invalid chunk
}
tmpName.setByteChunk(this.rawData, nameStart, nameEnd - nameStart);
if (valueStart >= 0) {
tmpValue.setByteChunk(this.rawData, valueStart, valueEnd - valueStart);
} else {
tmpValue.setByteChunk(this.rawData, 0, 0);
}
try {
String name;
String value;
if (decodeName) {
name = new String(URLCodec.decodeUrl(Arrays.copyOfRange(tmpName.getBytes(), tmpName.getStart(), tmpName.getEnd())), this.encoding);
} else {
name = new String(tmpName.getBytes(), tmpName.getStart(), tmpName.getEnd() - tmpName.getStart(), this.encoding);
}
if (valueStart >= 0) {
if (decodeValue) {
value = new String(URLCodec.decodeUrl(Arrays.copyOfRange(tmpValue.getBytes(), tmpValue.getStart(), tmpValue.getEnd())), this.encoding);
} else {
value = new String(tmpValue.getBytes(), tmpValue.getStart(), tmpValue.getEnd() - tmpValue.getStart(), this.encoding);
}
} else {
value = "";
}
if (StringUtils.isNotBlank(name)) {
ArrayList<String> values = this.parameters.get(name);
if (values == null) {
values = new ArrayList<String>(1);
this.parameters.put(name, values);
}
if (StringUtils.isNotBlank(value)) {
values.add(value);
}
}
} catch (DecoderException e) {
// ignore invalid chunk
}
tmpName.recycle();
tmpValue.recycle();
}
}
and Error Message is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
I Don't know why this problem happened...

Recycler View with Header and Edit Text

I have a recyclerview with a header achieved by using two different element types. In my header there is an edit text which I want to use for filtering the nonheader elements of the list. Below is my current implementation, I have one concern and one problem with it.
My concern is that what I am doing in publishResults with the notifyItemRangeRemoved and notifyItemInserted is the wrong way to update the recycler view. I originally was doing notifyDatasetChanged but his would cause the header row to be refreshed too and the edit text to lose focus. What I really want is a way to refresh only the item rows and leave the header row untouched.
My current problem is that with the existing code if I scroll down too much the edit text looses focus. I want the edit text to keep focus even if I scroll to the bottom of the list.
The code used to use a ListView with setHeaderView and that worked somehow so there must be someway of achieving the goal just not sure what the trick with a recycler view is. Any help is much appreciated.
public class SideListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private final List<String> data;
public List<String> filteredData;
private HeaderActionListener headerActionListener;
public SideListAdapter(Context context, ArrayList<String> data, HeaderActionListener headerActionListener) {
this.data = data;
filteredData = new ArrayList<>(data);
this.context = context;
this.headerActionListener = headerActionListener;
}
#Override
public Filter getFilter() {
return new TestFilter();
}
static class SideListItem extends RecyclerView.ViewHolder {
LinearLayout baseLayout;
public SideListItem(View itemView) {
super(itemView);
baseLayout = (LinearLayout) itemView.findViewById(R.id.settings_defaultcolor);
}
}
class SideListHeader extends SideListHeader {
EditText sort;
public SideListHeaderLoggedIn(View itemView) {
super(itemView);
sort = (EditText) itemView.findViewById(R.id.sort);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new SideListItem(v);
} else if (viewType == SideListHeader) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
return new SideListHeader(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
public interface HeaderActionListener {
boolean onSortEditorAction(TextView arg0, int arg1, KeyEvent arg2);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof SideListHeader) {
final SideListHeader sideListHeader = (SideListHeader) holder;
sideListHeader.sort.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
}
});
sideListHeader.sort.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void afterTextChanged(Editable editable) {
String result = sideListHeader.sort.getText().toString().replaceAll(" ", "");
getFilter().filter(result);
}
});
}
if (holder instanceof SideListItem) {
// Inflate normal item //
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
}
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
//increasing getItemcount to 1. This will be the row of header.
#Override
public int getItemCount() {
return filteredData.size() + 1;
}
private class TestFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix.isEmpty()) {
ArrayList<String> list = new ArrayList<>(data);
results.values = list;
results.count = list.size();
} else {
final ArrayList<String> list = new ArrayList<>(data);
final ArrayList<String> nlist = new ArrayList<>();
for (int i = 0 ; i < list.size(); i++) {
String item = list.get(i);
if (item.contains(prefix)) {
nlist.add(item);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
notifyItemRangeRemoved(1, getItemCount()-1);
filteredData.clear();
filteredData.addAll((List<String>)results.values);
for(int i = 1; i < getItemCount() - 1; i++){
notifyItemInserted(i);
}
}
}
}
I'm not sure how correct this way is, but in my code I implemented it like that
private var headerList: List<HeaderItem> = listOf(HeaderItem("Title"))
private fun searchItem(items: List<Items>, query: String) {
items.filterIsInstance<MainItem>().filter { filteredItems ->
filteredItems.header.lowercase().contains(query.lowercase())
}.let { searchedItems ->
rvAdapter.submitList(headerList + searchedItems)
}
}
This way I was able to preserve header element when I did my search

GUI JFrame background color change

I've revisited this post. I have been able to upload the text file, create a GUI, populate the GUI with JRadioButtons that are labeled from the text file...
Now, I cannot get the background to change color when the JRadioButton is selected! I know that it has something to do with the ActionListener, but how do I fix this? The color needs to be implemented from the hex color code.
public class FP extends JFrame implements ActionListener {
TreeMap<String, String> buttonMap = new TreeMap <>();
// Constructor
#SuppressWarnings("empty-statement")
public FP() throws IOException {
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new TitledBorder("Pick a Radio Button!"));
JRadioButton[] btnArray = new JRadioButton[20];
ButtonGroup btnGroup = new ButtonGroup();
BufferedReader reader;
reader = new BufferedReader(new FileReader("src/colors.txt"));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] pair = currentLine.split("\\s+");
buttonMap.put(pair[0],pair[1]);
currentLine = reader.readLine();
}
//check retrieving values from the buttonMap
for(Map.Entry<String,String> entry : buttonMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
for (int i = 0; i<20; i++){
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
JRadioButton rb = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(rb);
btnGroup.add(rb);
rb.addActionListener(this);
}
}
//private final JRadioButton btnMale = new JRadioButton("Male")
Collection bMapIt = buttonMap.entrySet();
Iterator it = bMapIt.iterator();
System.out.println("Colors and codes");
while(it.hasNext())
System.out.println(it.next());
}
#Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.decode(buttonMap.get(e)));
}
public static void main(String[] args) throws IOException {
FP frame = new FP();
frame.setVisible(true);
frame.setSize(350, 240);
frame.setTitle("Final Project");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
for (int i = 0; i<1; i++){
btnArray[i] = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(btnArray[i]);
btnGroup.add(btnArray[i]);
btnArray[i].addActionListener((ActionEvent e) -> {
String btnColor = buttonMap.get(((JRadioButton) e.getSource()).getText());
String hexColor = entry.getValue();
System.out.println(hexColor);
panel.setBackground(Color.decode("#"+hexColor));
});
}
}
This with the addition of class....
#Override
public void actionPerformed(ActionEvent e) {}
}

How to display toast in AsyncTask

I want to display toast message in doInBackground as follows.
private class myAsync extends AsyncTask<Void, Integer, Void>
{
int duration = 0;
int current = 0;
int inc = 0;
#Override
protected Void doInBackground(Void... params) {
videoView.start();
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
duration = videoView.getDuration();
}
});
do {
current = videoView.getCurrentPosition();
inc = inc + 1;
if(inc == 10000 || inc == 25000 || inc == 30000){
Toast.makeText(getApplicationContext(), inc, Toast.LENGTH_LONG).show();
}
} while (current <= duration);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Toast toast = Toast.makeText(getApplicationContext(),values[0], Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
I want to display the inc value when it is 10000, 25000, 30000.
I hope someone who knows this help me.
Thanks
Supposing MyAsync is nested in an Activity :
private class myAsync extends AsyncTask<Void, Integer, Void>
{
int duration = 0;
int current = 0;
int inc = 0;
#Override
protected Void doInBackground(Void... params) {
videoView.start();
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
duration = videoView.getDuration();
}
});
do {
current = videoView.getCurrentPosition();
inc = inc + 1;
if(inc == 10000 || inc == 25000 || inc == 30000){
showToast(inc);
}
} while (current <= duration);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
showToast(values[0]);
// Todo integrate gravity parameter
}
private void showToast(String text)
{
MainActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
});
}
}
I solved it as I put publishProgress(inc); in if statement like
if(inc == 10000 || inc == 25000 || inc == 30000){
publishProgress(inc);
}
it works.

Resources