How to pass arraylist to other function in AsyncTask..? - android

I am trying to pass an array list to other function in Asyctask but it is getting null.
Written following code to read an array list
#Override
protected ArrayList<String> doInBackground(ArrayList<String>... params) {
// TODO Auto-generated method stub
switch (type) {
case MZIP:
fileManager.createZipFolderForMulti(params[0]);
return null;
}
return null;
}
Written following code to pass an array list to AsyncTask
private void zipMiltiple(ArrayList<String> multiSelectData2) {
// TODO Auto-generated method stub
new Back(MZIP).execute(multiSelectData2);
Log.d("JWP", "METHOD :"+ multiSelectData2);
}
Is there any issue in code?

I'm trying to pass the array list to the other function in Asyctask
but I'm getting array list null..
You need to check whether on this line:
private void zipMiltiple(ArrayList<String> multiSelectData2)
multiSelectData2 variable is properly instantiated, i.e.
if (multiSelectData2 != null) {
new Back(MZIP).execute(multiSelectData2);
Log.d("JWP", "METHOD :"+ multiSelectData2);
}
else {
// ArrayList is NULL
}
You need to make sure that your ArrayList is not NULL. You're passing ArrayList correctly but probably you are passing ArrayList that is not instantiated.
If it still won't work, problem is elsewhere and you should add here your logcat.
It's worth to say that there are more possible approaches:
Pass ArrayList via constructor
Make AsyncTask implementation inner class of Activity class -> since
this, you'll have direct access to variables in Activity

The best way to do that is to use inner class:
put your function inside the inner class.
implement doInBackground.
call your function from doInBackground.
package com.stack.question;
import java.util.ArrayList;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;
import android.util.Log;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
public class StackActivity extends Activity {
RatingBar ratingBar;
float nowValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new yourclass().execute("99");
}
class yourclass extends AsyncTask<String, Integer, ArrayList<String>> {
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
yourfunction(result);
zipMiltiple(result);
}
private void zipMiltiple(ArrayList<String> multiSelectData2) {
// TODO Auto-generated method stub
new Back(MZIP).execute(multiSelectData2);
Log.d("JWP", "METHOD :"+ multiSelectData2);
}
private void yourfunction(ArrayList<String> result) {
for (int i = 0; i < result.size(); i++)
Toast.makeText(StackActivity.this, result.get(i),
Toast.LENGTH_LONG).show();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("st1");
arrayList.add("st2");
// Here put your code
return arrayList;
}
}
}
This is a working example, I also include your code in it

Related

Populate a List View with Parse Objcets

My Main Activity has a button which redirects to ResterauntList Activity. I want to get a couple of Objects from my Parse Cloud, and want to add only the name to the ListView. This the code so far
package com.example.gastronomaapp;
import java.util.List;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseQueryAdapter.OnQueryLoadListener;
public class ResterauntList extends ActionBarActivity {
String mValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resteraunt_list);
Bundle bdl = getIntent().getExtras();
mValue = bdl.getString("Value");
setContentView(R.layout.activity_resteraunt_list);
populateList(mValue);
}
private void populateList(String Value) {
ParseQueryAdapter.QueryFactory<ParseObject> factory = new ParseQueryAdapter.QueryFactory<ParseObject>() {
#SuppressWarnings({ "unchecked", "rawtypes" })
public ParseQuery create() {
ParseQuery query = new ParseQuery("Restraunt");
query.whereEqualTo("Location", Value);
return query;
}
};
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(
this, factory);
adapter.setTextKey("name");
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
public void onLoading() {
// Trigger any "loading" UI
}
#Override
public void onLoaded(List<ParseObject> objects, Exception e) {
// TODO Auto-generated method stub
}
});
// Attach it to your ListView, as in the example above
ListView listView = (ListView) findViewById(R.id.restListView);
listView.setAdapter(adapter);
}
}
Not sure whats wrong, but the ListView never populates. My Parse Data Browser claims it has received requests though. Checked the Logcat, it claims the application may be doing too much work.Not really sure whats wrong.
(EDIT) Made a change as suggested in the comments. But now the list view has 2 entries but empty. I know there are 2 entries namely because they are clickable. Completely confused on what is wrong. Have edited the code too!
This is my emulator, as you can see the line there are list view entries
You are forgetting to call the adapter.notifyDatasetChanged() method. If I am not wrong, Parse queries are executed in background, right ? If so, then you need to call this method when the background thread is done.
Plus, as a suggestion, you can simplify your code as:
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("ClassName");
query.whereEqualTo("KEY","VALUE");
query.findInBackground(new FindCallback<ParseObject>(){
#Override
public void done(List<ParseObject> dataFromServer, ParseException e){
if( e == null ) { /** DO SOMETHING */ }
else { /** DO SOMETHING ELSE */ }
}
});

can't return data from inner asynctask class to outer class

Hi friends I know there is a bunch of questions about this topic but I can not get any result from them. i am parsing xml data with my ClassIsInternalParser extends default handler. I use this class in my activity in an inner class PostAsync extends AsyncTask
but the reason is i can not return the data that ı collected in PostAsync class to main activity. it sets only null
here is my codes
package com.example.uiexercisesplash;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ClassIsInternalListViewActivity extends Activity implements OnClickListener{
TextView tv, tv2;
Button back;
String[][] array = new String[10][3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classisinternal_listview);
new PostAsync().execute();
tv=(TextView) findViewById(R.id.tatar);
tv2= (TextView) findViewById(R.id.tatar2);
tv2.setText(array[0][0]); //Why this sets null!!
back= (Button) findViewById(R.id.back);
back.setOnClickListener(this);
}
class PostAsync extends AsyncTask<Void, Void,String[][]>{
ProgressDialog pd;
ClassIsInternalParser parser;
#Override
protected void onPreExecute() {
//we can set up variables here
pd = ProgressDialog.show(ClassIsInternalListViewActivity.this,
"Classisinternal","Loading last post...",true,false);
}
protected void onPostExecute(String[][] result) {
//in this way it sets correctly
tv.setText(result[0][0]);
array=result;
pd.dismiss();
pd.cancel();
}
protected String[][] doInBackground(Void... params) {
parser = new ClassIsInternalParser();
parser.get();
return parser.dataArray;
}
}
#Override
public void onClick(View v) {
finish();
}
}
Try to create PostAsync object and call execute() from that object. After that call get() method to retrieve your return array like this:
PostAsync obj=new PostAsync(this);
obj.execute();
String[][] array=obj.get();
tv2.setText(array[0][0]);
tv2.setText(array[0][0]); is null because you are getting array value before setting values in it,i.e. tv2.setText(array[0][0]); is execute before completing Asynctask.
So do this step in onPostExecute method as
protected void onPostExecute(String[][] result) {
//in this way it sets correctly
tv.setText(result[0][0]);
tv2.setText(result[0][2]);
array=result;
tv2.setText(array[0][0]);// add here
pd.dismiss();
pd.cancel();
}

How to fetch data from Api into listview?

When i am trying to call the method "refresh" of main activity from another Api class,the method was called and also it shows some fatal errors.And it didn't change the adapter values.Can anyone give any idea to clear that.?
package com.example.hotspot;
import com.example.hotspot.HotspotApi;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends Activity {
TextView textview;
ListView listview;
HotspotAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hot_spot);
textview = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
adapter = new HotspotAdapter(this);
listview.setAdapter(adapter);
new HotspotApi(adapter).execute();
}
public void refresh() {
System.out.println("refresh() is called");
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hot_spot, menu);
return true;
}
}
hotspot.java
package com.example.hotspot;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.hotspot.HotspotModel;
import com.example.hotspot.HotspotAdapter;
import android.os.AsyncTask;
public class HotspotApi extends AsyncTask<Void, Integer, Void> implements
Icommon {
public Boolean IsServerErr = false;
private JSONArray response_array;
String url = "some url";
HotspotAdapter adapter;
HotSpot hot;
public HotspotApi(HotspotAdapter adapter) {
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getresult();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
hot=new HotSpot();
hot.refresh();
super.onPostExecute(result);
}
void getresult() {
InternetManager manager = new InternetManager(url);
String category_jsonresponse = manager.URLRequest();
if (!manager.IsServerConn) {
IsServerErr = true;
}
if (category_jsonresponse != null) {
System.out.println("Hotspot_jsonresponse" + category_jsonresponse);
try {
response_array = new JSONArray(category_jsonresponse);
for (int i = 1; i < response_array.length(); i++) {
JSONObject image_object = response_array.getJSONObject(i);
HotspotModel h = new HotspotModel();
h.setId(image_object.getString("id") == null ? ""
: image_object.getString("id"));
h.setContent(image_object.getString("content") == null ? ""
: image_object.getString("content"));
h.setImg(image_object.getString("img") == null ? ""
: image_object.getString("img"));
h.setName(image_object.getString("name") == null ? ""
: image_object.getString("name"));
arraylist.add(h);
}
System.out.println("HotspotModelsize() is " + arraylist.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
HotspotAdapter.java
package com.example.hotspot;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class HotspotAdapter extends BaseAdapter implements Icommon{
private TextView textview;
private View view;
ImageView imageview;
private LayoutInflater inflater;
public HotspotAdapter(Context context ){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arraylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arraylist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
view = inflater.inflate(R.layout.custom_layout, null);
} else {
view = arg1;
}
textview = (TextView) view.findViewById(R.id.txt_content);
textview.setText(arraylist.get(arg0).getName());
return view;
}
}
In your HotSpotApi class you are creating a new HotSpot activity, this seems wrong. I guess that you are getting json data from internet and load it into a listview.
Solution:
In HotspotApi change following instead of calling activity method:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter.notfiyDatasetChanged();
}
Hope this will help you.
hot=new HotSpot(); ?? you cannot use like that! HotSpot is an activity, should be called by Framework for example, activitymanager. Or use startActivity() to show a activity.
Refresh method (adapter.notifyDataSetChanged();) will result in refresh of UI. However, hot = new HotSpot() will not call onCreated() method,which means the UI is not created. So it definitely results in the fatal error.
I'd never see anyone call an Activity with new operator.
You should reference the common process about how use a activity and adapter.

ArrayAdapter with string array and Jsoup

I am able to extract the href elements from a page and store the results into a string array. Then display it inside a TextView. The problem comes if I try to display to a ListView. I don't know how to work with ArrayAdapters in this case. This is my working code that displays into a TextView.
package com.example.jsouptestarray;
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.example.jsouptestarray.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView text;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> arr_linkText=new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document doc;
String linkText = "";
try {
doc = Jsoup.connect("https://www.google.com/").get();
Elements links = doc.getElementsByTag("a");
for (Element el : links) {
linkText = el.attr("href");
arr_linkText.add(linkText); // add value to ArrayList
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr_linkText; //<< retrun ArrayList from here
}
#Override
protected void onPostExecute(ArrayList<String> result) {
// get all value from result to display in TextView
for (String temp_result : result) {
System.out.println("links :: "+temp_result);
text = (TextView) findViewById (R.id.textView2);
text.append(temp_result + "\n" + "\n");
text.setMovementMethod(new ScrollingMovementMethod());
}
}
}
}
This is my attempt with the ListView, but I get an error and I don't understand how to fix it.
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, temp_result);
// Assign adapter to ListView
list.setAdapter(adapter);
Here is a screenshot of the error
I hope someone can help me fix it, and I appreciate your time!
Fourth element of the constructor is excess in your case. It can be used to set data at once, you should see API.
Try this:
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1);
for (String temp_result : result)
{
adapter.add(temp_result);
}
// Assign adapter to ListView
list.setAdapter(adapter);
Replace this with MainActivity.this. When you're inside the AsyncTask, this refers to the AsyncTask instance, which can't be passed to the constructor (different, unrelated, incompatible classes)
So you need to call an Activity as the argument and since your AsyncTask is part of an Activity, you can explictly reference the Activity instance with ClassName.this.

using AsyncTask class for parallel operationand displaying a progress bar

I am displaying a progress bar using Async task class and simulatneously in parallel operation , i want to retrieve a string array from a function of another class that takes some time to return the string array.
The problem is that when i place the function call in doing backgroung function of AsyncTask class , it gives an error in Doing Background and gives the message as cant change the UI in doing Background ..
Therefore , i placed the function call in post Execute method of Asynctask class . It doesnot give an error but after the progress bar has reached 100% , then the screen goes black and takes some time to start the new activity.
How can i display the progress bar and make the function call simultaneously.??plz help , m in distress
here is the code
package com.integrated.mpr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Progess extends Activity implements OnClickListener{
static String[] display = new String[Choose.n];
Button bprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
bprogress = (Button) findViewById(R.id.bProgress);
bprogress.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bProgress:
String x ="abc";
new loadSomeStuff().execute(x);
break;
}
}
public class loadSomeStuff extends AsyncTask<String , Integer , String>{
ProgressDialog dialog;
protected void onPreExecute(){
dialog = new ProgressDialog(Progess.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i = 0 ;i<40;i++){
publishProgress(5);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dialog.dismiss();
String y ="abc";
return y;
}
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result){
display = new Logic().finaldata();
Intent openList = new Intent("com.integrated.mpr.SENSITIVELIST");
startActivity(openList);
}
}
}
You can't dismiss the dialog in doInBackground() - even dismissing a dialog needs the UI task. Move dialog.dismiss() to onPostExecute() of the AsyncTask.

Categories

Resources