AsyncTasck class will not execute after calling execute method - android

I have a class to download a file (PortParser) class. and after setting the debugger inside doInBackground method. I can see after calling execute, it jumps to the next line in MainActivity instead of going inside doInBackground. what could this be. I can see the program going inside the execute method which in turn calls the AsyncTask execute method. but it never goes inside doInBackground method. Thanks.
this is the calling instance inside main activity class
portParser = new PortParser(this.getApplicationContext());
portParser.execute();
package org.pctechtips.netdroid.classes;
import android.os.AsyncTask;
import android.content.Context;
import android.util.*;
import org.pctechtips.netdroid.dbhelper.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.zip.*;
import javax.net.ssl.*;
/**
* Java class to downloand and parse service-port csv file from iana.org
*/
public class PortParser {
//public static final String PORT_URL = "https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv";
public static final String PORT_URL = "http://pctechtips.org/apps/service-names-port-numbers.csv";
org.pctechtips.netdroid.dbhelper.DatabaseHelper dbHelper;
DownloadPortFile downloadFile;
android.database.sqlite.SQLiteDatabase db;
Context context;
public PortParser(Context ctxt) {
dbHelper = new org.pctechtips.netdroid.dbhelper.DatabaseHelper(ctxt);
db = dbHelper.getWritableDatabase();
downloadFile = new DownloadPortFile();
}
public void execute() {
Log.v("DOWNLOADING", "DOWNLOADING PORT FILE");
downloadFile.execute();
}
public class DownloadPortFile extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
BufferedReader in = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(PORT_URL);
connection = (HttpsURLConnection) url.openConnection();
// connection.setRequestProperty("Accept-Encoding", "gzip");
connection.connect();
Log.v("CONNECTION", "CONNECTION OK");
if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
Log.v("CONNECTION", "CONNECTION OK");
}
in = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));
String line;
int lineNum = 0;
while ((line = in.readLine()) != null) {
String[] data = line.split(",", -1);
Log.v("DATA", Arrays.toString(data) +" "+ lineNum);
if(data.length != 12) { continue; }
if(data == null) { continue; }
if(!data[2].equalsIgnoreCase("tcp")) { continue; }
String service = (data[0].equals(" ")) ? "null" : data[0];
int portNum = Integer.parseInt(data[1]);
String protocol = data[2];
String desc = data[3];
Log.v("PARSED", service +" "+ portNum +" "+ protocol +" "+ desc +" "+data.length);
long dbInsert = dbHelper.addTableRecord(service, portNum, protocol, service);
}
} catch (Exception e) {
} finally {
/*try {
if (in != null) {
in.close();
}
} catch (IOException ignored) {
}
if (connection != null) {
connection.disconnect();
}*/
}
return null;
}
#Override
protected void onProgressUpdate(Void... voids) {
}
#Override
protected void onPostExecute(Void aVoid) {
}
}
}

I can see after calling execute, it jumps to the next line in MainActivity instead of going inside doInBackground
This is how it should be as there's no reason for main thread flow to be disrupted just because you spawned other asynchronous worker. That would be actually contrary to what async things are for. If you want to debug doInBackground() you should set a breakpoint on that method's code somewhere (+ you may need to call Debug.waitOnDebugger() if just breakpoint won't work).

Related

Using getSupportFragmentManager() inside AsyncTask

I have an Activity which has a Navigation Drawer that has many buttons and one of them is leading to a fragment.
The problem is that I have to make an AsyncTask to get some information from the server but I can't get to use getSupportFragmentManager() inside the AsyncTask.
I tried to use context or activity but I can't get it to work.
I get this error cannot resolve method getSupportFragmentManager()
AsyncTask.java:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AsyncTask extends AsyncTask<Void, Void, String> {
private Context c;
private String urlAddress;
private String token;
private DatabaseHelper db;
private Activity mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
this.mainActivity = activity;
//GET token FROM database
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}
#Override
protected String doInBackground(Void... params) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
//SUCCESS
mainActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new SessionsFragment())
.addToBackStack("back")
.commit();
} else {
//NO SUCCESS
}
}
private String send() {
//CONNECT
HttpURLConnection connection = Connector.connect(urlAddress);
if (connection == null) {
return null;
}
try {
OutputStream outputStream = connection.getOutputStream();
//WRITE
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(new DataPackager(token).packData());
bufferedWriter.flush();
//RELEASE RES
bufferedWriter.close();
outputStream.close();
//HAS IT BEEN SUCCESSFUL?
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//GET EXACT RESPONSE
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
//READ LINE BY LINE
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondParentObject = parentObject.getJSONObject("data");
//json getter and adder to database
JSONArray array = secondParentObject.getJSONArray("s");
for (int i = 0; i < array.length(); i++) {
JSONObject finalObject = array.getJSONObject(i);
db.SessionsAddJson(finalObject);
//RELEASE RES
reader.close();
}
return "c";
} else {
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return null;
}
}
I call the task by:
new $AsyncTask(getApplicationContext(), db, URL, MyActivity.this).execute();
Thank you for your help.
Upd.:
You should pass the AppCompatActivity in constructor, like this:
Replace
private Activity mainActivity;
with
private AppCompatActivity mainActivity;
Also when you use it: replace
new $AsyncTask(getApplicationContext(), db, URL).execute();
with
new $AsyncTask(getApplicationContext(), db, URL, YourCurrentActivity.this).execute();
Notice that YourCurrentActivity should extends AppCompatActivity.
You just confuse AppCompatActivity with Activity. Activity haven't getSupportFragmentManager(), but AppCompatActivity have this.
If you are using an asyntask class then to load fragment you need context,i.e context of particular activity.
So typecast the context to the respective activity where you want to load the fragment and onPostExecute load the fragment using particular activity fragmentManager.
public class sampleAsyncTask extends AsyncTask<Void, Void, Void> {
private YourActivity mActivity;
#Override
protected Void doInBackground(Void... voids) {
return null;
}
public sampleAsyncTask(Context context) {
super();
activity = (YourActivity) context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();
}
}
EDIT:
In this line of code instead of storing generic reference of activity typecast to particular activity i.e your current activity.
private YOURACTIVITY mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
//TypeCast to your particular activity
mainActivity =(YOURACTIVITY) activity;
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}
Your activity should be AppCompatActivity not Activity
try this
getActivity().getFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();

App Crashes while switching from one Activity to another

Aim: Building app on Google API to fetch the data about the books the user searches
Problem Explanation:
Whenever I hit the submit Button, my app crashes.
This is my first approach in making a network request app and I need guidance.
MainActivityClass
package com.example.vidit.books;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText query = (EditText) findViewById(R.id.query);
Button submit= (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity.this,Request.class);
intent.putExtra ( "text", query.getText().toString() );
startActivity(intent);
}
});
}
}
Second Class
package com.example.vidit.books;
import android.content.Intent;
public class Request {
Intent i = getIntent();
String text = i.getStringExtra ("text");
public static final String LOG_TAG = Request.class.getSimpleName();
String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
}
public void UpdateUi(Book book)
{
BookAdapter bookAdapter = new BookAdapter(this,book);
ListView listView= (ListView) findViewById(R.id.listview_all);
}
private class BookAsyncTask extends AsyncTask<URL,Void,Book>
{
#Override
protected Book doInBackground(URL... urls) {
URL url = createUrl(APIURL);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
final Book book = extractFeatureFromJson(jsonResponse);
return book;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if(urlConnection.getResponseCode()==200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private Book extractFeatureFromJson(String bookJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray items = baseJsonResponse.getJSONArray("items");
// If there are results in the features array
for(int i=0;i<10;i++)
{
JSONObject firstFeature = items.getJSONObject(i);
JSONArray author=firstFeature.getJSONArray("author");
for(int j=0;j<author.length();j++)
{
JSONObject authorFeature=author.getJSONObject(j);
}
String title = items.getString(Integer.parseInt("title"));
// Create a new {#link Event} object
return new Book(title,author);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
BookAdapter Class:
package com.example.vidit.books;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, Book book)
{
super(context,0, (List<Book>) book);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book cbook=getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(cbook.getmTitle());
TextView author=(TextView) listItemView.findViewById(R.id.author);
author.setText((CharSequence) cbook.getmAuthor());
return listItemView;
}
}
Showing error in statement:
String text = i.getStringExtra ("text");
Need guidance
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
Showing error in statement : String text = i.getStringExtra ("text");
Request for Guidance
Well you need to get the data passed inside onCreate like below.
String APIURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
Bundle bundle = getIntent().getExtras();
String text = bundle.getString("text");
APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
}
And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.

How to get multiple messages from server in android socket

I am implementing socket programming in android. I am successfully getting data from client and displaying it to the server.
The asynctask is as follows:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
The above code gets data from server and write it to the text view. I want to use the same socket to get data multiple times from server, unless a particular button is clicked. But, in doInBackground, we can't use any ui component. I want to change the following component, so that I can recieve multiple data from the server:
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
I tried to use
onProgressUpdate
but it didn't work either. Please help me to solve this.
Edit 1: the client's main activity :
package com.example.shiza.client;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "CLIENT_MESSAGE";
EditText ip_address;
EditText port_number;
EditText message_client;
Button button_send;
Button button_cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View view) {
// ip_address = (EditText) findViewById(R.id.ip_address);
// ip_address.setText("192.168.9.100");
// port_number = (EditText) findViewById(R.id.port_number);
// port_number.setText("8080");
message_client = (EditText) findViewById(R.id.message_client);
button_send = (Button)findViewById(R.id.button_send);
button_cancel = (Button)findViewById(R.id.button_cancel);
Log.d(TAG, "connecting to the server.");
// new ConnectToServer(ip_address.getText().toString(), port_number.getText().toString(), message_client,button_send,button_cancel).execute();
new ConnectToServer("192.168.9.100","8080", message_client,button_send,button_cancel).execute();
}
}
class ConnectToServer extends AsyncTask<Void, DataOutputStream, Void> {
private static final String TAG = "CLIENT_MESSAGE";
String ip_address;
int port_number;
EditText message_client;
Button button_send;
Button button_cancel;
boolean send = false;
boolean cancel = false;
public ConnectToServer(String ip_address, String port_number, EditText message_client,Button button_send,Button button_cancel) {
this.ip_address = ip_address;
this.port_number = Integer.parseInt(port_number);
this.message_client = message_client;
this.button_cancel = button_cancel;
this.button_send = button_send;
}
#Override
protected Void doInBackground(Void... params) {
try {
Socket socket = new Socket(ip_address, port_number);
if (LoggerConfig.TAG) {
Log.d(TAG, "the socket is created at " + ip_address);
}
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
while (!cancel )
publishProgress(output);
// output.writeUTF("Hello from string");
if (LoggerConfig.TAG) {
Log.d(TAG, "I have written and closed the loop.");
}
socket.close();
} catch (IOException e) {
if (LoggerConfig.TAG) {
Log.d(TAG, "Could not connect.");
}
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(DataOutputStream... values) {
super.onProgressUpdate(values);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send = true;
}
});
button_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel = true;
}
});
Log.d(TAG, "I am in onProgressUpdate");
if ( send )
{
try {
values[0].writeUTF(message_client.getText().toString());
Log.d(TAG, "I am in onProgressUpdate try.");
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "I am in onProgressUpdate catch.");
}
send = false;
}
}
}
The server's main activity:
package com.example.shiza.server;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
TextView ip_address;
TextView client_message;
TextView server_status;
TextView show_client_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip_address = (TextView) findViewById(R.id.ip_address);
client_message = (TextView) findViewById(R.id.get_client_message);
server_status = (TextView) findViewById(R.id.server_status);
show_client_message = (TextView) findViewById(R.id.show_client_message);
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
ip_address.setText(ip);
// Making a server socket here
}
public void startServer(View view) {
GetFromClient getFromClient = new GetFromClient(this,server_status,show_client_message);
getFromClient.execute();
}
}
class GetFromClient extends AsyncTask<Void, String, Void> {
Context context;
TextView server_status;
TextView show_client_message;
String TAG = "SERVER_MESSAGE";
String inputFromClient = null;
public GetFromClient(Context context,TextView server_status,TextView show_client_message) {
this.context = context;
this.server_status = server_status;
this.show_client_message = show_client_message;
}
#Override
protected Void doInBackground(Void... params) {
Socket socket;
try {
ServerSocket serverSocket = new ServerSocket(8080);
Log.d(TAG, "Server Socket is starting....");
// server_status.setText("The server is running");
publishProgress("okay");
socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
// Calling the second background task for handling input from server
// Log.d(TAG, "Server Socket is started....");
do
{
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
inputFromClient = input.readUTF();
publishProgress(inputFromClient);
}
while ( inputFromClient != "bye" );
// publishProgress(2);
socket.close();
} catch (IOException e) {
Log.d(TAG, "I am in catch.");
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d(TAG, "I am in onProgress update.");
if ( values[0].equals("okay") )
{
server_status.setText("Server has been started");
server_status.setTextColor(context.getResources().getColor(R.color.green));
}
else
{
show_client_message.setText(values[0]);
}
}
protected void onPostExecute(Void inputFromClient)
{
Log.d(TAG, "I am in onPostExecute.");
server_status.setText("Server is not running");
server_status.setTextColor(context.getResources().getColor(R.color.red));
}
}
I am able to do the messaging but the following loop blocks everything:
do
{
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
inputFromClient = input.readUTF();
publishProgress(inputFromClient);
}
while ( inputFromClient != "bye" );
You can update your TextView in the doInBackground method using RunUiThread. After receiving the data from server just call
runOnUiThread(new Runnable() {
#Override
public void run() {
//here you update the views
}
});

android: hide progressdialog whe the app regain control

I've an app that opens the facebook app when you click on a button, it works fine but on slow devices (like mine) facebook takes some seconds to show up, so i want to add a simple progressdialog that says "please wait"
i can show the progress dialog and open facebook with this code:
final ProgressDialog pd = ProgressDialog.show(contatti.this, "", "Attendere...", true);
Intent facebookIntent = getOpenFacebookIntent(getApplicationContext());
startActivity(facebookIntent);
//pd.dismiss();
the first time i tried, it worked fine but when i went back from facebook to my app the dialog was still showing, and i had no way to close it.
added dismiss() to try hide it, but it was a stupid idea >.<
how can i dismiss the dialog when the app regain control?
For this situation you have to check whether the application is sent background or not in on pause if it sent to background then close the dialog.
for checking the application is in bacground or not just have a look
android:how to check if application is running in background
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.gvsu.cis.toptracks.R;
import edu.gvsu.cis.toptracks.TopTrackListActivity;
import edu.gvsu.cis.toptracks.data.Customer;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class LastWebAPITask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private TopTrackListActivity activity;
private static final String debugTag = "LastWebAPITask";
public LastWebAPITask(TopTrackListActivity activity) {
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_tracks), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
Log.d(debugTag, "Background:" + Thread.currentThread().getName());
String result = LastHelper.downloadFromServer(params);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<Customer> trackdata = new ArrayList<Customer>();
progDialog.dismiss();
if (result.length() == 0) {
this.activity.alert("Unable to find track data. Try again later.");
return;
}
try {
JSONObject respObj = new JSONObject(result);
JSONArray tracks = respObj.getJSONArray("GetStockListResult");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String Inventory_Status = track.getString("Inventory_Status");
String modify_Date = track.getString("modify_Date");
String msg = track.getString("msg");
String serial_nbr = track.getString("serial_nbr");
;
trackdata
.add(new Customer(Inventory_Status, modify_Date, msg, serial_nbr));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.activity.setTracks(trackdata);
}
}
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class LastHelper {
private static final String LastUrl = "http://etosxmldev.ctdi.com/ws/wcf/UNIVERSAL-DEMO/Service.svc/GetStockList?LocationId=300779360.svc/GetStockList/1111";
private static final int HTTP_STATUS_OK = 200;
private static byte[] buff = new byte[1024];
private static final String logTag = "LastHelper";
public static class ApiException extends Exception {
private static final long serialVersionUID = 1L;
public ApiException(String msg) {
super(msg);
}
public ApiException(String msg, Throwable thr) {
super(msg, thr);
}
}
protected static synchronized String downloadFromServer(String... params)
throws ApiException {
String retval = null;
String url = LastUrl;
Log.d(logTag, "Fetching " + url);
// create an http client and a request object.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
// execute the request
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
// handle error here
throw new ApiException("Invalid response from last.fm"
+ status.toString());
}
// process the content.
HttpEntity entity = response.getEntity();
InputStream ist = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readCount = 0;
while ((readCount = ist.read(buff)) != -1) {
content.write(buff, 0, readCount);
}
retval = new String(content.toByteArray());
} catch (Exception e) {
throw new ApiException("Problem connecting to the server "
+ e.getMessage(), e);
}
return retval;
}
}
U have to use Asynctask class for doing this.Working Example for me.in your Activity class
LastWebAPITask lfmTask = new LastWebAPITask(
TopTrackListActivity.this);
lfmTask.execute(metroTxt);
thanks to another forum. looks like the fastest and simple way to do this is using onResume():
#Override
public void onResume(){
super.onResume();
if(waitdialog != null){ //check if we are resuming (not coming from another activity)
if (waitdialog.isShowing()) { //check if is showing
waitdialog.dismiss(); //dismiss
}
}
}

Simple Socket example issue in Android

Can anyone let me know what is wrong in the below code.. Why is it not executing the while loop block?
I have the necessary permissions in the manifest file.
public class MainActivity extends Activity {
static TextView t;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.txt);
NetConnect th=new NetConnect();
th.start();
}
public class NetConnect extends Thread {
public void run(){
try{
runOnUiThread(new Runnable(){public void run(){t.append("Thread start...");}});
Socket client = new Socket("time-b.nist.gov", 13);
BufferedReader in =new BufferedReader(new InputStreamReader(client.getInputStream()));
String str;
while((str=in.readLine())!=null)
t.append(str);
}catch(Exception e){
Log.e("Internet:",e.toString());
}
}
}
There seems to be a problem with "time-b.nist.gov". I tried the following simple socket example in a java project (to simplify against creating an Android project):
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestSocketClass {
public static void main(String[] args) {
String hostname = "time-b.nist.gov";
try {
Socket theSocket = new Socket(hostname, 13);
InputStream timeStream = theSocket.getInputStream();
StringBuffer time = new StringBuffer();
int c;
while ((c = timeStream.read()) != -1)
time.append((char) c);
String timeString = time.toString().trim();
System.out.println("It is " + timeString + " at " + hostname);
} // end try
catch (UnknownHostException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Nothing returned if String hostname = "time-b.nist.gov";:
It is at time-b.nist.gov
but if I change it to String hostname = "time.nist.gov"; I get:
It is 56438 13-05-26 11:49:57 50 0 0 809.9 UTC(NIST) * at
time.nist.gov

Categories

Resources