sorry to be a pain, but I've been on this one too long and I am sure it's a easy one but I am tired and can't see it. All works fine but the 'String result' is empty
package com.example.me;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnLoginButton;
TextView tmpError, tmpUsername, tmpPassword;
ArrayList<NameValuePair> postParameters;
String response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tmpError = (TextView) findViewById(R.id.lblMessage);
tmpUsername = (TextView) findViewById(R.id.txtUsername);
tmpPassword = (TextView) findViewById(R.id.txtPassword);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
btnLoginButton = (Button) findViewById(R.id.btnLogin);
btnLoginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg) {
try{
triggerClick();
}
catch (Exception e) {
tmpError.setText("[]" + e.toString());
}
}
});
}
private void triggerClick() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", tmpUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", tmpPassword.getText().toString()));
final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
#Override
protected String doInBackground(String... params) {
publishProgress(true);
try {
response = CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
publishProgress(false);
result = result.replaceAll("\\s+","");
if(result.equals("1")) {
tmpError.setText("Correct");
}
else {
tmpError.setText("Sorry!!("+result+")");
}
}
}
new HttpTask().execute();
}
}
come back time and time again with an empty "result" string :-(
because in the doInBackground() you return empty string, you should do:
protected String doInBackground(String... params) {
publishProgress(true);
try {
return CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
The string result is empty because you're returning an empty string from doInBackground().
return "";
Please Declare String response; as a global variable.
protected String doInBackground(String... params)
{
publishProgress(true);
try
{
response=CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
}
catch (Exception e)
{
e.printStackTrace();
}
}
Related
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.
I have two seekbars in my main activity but I can only use one of them at a time, so I need to retrieve a value seekbarx and seekbary, store either of them in a string variable to use it forward. I already used onProgressChange and onStopTrackingTouch but I guess it doesn't hold the value long enough.
This is what I had for the seekbars
package edu.itdurango.servocontrolyun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
// TODO: adjust ARDUINO_IP_ADDRESS
public final String ARDUINO_IP_ADDRESS = "192.168.1.71"; //Dirección IP del Arduino Yun
public final String TAG = "ArduinoYun";
public String servo;
private SeekBar SeekBarX; //Barra de búsqueda del eje X
private SeekBar SeekBarY; //Barra de búsqueda del eje Y
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBarX = (SeekBar) findViewById(R.id.barraEjeX);
/*SeekBarX.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeX) {
servo = "servox/";
}
});*/
SeekBarX.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onProgressChanged(SeekBar barraEjeX, int progressX,
boolean fromUser) {
servo = "servox/";
log("touching X bar. servo = " + servo);
QueueX.offer(progressX);
}
});
SeekBarY = (SeekBar) findViewById(R.id.barraEjeY);
/*SeekBarY.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeY) {
servo = "servoy/";
}
});*/
SeekBarY.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onProgressChanged(SeekBar barraEjeY, int progressY,
boolean fromUser) {
servo = "servoy/";
log("touching Y bar. servo = " + servo);
QueueY.offer(progressY);
}
});
}
#Override
protected void onStart() {
mStop.set(false);
if(sNetworkThreadSend == null){
sNetworkThreadSend = new Thread(mNetworkRunnableSend);
sNetworkThreadSend.start();
}
super.onStart();
}
#Override
protected void onStop() {
mStop.set(true);
QueueX.clear();
QueueX.offer(-1);
QueueY.clear();
QueueY.offer(-1);
if(sNetworkThreadSend != null) sNetworkThreadSend.interrupt();
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void log(String s){
Log.d(">==< "+TAG+" >==<", s);
}
private ArrayBlockingQueue<Integer> QueueX = new ArrayBlockingQueue<Integer>(100);
private ArrayBlockingQueue<Integer> QueueY = new ArrayBlockingQueue<Integer>(100);
private AtomicBoolean mStop = new AtomicBoolean(false);
private static Thread sNetworkThreadSend = null;
private final Runnable mNetworkRunnableSend = new Runnable() {
#Override
public void run() {
log("starting network thread for sending");
String urlBase = "http://"+ARDUINO_IP_ADDRESS+"/arduino/"+servo;
String url;
try {
while(!mStop.get()){
int val;
if (servo == "servoy/"){
val = QueueY.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
if (servo == "servox/"){
val = QueueX.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
log("returning from network thread for sending");
sNetworkThreadSend = null;
}
};
private static Thread sNetworkThreadReceive = null;
private final Runnable mNetworkRunnableReceive = new Runnable() {
#Override
public void run() {
log("starting network thread for receiving");
String url = "http://"+ARDUINO_IP_ADDRESS+"/data/get/D9";
while(!mStop.get()){
try {
String string = readURL(url);
String value = "";
try {
JSONObject jsonMain = new JSONObject(string);
value = jsonMain.get("value").toString();
log("value = "+value);
} catch (Exception e) {
e.printStackTrace();
}
updateText(value);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log("returning from network thread for receiving");
sNetworkThreadReceive = null;
}
};
public void updateText(final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(value);
}
});
}
public String readURL(String value){
URL url;
StringBuilder builder = new StringBuilder();
try {
url = new URL(value);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
builder.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
It prints in the LogCat touching Y bar. servo = servoy/ but when I want to use the servo value it prints null.
How can I hold the value for this string?
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import sereen.sql.Info;
import sereen.sql.InfoServicesNew;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class PenddingOrders extends Activity {
ArrayList<Info> info=new ArrayList<Info>();
int imgPendding=R.drawable.ex2;
ListView list;
ProgressDialog pd;
ArrayAdapter<String> adapter;
private String defValue = "N/A";
InfoServicesNew databaseHelper;
String name=InfoServicesNew.DB_TABLE_NAME;
static int img[]={R.drawable.ex2,R.drawable.ex2,R.drawable.ex2,R.drawable.ex2,
R.drawable.ex2,R.drawable.ex2,R.drawable.ex2,R.drawable.ex2, R.drawable.ex2,
R.drawable.ex2};
String data;
Intent o;
int position;
Object object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pendding_orders);
databaseHelper = new InfoServicesNew(this);
list=(ListView)findViewById(R.id.listView1);
pd = new ProgressDialog(this);
new asy().execute("http://jsonblob.com/api/jsonBlob/53021f22e4b0f9ce1677329a");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pendding_orders, menu);
return true;
}
public class asy extends AsyncTask<String, String, ArrayList<Info>>
{
#Override
protected ArrayList<Info> doInBackground(String... params) {
// TODO Auto-generated method stub
//activity is defined as a global variable in your AsyncTask
try {
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(params[0]);
HttpResponse hr = hc.execute(hg);
HttpEntity he = hr.getEntity();
data = EntityUtils.toString(he);
Log.i("data", data);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Info> sereenlist = new ArrayList<Info>();
sereenlist = getJSONData(data);
return sereenlist;
}
private ArrayList<Info> getJSONData(String data) {
// TODO Auto-generated method stub
ArrayList<Info> rs = null;
try {
JSONObject obj = new JSONObject(data);
JSONArray finalObj = obj.optJSONArray("orders");
for (int i = 0; i < finalObj.length(); i++)
{
final String orderNumber = finalObj.optJSONObject(i).optString(
"order-number");
final String orderAmount = finalObj.optJSONObject(i).optString(
"order-amount");
final String date = finalObj.optJSONObject(i).optString(
"date");
final String client = finalObj.optJSONObject(i).optString(
"client");
final String upperLimit = finalObj.optJSONObject(i).optString(
"upper-limit");
final String debt = finalObj.optJSONObject(i).optString(
"debt");
long id1=databaseHelper.insert(new Info(client,orderAmount,date ,orderNumber,upperLimit,debt));
// long id1 = databaseHelper.insert(info);
if(id1 < 0)
{
Toast.makeText(getApplicationContext(), "unsuccessfull add", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
// select all
}
rs = databaseHelper.selectAll();
databaseHelper.close();
Log.i("size", finalObj.length()+"");
}//try end
catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return rs;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.setTitle("fetching");
pd.setMessage("waiting...");
pd.show();
}
#Override
protected void onPostExecute(ArrayList<Info> result) {
// TODO Auto-generated method stub
SetAdapterList(result);
pd.dismiss();
}
private void SetAdapterList(ArrayList<Info> result)
{
// TODO Auto-generated method stu
CustomAdapter adapter=new CustomAdapter(getApplicationContext(),result);
list.setAdapter(adapter);
//
}
}
}
strong text what i want to do is to get all the JSON data from the link .. and it show in the logcat so i get it successfully .. and then i try to insert it in the database using dbhelper and info class which contain getter and setter for all values .. but each time i run the code here what i get :
02-19 01:09:34.490: E/AndroidRuntime(1210): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
You're calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});
First of all you have to get the JSON Data from network and store them in a structure.
So, the first step will be something like that . For json parsing i used Gson library. You have also to create a model class for your objects that you will receive from the requests.
private void getJSONModelHttpRequest(){
AsyncHttpClient asyncClient = new AsyncHttpClient();
asyncClient.get(YOUR_URL_HERE , new AsyncHttpResponseHandler(){
#Override
public void onStart(){
}
#Override
public void onSuccess(String response){
try {
JSONObject jsonObj = new JSONObject(response);
Gson gson = new Gson();
ModelClass model = gson.fromJson(jsonObj.toString() , ModelClass.class);
// store the models in a array list or something like that to have the data available in the future
Log.d(“Model”, " model = " +teamModel.getAnAtttributeVal);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable e,String response){
}
#Override
public void onFinish(){
// Your database insertions here
}
});
}
You can also call the Toast using handler itself, provided you use the handler's message passing feature.
What we do is pass the message which is your string using sendMessage() method inside your Thread,
handler.sendMessage(msgObj);
and tehn get the message inside the handler's handleMessage(Message msg) method using,
String aResponse = msg.getData().getString("message");
Complete example here.
in your code do it like this .first create a handler and send data to handler whatever you want to show
if(id1 < 0)
{
Message msg=new Message();
msg.obj=unsuccessfull add;
handle.sendMessage(msg);
}
Handler handle=new Handler(){
public void handleMessage(Message msg) {
String data=(String)msg.obj;
Toast.makeText(activity, data, Toast.LENGTH_SHORT).show();
}
};
i found out the problem .. it was because of the toast ... we can't make a toast inside doInBackground service .. my code worked just fine ..
I am beginner for Android. I want to send the data to my PHP page. but here i m trying to toast that post values. but there is no response. Plz help me.
My Code is:
public class send_msgActivity extends Activity{
//static final String KEY_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_msg);
Button btn_ok = (Button) findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText1 = (EditText)findViewById(R.id.sender);
String S_name = editText1.getText().toString();
EditText editText2 = (EditText)findViewById(R.id.reciever);
String S_email = editText2.getText().toString();
postData(S_name,S_email);
}
});
};
public void postData(String name,String email) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.URL.com/yourpage.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Fname", name));
nameValuePairs.add(new BasicNameValuePair("Femail", email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost, new BasicResponseHandler());
HttpResponse response = httpclient.execute(httppost);
String reverseString = response.toString();
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Use this example how to code HTTPpost method
package com.example.login;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpResponse;a
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class pdf extends Activity
{
public boolean connect=false,logged=false;
public String db_select;
ListView l1;
String mPwd,UName1="Success",UName,ret;
public Iterator<String> itr;
private String SERVICE_URL = "http://61.12.7.197:8080/Agero/person/pdf";
private String SERVICE_URL1 = "http://61.12.7.197:8080/Agero/person/url";
//private final String SERVICE_URL = "http://10.1.1.138:8080/Agero/person/pdf";
//private final String SERVICE_URL1 = "http://10.1.1.138:8080/Agero/person/url";
private final String TAG = "Course";
ArrayList<String> todoItems;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayAdapter<String> aa;
public List<String> list1=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf);
l1 = (ListView)findViewById(R.id.list);
todoItems = new ArrayList<String>();
aa = new ArrayAdapter<String>(this,R.layout.list_row,R.id.title,todoItems);
l1.setAdapter(aa);
todoItems.clear();
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user();
//display("hi");
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String name=(String)parent.getItemAtPosition(position);
/*Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show();
Intent i = new Intent(getBaseContext(),Webview.class);
i.putExtra("USERNAME", name);
startActivity(i);*/
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user1(name);
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
}
});
}
public void display(String msg)
{
Toast.makeText(pdf.this, msg, Toast.LENGTH_LONG).show();
}
private void validat_user()
{
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "");
// wst.addNameValuePair("State", stg1);
// wst.addNameValuePair("Emp_PWD", stg2);
// db_select=stg1;
//display("I am");
wst.execute(new String[] { SERVICE_URL });
//display(SERVICE_URL);
}
private void validat_user1(String stg1)
{
db_select=stg1;
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Loading...");
wst.addNameValuePair1("PDF_NAME", stg1);
wst.execute(new String[] { SERVICE_URL1 });
}
#SuppressWarnings("deprecation")
public void no_net()
{
display( "No Network Connection");
final AlertDialog alertDialog = new AlertDialog.Builder(pdf.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
//alertDialog.setIcon(R.drawable.error_info);
alertDialog.setCancelable(false);
alertDialog.setButton("Close", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.cancel();
pdf.this.finish();
System.exit(0);
}
});
alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
display( "Accessing local DataBase.....");
alertDialog.cancel();
}
});
alertDialog.show();
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
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 WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair1(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();
}
// Establish connection and socket (data retrieval) timeouts
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);
// Add parameters
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);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{ //display("JSON responce is : "+response);
if(!response.equals(""))
{
try {
JSONObject jso = new JSONObject(response);
int UName = jso.getInt("status1");
if(UName==1)
{
String status = jso.getString("status");
ret=status.substring(13,status.length()-2);
todoItems.add(0, status);
aa.notifyDataSetChanged();
}
else if(UName==-1)
{
String status = jso.getString("status");
//display(status);
Intent intObj=new Intent(pdf.this,Webview.class);
intObj.putExtra("USERNAME", status);
startActivity(intObj);
}
else
{
// int count=Integer.parseInt(UName);
// display("Number of Projects have been handling in AFL right now: "+count);
list1=new ArrayList<String>();
JSONArray array=jso.getJSONArray("reps1");
for(int i=0;i<array.length();i++)
{
list1.add(array.getJSONObject(i).getString("pdfName"));
}
itr=list1.iterator();
while(itr.hasNext())
{
//str1=itr.next()+"\n";
todoItems.add(0, itr.next().toString());
aa.notifyDataSetChanged();
}
//tv1.setText(str1);
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return;
}
}
else
{
display("unable to reach the server");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent intObj=new Intent(pdf.this, MainActivity.class);
intObj.putExtra("finish", true); // if you are checking for this in your other Activities
intObj.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intObj);
//pdf.this.finish();
finish();
return (true);
}
return super.onOptionsItemSelected(item);
}
}
I'm very new to android. I wanted to build client/server application, where client is running android and Server is running Java.
Clients code
package com.example.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.AsyncTask;
import java.io.*;
import java.net.*;
public class MainActivity extends Activity {
static String line= "works";
private MyTask mt;
private EditText nameField;
private TextView nameView;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameField =(EditText) findViewById(R.id.FirstInputField);
nameView =(TextView) findViewById(R.id.DisplayText);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mt=new MyTask();
mt.execute();
}
});
}
private class MyTask extends AsyncTask<Void, String, Void>
{
protected void onPreExecute()
{
}
#Override
protected Void doInBackground(Void... params) {
Socket s;
try {
s = new Socket ("172.17.20.42", 8888);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ios=new ObjectInputStream(s.getInputStream());
oos.writeObject(line);
oos.close();
ios.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This program works fine, but the problem is , that I'm sending static String.
doInBackground method does not have access to UI thread. The question is "How to send a strings, that are typed in UI?"
Thank you in advance
private class MyTask extends AsyncTask<Void, String, Void>
{
String line;
public MyTask(String line) {
this.line = line;
}
Then in onCreate():
public void onClick(View v) {
mt=new MyTask(nameView.getText().toString());
mt.execute();
}
Note: This is not the most efficient or memory-saving method as you instantiate a new MyTask object for each line that is sent, but is the method that demands less changes in your code as it is now.
In the on click of your button pass nameView.getText() to the MyTask, either in the constructor or the execute() method (will require you to accept the parameter as String... string and read it as string[0])
Make first generic parameter of MyTask of type String:
private class MyTask extends AsyncTask<String, String, Void>
{
protected void onPreExecute()
{
}
#Override
protected Void doInBackground(String... params) {
String stringToSend = params[0];
Socket s;
try {
s = new Socket ("172.17.20.42", 8888);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ios=new ObjectInputStream(s.getInputStream());
oos.writeObject(stringToSend);
oos.close();
ios.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
And pass the string parameter through execute:
mt.execute(new String[1] {nameField.getText().toString()});