I am making an application where i need to take the input from the user and append that input with the string and use that as a url for data parsing
But the edit text content is null even though i am entering text in edittext
I converted edittext content to string as below
EditText edit = (EditText)findViewById(R.Id.tv5);
And inside onclicklistener
String data = edit.getText().toString();
Can anybody tell me why the data.length() is giving me zero?
my complete main activity is below:
public class Pnr extends Activity {
EditText edit;
TextView text1;
Button button;
String pnr, check;
HttpClient client;
JSONObject json;
int s;
String URL = "pnrbuddy.com/pnrstatus=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pnr);
edit = (EditText) findViewById(R.id.tv5);
text1 = (TextView) findViewById(R.id.textView2);
button = (Button) findViewById(R.id.button1);
client = new DefaultHttpClient();
pnr = String.valueOf(edit.getText());
s = pnr.length();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Read().execute("trainNo");
}
});
}
public JSONObject pnrStatus(String key) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(key);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
JSONObject last = new JSONObject();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
last = new JSONObject(data);
return last;
} else {
return last;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = pnrStatus(pnr);
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return s + "";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
text1.setText(" " + result);
}
}
}
when i enter the string instead of accepting from edittext in the string URL along with the exsisting string the code works
URL="pnrbuddy/pnrstatus=myText";
why i m unable to get string from editText?
try with this
EditText edit = (EditText)findViewById(R.id.tv5);
String data = edit.getText().toString();
If you are try to get length in onclicklistener in EditText it will give u 0 only.In this case try to get from onTextChange.
Replace your on create method by this n try
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pnr);
edit = (EditText) findViewById(R.id.tv5);
text1 = (TextView) findViewById(R.id.textView2);
button = (Button) findViewById(R.id.button1);
client = new DefaultHttpClient();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pnr =edit.getText().toString();
s = pnr.length();
new Read().execute("trainNo");
}
});
}
Actually your getting text when the activity is created not when button is clicked, So placing the gettext code in onclick method would resolve your problem
Related
My purpose is simple,I want to creat a countdown that count from 10 to 1.I have tried using countdown given by google but I can't make it as a thread,so I use this way to creat the same function but I had a problem with this code.My app getting crashed when I use this threads code.Please help me man.
public class MainActivity extends Activity {
TextView textView;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
String string = textView.getText().toString();
int num = Integer.parseInt(string);
num = num-1;
string = Integer.toString(num);
textView.setText(string);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
for(int i = 10; i>0;i--){
try {
Thread.sleep(1000);
//handler.sendMessage(handler.obtainMessage());
handler.sendMessage(handler.obtainMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
myThread.start();
}
}
Your problem isnt with the thread, its with these lines
String string = textView.getText().toString();
int num = Integer.parseInt(string);
You probably have that textView starting out with some text in the XML("Large Text"). Remove it. "Large Text" isn't a number, so when you call parseInt() on that original string its trying to convert "Large Text" to a number.
Try this code:
try {
String string = textView.getText().toString();
int num = Integer.parseInt(string);
textView.setText(String.valueOf(--num));
catch(NumberFormatException ignored){
}
with a try/catch block
this is my LoginActivity class, i want to do add remember me option to this class.
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_email);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxx/xxxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
After some research I was able to come up with this code to do the remember me option using shared preference.
public class MainActivity extends Activity {
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#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;
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void doLogin(View view) {
EditText txtuser = (EditText) findViewById(R.id.txt_user);
EditText txtpwd = (EditText) findViewById(R.id.txt_pwd);
String email = "u";
String password = "p";
if (txtuser.getText().toString().equals(email)
&& txtpwd.getText().toString().equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email and password
// show logout activity
showLogout(email);
} else {
Toast.makeText(this, "Invalid email or password", Toast.LENGTH_LONG)
.show();
}
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
}
I need help to integrate these 2 classes. I tried but didn't work
this is my out put
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_user);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email
// and
// password
// show logout activity
showLogout(email);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxxx/xxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I parsed json to adapt for my autocompleteTextView. I tried to match the value parsed by my json object with the value entered by user.
But some where i am failing. please help me in matching these values.
i have to match the string(acity) that is entered by user with my parsed json value stored in responseList.
This is how i am trying.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
final List<String> responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
So lets assume you need to match a certain city before you intent to a map :
private final List<String> responseList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
for(int i=0; i<responseList.size(); i++) {
if(responseList.get(i).equals(aCity)) {
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
}
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
It should be something like that if I didnt guess your intent wrongly.
I want to retrieve array of string from my webservice and have to show it in my android project in Toast I coded it like this but its not showing anything can anyone please help me out :(
public class InsertData extends MainActivity {
EditText txt_1,txt_2;
Button SetData,GetData;
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://10.0.2.2:49371/WebService1.asmx";
private static String SOAP_ACTION = "http://tempuri.org/GetData";
private static String SOAP_ACTION2 = "http://tempuri.org/ThrowData";
private static String METHOD_NAME = "GetData";
private static String METHOD_NAME2 = "ThrowData";
String DateTime;
String IMEI;
//private static String[] arrString = new String[40];
Long time = (long) 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.setdata);
txt_1 = (EditText) findViewById (R.id.editText1);
txt_2 = (EditText) findViewById (R.id.editText2);
SetData = (Button) findViewById(R.id.button1);
GetData = (Button) findViewById(R.id.button2);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy : HH:mm:ss");
DateTime = df.format(c.getTime());
txt_1.setText(DateTime);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
txt_2.setText(IMEI);
}
public void OnClickGetData(View view){
final Handler hnd = new Handler();
final Runnable r = new Runnable(){
public void run(){
SoapObject obj = new SoapObject(NAMESPACE,METHOD_NAME2);
SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelop.setOutputSoapObject(obj);
HttpTransportSE androidHTTP = new HttpTransportSE(URL,7000);
try{
androidHTTP.call(SOAP_ACTION2, envelop);
}catch(IOException e){
e.printStackTrace();
}catch(XmlPullParserException e){
e.printStackTrace();
}
try {
#SuppressWarnings("unchecked")
java.util.Vector<String> result11 = (java.util.Vector<String>)envelop.getResponse(); // to get List of Strings from the SoapObject.. then
final ArrayList<String> prjList = new ArrayList<String>();
for(String cs : result11)
{
prjList.add(cs);
}
hnd.post(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i <prjList.size();i++){
//arrString[i] = reques.toString();
String Nu = prjList(i).toString();
Toast.makeText(InsertData.this,Nu , Toast.LENGTH_LONG).show();
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
} catch (SoapFault e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
public void OnClickSetData(final View view)
{
final Handler hnd = new Handler();
final Runnable ru = new Runnable(){
//#SuppressWarnings("deprecation")
#Override
public void run() {
// TODO Auto-generated method stub
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
PropertyInfo pi2 = new PropertyInfo();
pi.namespace = NAMESPACE;
pi.setName("Date");
pi2.setName("IMEI_NO");
pi.setValue(DateTime);
pi2.setValue(IMEI);
pi.setType(String.class);
pi2.setType(String.class);
request.addProperty(pi);
request.addProperty(pi2);
SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelop.dotNet = true;
envelop.setOutputSoapObject(request);
HttpTransportSE androidHttp = new HttpTransportSE(URL,7000);
try
{
androidHttp.call(SOAP_ACTION, envelop);
}
catch(IOException e)
{
e.printStackTrace();
}
catch (XmlPullParserException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(ru).start();
}
}
and here is my webservice which is made in .NET its retriving data when i m retrieving it in my browser but not showing in android application
public string[] ThrowData()
{
string ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
SqlCommand cmd = new SqlCommand();
List<string> data = new List<string>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
cmd.CommandText = "SELECT IMEI_NO FROM MAD";
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
data.Add(dr["IMEI_NO"].ToString());
}
}
return data.ToArray();
}
Have a Log statement to see if its entering the loop and is receiving the expected value. If it does that but does not show the Toast, its because you are not showing the Toast on the UI thread. If you want to show any change on the UI, you need to do them in UI thread. To show toast here, you may use runOnUiThread. Eg:
YourActivityName.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(InsertData.this,Nu , Toast.LENGTH_LONG).show();
}
});
Edit:
For knowing more about Log statements see Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one? and http://developer.android.com/reference/android/util/Log.html
Hope this helps.
I have an HTTP GET that is receiving information from a URI. The URI is for Google Shopping.
https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom
(Left my key out).
Is there a way that I can change it from
q=digital+camera
to anything a user puts in an EditText?
So basically, I want the EditText to change what is searched on Google Shopping.
First screen, ProductSearchEntry with EditText for search query:
Code for ProductSearchEntry
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
startActivity(searchIntent);
}
});
}
}
Then, I have a second class, ProductSearch, with no picture, but just this code:
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Which references the ProductSearchMethod class which consists of a TextView that is changed to the code recieved in the HTTP GET:
Code:
public class ProductSearchMethod {
public String getSearchData(String query) throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
HttpGet request = new HttpGet();
request.setURI(site);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
ProductSearchMethod comes up great, but it doesn't change the text from "Loading Items" to the website code. I had it working before but then I tried to edit what it searched (all this ^) and now it doesn't change.
Make changes in your code like
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
EditText etSearch = (EditText) findViewById(id of your edittext);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//while calling intent
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
searchIntent.putExtra("searchText",etSearch.getText().toString());
startActivity(searchIntent);
}
});
}
}
and another activity like this,
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
String searchQuery = getIntent().getStringExtra("searchText");
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery);
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Yeah... Change your getSearchData() method to include a string as a parameter
public String getSearchData(String query) throws Exception{
Then, insert that string into the query URL, replacing spaces with "+". You may want to do further conditioning to the string, for instance URL encoding it.
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
In your XML, create a button that contains the following line:
android:onClick="search"
In your ProductSearch activity, add the following method, and move the code in onCreate into it. You will also need to create an EditText in your XML for input.
public void search(View v)
{
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String returned;
try {
returned = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Finally, you will probably want to read up on running asynchronous tasks so that the query won't freeze your app while performing.
May be I got you wrong, but why don't you just pass it as a parameter in
getSearchData() => getSearchData(string query)
Then you can change the line
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom");
to
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=+ URLEncoder.encode(query, "UTF-8")+&alt=atom");
Check out http://androidforums.com/developer-101/528924-arduino-android-internet-garage-door-works-but-could-use-input.html I use Asynctask to trigger a get command on a local Arduino server. It appends the Arduino's pin number and, depending on if it's needed, a port number to the end of the URL. I'm sure you could use it to help you out.