Can I search devices and computers in the same wifi network? - android

I'm trying to search for devices and equipment which are connected to the same wifi network to which my device is connected. I using the following code but until now I haven't had any success
new AsyncTask<Void, Void, Boolean>() {
URL[] urls;
URL proveUrl;
HttpURLConnection con;
private boolean next(int position){
if (position++ < urls.length){
try {
proveUrl = new URL(urls[position].getHost() + ":36000");
} catch (MalformedURLException e) {
Toast.makeText(SDCardImagesActivity.this, "Malformed URL", Toast.LENGTH_SHORT).show();
}
return true;
}else{
return false;
}
}
#Override
protected void onPreExecute() {
wifiManager.getScanResults().toArray(urls);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
proveUrl =new URL(urls[0].getHost() + ":36000");
} catch (MalformedURLException e) {
Toast.makeText(SDCardImagesActivity.this, "Malformed URL", Toast.LENGTH_SHORT).show();
}
return prove();
}
#Override
protected void onProgressUpdate(Void... values) {
direccionIp = proveUrl.getHost();
super.onProgressUpdate(values);
}
private Boolean prove(){
int position = 0;
try {
con = (HttpURLConnection) proveUrl.openConnection();
BufferedInputStream req = new BufferedInputStream(con.getInputStream());
} catch (IOException e) {
if (next(position)){
position++;
prove();
}else{
return false;
}
}
return true;
}
};
Somebody knows how to do this? Thanks

Related

Android with AsyncTask

Hi every oneI'm new in android
I'm trying to save a binary file with Asynctask and show process in a TextView
This is the layout:
<TextView
android:id="#+id/textView_pecent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
And this is my java code:
private class hideit extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... urls) {
try{
int c;
while((c = Data.read()) != -1) {
Data.write(c);
}
}catch (IOException e){
e.printStackTrace();
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
textview.setText(INTEGER.toStirng(x)); //x =0
x++
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getActivity(),"Done", Toast.LENGTH_LONG).show();
}
}
How do i use publish process?
I searched a lot but everyone use sleep or for or while loop but you can't do your process with sleep
I'm so confused how can i use this function to show my process in TextView?
Should i call it many times?
Thanks
edit:
This is an example:
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
How can i add below code to the example
try{
int c;
while((c = Data.read()) != -1) {
Data.write(c);
}
}catch (IOException e){
e.printStackTrace();
}
return true;
}

Check if URL exists or not on Server

This is my code which I am using to verify, URL exists or not on Server, but always getting not exist however link is alive
Where I am doing mistake in my code, why I am always getting "doesnot exist !"
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
boolean bResponse = exists(customURL);
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
You will get Network On Main Thread Exception
Look at NetworkOnMainThreadException
so your method always returns false because of:
catch (Exception e) {
e.printStackTrace();
return false;
}
quick fix:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
MyTask task = new MyTask();
task.execute(customURL);
}
private class MyTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
boolean bResponse = result;
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
}
}
With a ScheduledThreadPoolExecutor:
but remember to shut down it!!
public class MainActivity extends Activity {
String customURL;
String msg = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(customURL).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
msg = "File exist!";
}else{
msg = "File does not exist!";
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
e.printStackTrace();
return;
}
}
}, 0,10000, TimeUnit.MILLISECONDS);
}
Change your exists() to this
public boolean exists(String url){
HttpURLConnection huc = ( HttpURLConnection ) url.openConnection ();
huc.setRequestMethod ("GET"); //OR huc.setRequestMethod ("HEAD");
huc.connect () ;
int code = huc.getResponseCode() ;
System.out.println(code);
if(code==200)
return true;
else
return false;
}
Use if(bResponse) instead of if(bResponse==true)
you can use the follow code to try.
final String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
URL url = new URL(customURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
con.connect();
Log.i(TAG, "con.getResponseCode() IS : " + con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
Log.i(TAG, "Sucess");
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "fail");
}
}
}.start();
Reason: After android 2.3, you can't perform a networking operation on its main thread,
if you do so, there will be can exception and you can't get the right result.
So if you want the application to perform a networking operation, you can use another Thread to do it.
I use this code to verify url alive. I have tested this code with image url
Example:
url = "https://ima.vn/wp-content/uploads/2017/11/ima-sofa-titan-trungkinh-1-of-3.jpg"
message = "Image url";
public void assertUrlalive(String url, String message) {
try {
URL myUrl = new URL(url);
HttpURLConnection huc = (HttpURLConnection) myUrl.openConnection();
assertEquals(huc.getResponseCode(), 200, message);
} catch (IOException e) {
e.printStackTrace();
logger.error("Connection Err: " + e.getMessage());
}
}

How to use multiple AsyncTasks

I'm coding the client side of an Android application which uses sockets. Since I'm new with AsyncTask, I coded something simple to test my understanding. Here is what I have, it seems to be correct:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Boolean> {
String mex;
#Override
protected Boolean doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
Socket connection= new Socket(local , 7100);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
DataInputStream input = new DataInputStream(connection.getInputStream());
mex= input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch(Exception e){
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
}
When the connection to the server is established, the client sends a test meesage and the server should send the same message to the client, where it is printed.
But my task is to establish the connection immediatly when the app is opened and send a message only when the button "send" is pressed. Is possible to create multiple AsyncTasks and make them work at the same time without crashing the application? If yes, can you please post an example of how can I do this?
EDITED CODE
This is my new code:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
CliccaInvia asd123 = new CliccaInvia();
asd123.execute(connection);
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Socket> {
String mex;
#Override
protected Socket doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
connection= new Socket(local , 7100);
DataInputStream input = new DataInputStream(connection.getInputStream());
mex = input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return connection;
}
#Override
protected void onPostExecute(Socket result) {
super.onPostExecute(result);
if(result != null){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
private class CliccaInvia extends AsyncTask<Socket, Void, Boolean>{
#Override
protected Boolean doInBackground(Socket... params) {
try {
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Message Sent"));
aggiornaScroll();
}
else{
mLayout.addView(createNewTextView("Error sending Mex "));
aggiornaScroll();
}
}
}
But this doesn't work.. :(
Well if you need to spawn a lot of tasks and keep track of them all you could do something like this
List<LavoraDietro> tasks = new ArrayList<LavoraDietro>();
LavoraDietro task = new LavoraDietro();
task.execute;
tasks.add(task);
then in your LavoraDietro in the onPostExecute
tasks.remove(this);
But there is a million different ways you could make connections if you want. I recommend Apache's library. http://hc.apache.org/httpclient-3.x/
Here is an example of how you might make a connection, just call this function from inside the background of your task.
public static InputStream getHTTPRequest(String url, ArrayList<NameValuePair> parameters, ArrayList<NameValuePair> headers)
{
final String TAG = "getHTTPRequest";
HttpGet getRequest = new HttpGet(url);
// attach all and any params
if (parameters != null && parameters.size() > 0)
{
HttpParams params = getRequest.getParams();
for (NameValuePair param : parameters)
{
params.setParameter(param.getName(), param.getValue());
}
getRequest.setParams(params);
}
// attach all and any headers
if (headers != null && headers.size() > 0)
{
for (NameValuePair header : headers)
{
getRequest.addHeader(header.getName(), header.getValue());
}
}
getRequest.addHeader("Content-type", "application/json");
getRequest.addHeader("Accept", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
try
{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.d(TAG, "status not ok");
Log.d(TAG, "status = " + Integer.toString(statusCode));
Log.d(TAG, "url = " + getRequest.getURI().toString());
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d(TAG, "returning valid content");
return getResponseEntity.getContent();
} catch (IOException e)
{
Log.d(TAG, "IOException: getRequest.abort");
getRequest.abort();
}
return null;
}

Dismiss Progress Dialog and handle exception in AsyncTask

I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?
Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}
You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}
#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}
first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions
private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}

How to implement ASyncTask in Android

Can anybody tell me how to update the UI using ASyncTask and give an example?
I am getting the value from two webservices. From two webservices I am getting value in two arraylist on post method will not return value it will rounding in loop. How do I return from onPostExecuteMethod?
This is my async class:
public class HomeTask extends AsyncTask<Void,Void,Bundle>
{
private Context ctx;
public HomeTask(Context context) {
ctx = context;
}
#Override
protected void onPreExecute() {
//super.onPreExecute();
//setContentView(R.layout.splash);
dlg = new ProgressDialog(getDialogContext());
dlg.setMessage("Loading....");
dlg.show();
//setContentView(R.layout.splash);
}
#Override
protected Bundle doInBackground(Void... params) {
Bundle b=new Bundle();
// TODO Auto-generated method stub
try
{
WebService tableservice=new WebService();
tableservicevalue=tableservice.callTableServer(SOAP_ACTION,"",strUsername,strPassWord,questGroupId,URL);
tableservicevalue=decodeXMLData(tableservicevalue);
DomTableParser parser=new DomTableParser();
parser.setTableservicevalue(tableservicevalue);
parsedValue=parser.parseXmlFile(tableservicevalue);
Log.d("1234%%%%$$$$$$$parsed value$$$$$", parsedValue.toString());
WebService service=new WebService();
webservicevalue=service.callHomeServer(SOAP_ACTION,"",strUsername,strPassWord,questGroupId,URL);
webservicevalue=decodeXMLData(webservicevalue);
ArticleParser articleParser=new ArticleParser();
articleParsedValue=articleParser.parseXmlArticle(webservicevalue);
//b.putStringArrayList("articleParsedValue", articleParsedValue);
Log.d("(((((((parsed value is",parsedValue.toString());
b.putStringArrayList("parsedValue", parsedValue);
b.putStringArrayList("articleParsedValue", articleParsedValue);
Log.d("(((((((parsed value is",articleParsedValue.toString());
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return b;
}
#Override
protected void onPostExecute(Bundle b) {
Log.d("vijay checking","checking&&&&");
Log.d("****","*********");
Log.d("calling","handler");
Log.d("****","*********");
parsedValue1=b.getStringArrayList("parsedValue");
articleParsedValue1=b.getStringArrayList("articleParsedValue");
}
onupdating user interface
new HomeTask(HomeActivity2.this).execute(null);
for(int i=0;i<parsedValue1.size();i++)
{
DomParserTableDataSet dataSet=(DomParserTableDataSet)parsedValue1.get(i);
if(i==0)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex0.setText(dataSet.getIndexName());
txtlast0.setText(dataSet.getLastValue());
txtchange0.setText(dataSet.getChangePercentage());
}
if(i==1)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex1.setText(dataSet.getIndexName());
txtlast1.setText(dataSet.getLastValue());
txtchange1.setText(dataSet.getChangePercentage());
}
if(i==2)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex2.setText(dataSet.getIndexName());
txtlast2.setText(dataSet.getLastValue());
txtchange2.setText(dataSet.getChangePercentage());
}
if(i==3)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex3.setText(dataSet.getIndexName());
txtlast3.setText(dataSet.getLastValue());
txtchange3.setText(dataSet.getChangePercentage());
}
}
//
for(int i=0;i<articleParsedValue1.size();i++)
{
System.out.println("for loop checking i is"+i);
ArticleDataSet articleDataset=(ArticleDataSet)articleParsedValue1.get(i);
System.out.println("articleDataset.getArticle_title()"+articleDataset.getArticle_title());
HashMap<String, String> mapValue=new HashMap<String, String>();
WebView webviewcontent=new WebView(HomeActivity2.this);
if(articleDataset.getArticle_summary().length()>75)
{
summary=articleDataset.getArticle_summary().substring(0,75)+"...";
}
else
{
summary=articleDataset.getArticle_summary();
}
String html ="<html><body><div><label> <font face=\"verdana\" color=\"#C1002B\" size=\"4\"><b>"+articleDataset.getArticle_title()+"</b> </font> </label>"+ "<label> <font color=\"#000000\" size=\"2\" face=\"verdana\">"+"|"+"</font></label> "+"<label> <font color=\"#AAAAAA\" face=\"verdana\" size=\"2\">"+articleDataset.getArticle_date()+" </font></label></div>";
html=html+"<div><label> <font color=\"#000000\" face=\"verdana\" size=\"2\">"+summary+" </font></label></div></body></html>" ;
webviewcontent.getSettings().setJavaScriptEnabled(true);
webviewcontent.clearCache(true);
final Activity activity = HomeActivity2.this;
webviewcontent.loadData(html, "text/html", "utf-8");
if(i==articleParsedValue1.size()-1)
{
webviewcontent.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url)
{
// setContentView(R.layout.home);
if (dlg.isShowing())
{
dlg.dismiss();
dlg = null;
}
splash.setVisibility(View.GONE);
// setContentView(repl);
}
});
}
mainlinear4.addView(webviewcontent);
//webviewcontent.setOnTouchListener(HomeActivity2.this);
}
}
List<String> data; // declare here so that we can use it in onPostExecute().
public class YourActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
starttask();
}
private void starttask() {
new FileAsync().execute("start");
Toast toast = Toast.makeText(yourActivity.this," start:" , 7);toast.show();
}
class FileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressDialog = ProgressDialog.show(yourActivity.this,
"", "Loading ...", true);
}
#Override
protected String doInBackground(String... aurl) {
// These methods are calling data from web service made
// in sperate class but you can do this here as well.
TempDAO tempDAO = new TempDAOImpl();
data = tempDAO.getDataList(arg1,arg2);
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
}
#Override
protected void onPostExecute(String unused) {
TextView textData= new TextView(YourActivity.this);
textData.setText(data.get(1));
textData.setTextColor(Color.WHITE);
textData.setGravity(Gravity.CENTER);
setContentView(textData);
m_ProgressDialog.dismiss();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
AlertDialog.Builder builder;
protected void onPreExecute() {
super.onPreExecute();
builder = new AlertDialog.Builder(TabGroup2ProductsActivity.this);
}
#Override
protected String doInBackground(String... urls) {
if (urls.length == 1) {
return POST(urls[0]);
} else {
if ("pdf".equalsIgnoreCase(urls[1])) {
downloadPDF(urls[0]);
return "";
} else {
downloadImage(urls[0]);
return "";
}
}
}
#Override
protected void onPostExecute(String result) {
}
}
public String POST(String url) {
System.out.println("I am in post data./..............................");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
System.out.println("Status is : " + status);
ParseProductJson parseJson = new ParseProductJson();
if (status == 200) {
result = EntityUtils.toString(response.getEntity());
System.out
.println("################result1###############################"
+ result);
FileOutputStream fos = openFileOutput("productsJson.json",
Context.MODE_PRIVATE);
fos.write(result.getBytes());
fos.close();
System.out.println("Done");
HashMap<String, List<Product>> hashmap = parseJson
.parseProductJson(readProductsJSON("productsJson.json"));
arrGroupelements = parseJson.getHeadingArray(hashmap);
arrChildelements = parseJson.get2dArray(hashmap);
statusClass = status;
} else {
statusClass = 400;
result = "Did not work!";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
and from Activity onCreate(){
int statusClass = 2;
new HttpAsyncTask()
.execute("http://104.130.240.26:8080/bhn/service/products/");
do {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (statusClass == 2);
}
Sample Async task to request webservice
Following is the way how to make AsyncTask :
private class AsyncTaskGetPlaces extends AsyncTask<Void, Void, AsyncTaskResult<Object>>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected AsyncTaskResult<Object> doInBackground(Void... params)
{
try
{
LibHttp libHttp = new LibHttp();
String res = libHttp.listBusiness("21","test#ns.com");
return new AsyncTaskResult<Object>(res);
}
catch (Exception e)
{
e.printStackTrace();
return new AsyncTaskResult<Object>(e);
}
}
#Override
protected void onPostExecute(AsyncTaskResult<Object> result)
{
if(result.getError()!= null)
{
showOKAlertMsg("App",getResources().getString(R.string.txt_data_not_found), false);
}
else
{
String res = result.getResult().toString();
try {
JSONObject resObj = new JSONObject(res);
if(resObj.getString("status_code").equals("1")){
//parse
// Do your task here
}
} catch (JSONException e) {
e.printStackTrace();
showOKAlertMsg("",getResources().getString(R.string.txt_internal_server_error), false);
}
}
}
}
Where AsyncTaskResult is
public class AsyncTaskResult<T>
{
private T result;
private Exception error;
public T getResult()
{
return result;
}
public Exception getError()
{
return error;
}
public AsyncTaskResult(T result)
{
this.result = result;
}
public AsyncTaskResult(Exception error)
{
this.error = error;
}
}

Categories

Resources