android update custom view in asynctask - java

Ok, I have a custom view which plays gifs from the internet. Therefor I need to add an url to my view to download the gif. But I can't seem to update my custom view inside my asynctask. I need to add an url string to my custom view gifView.setUrl(). It works in the onCreate Class but it gives me null in asynctask.
Oncreate class
GifView gifView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
id = extras.getInt("id");
String idStr = String.valueOf(id);
String extension = extras.getString("extension");
if(extension.equals(".gif")){
setContentView(R.layout.activity_post_gif);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gifView = (GifView)findViewById(R.id.gifview);
titleStr = (TextView)findViewById(R.id.titleTXT);
postInfo = (TextView)findViewById(R.id.infoTXT);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//the url
new getJsonInfoGif().execute("http://www.website.com/jsonApi");
}else{
Asynctask
public class getJsonInfoGif extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("loading post...");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
return GET(strings[0]);
}
#Override
protected void onPostExecute(String res) {
try {
JSONObject jsonObject = new JSONObject("{'postinfo':[" + res + "]}");
JSONArray jsonArray = jsonObject.getJSONArray("postinfo");
JSONObject obj = jsonArray.getJSONObject(0);
//post title
titleStr.setText(obj.getString("name"));
//category and maker full name
//large image
JSONObject imgObj = obj.getJSONObject("thumbnails");
gifView.setUrl("http://www.website.com/my.gif");
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
GifView.java
public void setUrl(String urlStr){
this.urlStr = urlStr;
invalidate();
requestLayout();
}
public String getUrl(){
return this.urlStr;
}
public void init(final Context context)throws IOException{
setFocusable(true);
movie = null;
movieWidth = 0;
movieHeight = 0;
movieDuration = 0;
final Thread thread = new Thread(new Runnable() {
#Override
public void run(){
try{
Log.d("DEBUG", "URL" + urlStr);
URL url = new URL(urlStr);
try {
HttpURLConnection http = (HttpURLConnection) url.openConnection();
inputStream = http.getInputStream();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
movie = Movie.decodeStream(inputStream);
movieWidth = movie.width();
movieHeight = movie.height();
movieDuration = movie.duration();
((PostActivity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
invalidate();
requestLayout();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
thread.start();
}
Here is the Log from the url, it gives me null if I add the url inside my asynctask in Activity.
11-07 14:41:58.821 5674-6076/svenmobile.tools.showcase D/DEBUG﹕ URLnull
What I want to know is what the problem is and how to solve it if possible.
Thanks in advance, Sven

Maybe you called init() before setUrl().
You can pass it the url in the contructor, or public void init(final Context context, String urlStr)throws IOException{
I also suggest you to move all that network code to doInBackground

Related

Can't read directly from URL using AsynTask

I am trying to develop an application that reads jokes from a URL. I am using an AsyncTask to read from URL and then put the string to a textView. But I can't figure out why it isn't working.
Here is my code:
public class MainActivity extends AppCompatActivity {
private Button oneJokeBtn, threeJokesBtn;
private final static String ERROR_TAG = "Download Error";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capturing our buttons from the view
oneJokeBtn = findViewById(R.id.joke_1);
threeJokesBtn = findViewById(R.id.joke_3);
// Register the onClick listener
oneJokeBtn.setOnClickListener(buttonHandler);
threeJokesBtn.setOnClickListener(buttonHandler);
// Declaring the Spinner
Spinner spinner = findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.length_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
// Spinner onItemSelector implemented in the OnCreate Method
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
Toast.makeText(parent.getContext(), R.string.short_toast, Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(parent.getContext(), R.string.medium_toast, Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(parent.getContext(), R.string.long_toast, Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/** AsyncTask that reads one joke directly from the URL and adds it to the textView */
private class Download1JokeAsyncTask extends AsyncTask <Void, Void, String> {
private ProgressDialog progressDialog;
private String mResponse = "";
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage(getString(R.string.progress_msg));
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... voids) {
String joke = null;
try {
// Open a connection to the web service
URL url = new URL( "http://www-staff.it.uts.edu.au/~rheise/sarcastic.cgi" );
URLConnection conn = url.openConnection();
// Obtain the input stream
BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
// The joke is a one liner, so just read one line.
joke = in.readLine();
// Close the connection
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
mResponse = getString(R.string.fail_msg);
} catch (IOException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
mResponse = getString(R.string.fail_msg);
}
return joke;
}
#Override
protected void onPostExecute(String joke) {
TextView tv = findViewById(R.id.tv_joke);
if (joke == null) {
tv.setText(R.string.fail_msg);
}
else {
tv.setText(joke);
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
/** AsyncTask that reads three jokes directly from the URL and adds it to the textView */
private class Download3JokeAsyncTask extends AsyncTask<Void, Integer, String[]> {
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgress(0);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(true);
mProgressDialog.setMessage(getString(R.string.three_jokes_btn));
mProgressDialog.show();
}
#Override
protected String[] doInBackground(Void... voids) {
int count = 2;
for (int i = 0; i < 2; i++){
try {
URL url = new URL("http://www.oracle.com/");
URLConnection conn = url.openConnection();
// Obtain the input stream
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// The joke is a one liner, so just read one line.
String joke;
while ((joke = in.readLine()) != null) {
System.out.println(joke);
}
// Close the connection
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
} catch (IOException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
}
publishProgress((int) ((i / (float) count) * 100));
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
setProgress(0);
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
}
}
/** onClickListener that gets the id of the button pressed and download jokes accordingly */
OnClickListener buttonHandler = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.joke_1:
new Download1JokeAsyncTask().execute();
break;
case R.id.joke_3:
new Download3JokeAsyncTask().execute();
break;
}
}
};
The AsyncTask is called Download1JokeAsyncTask, it is supposed to read from URL and then put it into a text view. and I've put an error message to appear in the text view if the joke (the string where the joke is stored) is null.
And always the text view says that it failed to download a message.
Please help.
I went to your joke page and inspecting the source (in Firefox) and I found this:
<html>
<head>
<link rel="alternate stylesheet" type="text/css" href="resource://content-accessible/plaintext.css" title="Wrap Long Lines">
</head>
<body>
<pre>I'm really good at stuff until people watch me do that stuff.</pre>
</body>
</html>
So you could save the whole output as a String and then use this:
string.substring(string.indexOf("<pre>"), string.indexOf("</pre>");
string.substring(4);
Basically you are downloading only the first line of the page which would be the content declaration.
Instead you need to download the sixth line and remove the pre tags.
Good Luck!

how to fetch data without button click

how to fetch first image without click fetch image button
click to view image
this code work fine but on click fetch image button but i want fetch image with out click fetch images button i want to remove this button
Public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
You can trigger it in onCreate(),but you must not run it on UI thread,for it might be a time-consuming operation.Read Specifying the Code to Run on a Thread to help,
you might add the following block in your onCreate() method:
new Runnable() {
#Override
public void run() {
getAllImages();
}
}.run();

Error In MyTask with URLEncoder - android & java

I'm using URLEncoder in my activity. but i have a error in MyTask. I have marked the error with Error in my code.
public class Search_Ringtone extends SherlockActivity{
ListView lsv_latest;
List<ItemRingCategoryItem> arrayOfRingcatItem;
RingCateItemAdapter objAdapterringitemitem;
AlertDialogManager alert = new AlertDialogManager();
private ItemRingCategoryItem objAllBean;
JsonUtils util;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ringcatitem_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
lsv_latest=(ListView)findViewById(R.id.latest_list);
arrayOfRingcatItem=new ArrayList<ItemRingCategoryItem>();
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = URLEncoder.encode(str, "UTF-8");
MyTask().execute(myUrl); //*Error*
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(Search_Ringtone.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
}
lsv_latest.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
objAllBean=arrayOfRingcatItem.get(position);
Intent intplay=new Intent(getApplicationContext(),SingleRingtone.class);
Constant.RINGTONE_ITEMID=objAllBean.getRingItemId();
startActivity(intplay);
}
});
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search_Ringtone.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(getApplicationContext(), "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.LATEST_ARRAY_NAME);
JSONObject objJson = null;
if(jsonArray.length()==0)
{
showToast("موردی پیدا نشد!");
}
else
{
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemRingCategoryItem objItem = new ItemRingCategoryItem();
objItem.setRingItemId(objJson.getString(Constant.CATEITEMRING_RINDID));
objItem.setRingItemCatId(objJson.getString(Constant.CATEITEMRING_RINDCATID));
objItem.setRingItemCatName(objJson.getString(Constant.CATEITEMRING_CATENAME));
objItem.setRingItemName(objJson.getString(Constant.CATEITEMRING_RINGNAME));
objItem.setRingItemUrl(objJson.getString(Constant.CATEITEMRING_RINDURL));
objItem.setRingItemDownCount(objJson.getString(Constant.CATEITEMRING_RINDDOWNCOUNT));
objItem.setRingItemUser(objJson.getString(Constant.CATEITEMRING_RINDUSER));
objItem.setRingItemTag(objJson.getString(Constant.CATEITEMRING_RINDTAG));
objItem.setRingItemSize(objJson.getString(Constant.CATEITEMRING_RINDSIZE));
objItem.setRingStar(objJson.getString(Constant.LATESTRING_RINGSTAR));
objItem.setRingImage(objJson.getString(Constant.LATESTRING_RINGIMAGE));
arrayOfRingcatItem.add(objItem);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
Shouldn't it be new MyTask().execute(myURL);?
Also because it's an AsyncTask you need to retain a reference to it until it's finished or else the garbage collector destroys it.
i write like this and solved thank you everyone:
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = null;
try {
myUrl = URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyTask().execute(myUrl);

Swipe Refresh freezes when executing async task

I'm encountering a problem, when I try running an asynchronous task on refresh using a swipe refresh layout it "freezes" and doesn't rotate. When the task is done it just disappears.
Here is my code:
HotActivityFragment.java:
public class HotActivityFragment extends Fragment {
ListView hotList;
SwipeRefreshLayout mSwipeRefreshLayout;
Context context;
SharedPreferences sharedPreferences;
HotListAdapter hotListAdapter;
public HotActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hot, container, false);
context = getContext();
mSwipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.activity_main_swipe_refresh_layout);
hotList = (ListView)view.findViewById(R.id.hotListView);
hotList.setOnScrollListener(new EndlessScrollListener(getActivity()));
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
try {
ArrayList<ListTypeItem> initial_list = new DownloadPosts(getActivity()).execute().get();
this.hotListAdapter = new HotListAdapter(getContext(), initial_list);
hotList.setAdapter(hotListAdapter);
}catch(Exception e)
{
Log.d("Download Error", e.toString());
}
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrievePosts();
}
});
mSwipeRefreshLayout.setColorSchemeResources(R.color.accentColor, R.color.backgroundColor);
return view;
}
public void retrievePosts()
{
// showing refresh animation before making http call
mSwipeRefreshLayout.setRefreshing(true);
//shared preferences = empty
sharedPreferences.edit().putString("last_time_downloaded", "empty").commit();
try {
ArrayList<ListTypeItem> listItems = new DownloadPosts(getActivity(), mSwipeRefreshLayout).execute().get();
hotListAdapter.updateList(listItems);
hotListAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.d("Download Error", e.toString());
}
mSwipeRefreshLayout.setRefreshing(false);
//for testing purposes
// new Handler().postDelayed(new Runnable() {
// #Override public void run() {
// mSwipeRefreshLayout.setRefreshing(false);
// }
// }, 5000);
}
}
DownloadPosts.java:
public class DownloadPosts extends AsyncTask<Void, Void, ArrayList<ListTypeItem>> {
SharedPreferences sharedPreferences;
SwipeRefreshLayout swipeRefreshLayout;
public DownloadPosts(Activity activity)
{
this.sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE);
}
public DownloadPosts(Activity activity, SwipeRefreshLayout swipeRefreshLayout)
{
this.sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE);
this.swipeRefreshLayout = swipeRefreshLayout;
}
#Override
protected ArrayList<ListTypeItem> doInBackground(Void... args)
{
StringBuilder parsedString = new StringBuilder();
ArrayList<ListTypeItem> downloadList = new ArrayList<>();
StringBuilder str = new StringBuilder();
if(sharedPreferences.getBoolean("Thomas More",false))
{
str.append("190155257998823,");
}
String school_url = str.toString();
if(school_url.length() > 0)
{
school_url = school_url.substring(0, str.length()-1);
}
try{
String date = "";
//checken of opnieuw moet bepaald worden
// + in de adapter moet als gereload wordt last_time_downloaded == empty
if(!sharedPreferences.getString("last_time_downloaded","empty").equals("empty"))
{
String last_date = sharedPreferences.getString("last_time_downloaded","nothing");
last_date = last_date.replace(" ","T");
date= "&datum_last_posted=" + last_date;
}
URL url = new URL("http://localhost/getpostlist.php?school_post=" + school_url + date);
URLConnection conn = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null)
{
parsedString.append(json + "/n");
}
String s = parsedString.toString().trim();
//converten van string opgehaald via http naar jsonobject
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++)
{
JSONObject tempObj = array.getJSONObject(i);
School_WithoutImage tempSchool = new School_WithoutImage(tempObj.getString("school_id"),
tempObj.getString("post_message"),tempObj.getInt("views"),tempObj.getInt("likes")
,tempObj.getInt("post_id"),tempObj.getString("datum_posted"));
downloadList.add(tempSchool);
if(i == array.length()-1) {
sharedPreferences.edit().putString("last_time_downloaded",tempObj.getString("datum_posted")).commit();
}
}
JSONObject obj = array.getJSONObject(0);
}catch(Exception e)
{
Log.d("Exception", e.toString());
}
return downloadList;
}
#Override
protected void onPostExecute(ArrayList<ListTypeItem> result)
{
if(this.swipeRefreshLayout != null)
{
// swipeRefreshLayout.setRefreshing(false);
}
}
}
I have no idea why the swiperefreshview doesn't spin. Anyone has an idea?
Because the call to get():
.execute().get()
Forces the UI thread to wait for the AsyncTask to finish.
Instead you should look at doing this in the onPostExecute method:
protected void onPostExecute(ArrayList<ListTypeItem> listItems) {
hotListAdapter.updateList(listItems);
hotListAdapter.notifyDataSetChanged();
}
Because you are waiting for the result from asynctask by calling get just after execute. And further passing it to list.
You can use Local Broadcast Listener or can create an interface and can us that as callback, without freezing UI

In Android: How can i send the result of from OnPostExecute() to other activity?

I got the result of OnPostExecute() to main activity but I want to use this result in second activity. I read and applied something with using Bundle but it doesn't run. I got error NullPointerException cause of not receiving the value in the second activity. Here is my MainActivity (It has an interface AsyncResponse ):
public class MainActivity extends Activity implements AsyncResponse
{
public String t;
public Bundle bnd;
public Intent intent;
public String sending;
private static final String TAG = "MyActivity";
ProductConnect asyncTask =new ProductConnect();
public void processFinish(String output){
sending=output;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
bnd=new Bundle();
intent=new Intent(MainActivity.this, second.class);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
bnd.putString("veri", sending);
intent.putExtras(bnd);
startActivity(intent);
}
});
}
// START DATABASE CONNECTION
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(
"http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(t);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait");
pd.setMessage("Authenticating..");
pd.show();
}
}
Here is My Second Activity:
public class second extends ActionBarActivity {
public CharSequence mTitle;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Bundle receive=getIntent().getExtras();
String get=receive.getString("veri");
Log.v(TAG, get);
}
What should i do?
AsyncTask.execute() is a non-blocking call. You can't set the result to the Bundle and start an Intent immediatly after execute(). That's why you are getting a NPE in your second Activity because sending isn't initialized, so it's null.
Move the code to start a new Activity with the desired data in your callback:
public void processFinish(String output){
bnd.putString("veri", output);
intent.putExtras(bnd);
startActivity(intent);
}
And make sure you call delegate.processFinished(String) if your data processing is finished. So move it out of the for loop. BTW t will only get the last "name"-String in the JSONArray. If you wanna get them all make t a String array and fill it.
As your variable t is globally declared in your activity so can directly use the value of t which you are assigning in your onPostExecute() method. Just you need to check for its null value only in your button click event as below :
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
if(t != null || t != "")
{
bnd.putString("veri", t);
intent.putExtras(bnd);
startActivity(intent);
}
}
});
// try this
public class MainActivity extends Activity
{
public String t;
public Bundle bnd;
public Intent intent;
private static final String TAG = "MyActivity";
ProductConnect asyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
bnd=new Bundle();
intent=new Intent(MainActivity.this, second.class);
asyncTask = new ProductConnect(new ResultListener() {
#Override
public void onResultGet(String value) {
bnd.putString("veri", value);
intent.putExtras(bnd);
startActivity(intent);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
}
});
}
class ProductConnect extends AsyncTask<Boolean, String, String> {
private ResultListener target;
public ProductConnect(ResultListener target) {
this.target = target;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(
"http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
target.onResultGet(t);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait");
pd.setMessage("Authenticating..");
pd.show();
}
}
interface ResultListener {
public void onResultGet(String value);
}
}
Shortly before someone posted a solution and it works without any errors but it was deleted. This solution is by this way:
public void onClick(View arg0) {
asyncTask.execute(true);
}
});
}
Then OnPostExecute changed like this:
protected void onPostExecute(String result) {
Intent passValue=new Intent(MainActivity.this, second.class);
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(t);
}
passValue.putExtra("veri", t);
startActivity(passValue);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
Lastly in my second activity receive the string by this way:
String receivedVal= getIntent().getExtras().getString("veri");
Log.v(TAG, receivedVal);
Thank you someone who posted this solution shortly before :)

Categories