how to call a web service in android [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need to call a web service from the url. wen i entered the no in the text box i should the output which i entered in text box. pls help me fixing the errors. here is my java code.
MainActivity.java
public class MainActivity extends Activity {
Button b;
TextView tv;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.tv_result);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
} else {
tv.setText("Please enter number");
}
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
displayText = ser.invokeiop(editText,"hello");
return null;
}
}
}
ser.java
public class ser {
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://my url";
private static String SOAP_ACTION = "srvice";
public static String invokeiop(String name, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo iop = new PropertyInfo();
iop.setName("name");
iop.setValue(name);
//iop.setType(String.class);
request.addProperty(iop);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
resTxt = response.toString();
} catch (Exception e) {
e.printStackTrace();
resTxt = "Error occured";
}

This might help you!!
public class MainActivity extends Activity {
Button b;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS();
} else {
// declare a toast
}
}
});
}
public void AsyncCallWS(final String q)
{
class HttpGetAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
String txtSearch = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("URL"+editText);
try
{
HttpResponse httpResponse = httpClient.execute(httpGet);
inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder strB = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null)
{
strB.append(bufferedStrChunk);
}
return strB.toString();
}
catch (ClientProtocolException cpe)
{
cpe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try {
// Parse your data here
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
httpGetAsyncTask.execute(editText);
}

Related

How to update values fetching from api at real time?

I making a quiz app in which i am displaying question and it's four option in radio buttons,i want to display question one by one by updating it to the next id question on a click of button.....How should i do that? and also how should i check score for it which i want to display on the next activity i will make? the app crashes on the listner of button
Thanks in advance!
QuizActivity:
public class Quiz extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton optionOne,optionTwo,optionThree,optionFour;
private TextView questionName;
String question_name;
String option1,option2,option3,option4;
Button next_question;
int first_question_index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionName=(TextView)findViewById(R.id.question_name);
radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
optionOne=(RadioButton)findViewById(R.id.answerOne);
optionTwo=(RadioButton)findViewById(R.id.answerOne);
optionThree=(RadioButton)findViewById(R.id.answerOne);
optionFour=(RadioButton)findViewById(R.id.answerOne);
next_question=(Button)findViewById(R.id.button_next_question);
FetchLists fetchLists =new FetchLists();
fetchLists.execute(10,0);
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
first_question_index++;
}
}); }
public class FetchLists extends AsyncTask<Integer, Void, String> {
#Override
protected String doInBackground(Integer... params) {
String urlString = "http://aptronnoida.com/Aditya_July4/Demo/JAVA_FETCH.php";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("data");
JSONObject list = (JSONObject) jsonArray.get(first_question_index);
question_name= list.getString("Question");
option1=list.getString("A1");
option2=list.getString("A2");
option3=list.getString("A3");
option4=list.getString("A4");
} catch (Exception e) {
e.printStackTrace();
}
return "quiz";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
questionName.setText(question_name);
((RadioButton) radioGroup.getChildAt(0)).setText(option1);
((RadioButton) radioGroup.getChildAt(1)).setText(option2);
((RadioButton) radioGroup.getChildAt(2)).setText(option3);
((RadioButton) radioGroup.getChildAt(3)).setText(option4);
}
}
}
public class Quiz extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton optionOne,optionTwo,optionThree,optionFour;
private TextView questionName;
String question_name;
String option1,option2,option3,option4;
Button next_question;
int first_question_index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionName=(TextView)findViewById(R.id.question_name);
radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
optionOne=(RadioButton)findViewById(R.id.answerOne);
optionTwo=(RadioButton)findViewById(R.id.answerOne);
optionThree=(RadioButton)findViewById(R.id.answerOne);
optionFour=(RadioButton)findViewById(R.id.answerOne);
next_question=(Button)findViewById(R.id.button_next_question);
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
first_question_index++;
FetchLists fetchLists = new FetchLists();
fetchLists.execute(10, 0);
}
});
FetchLists fetchLists = new FetchLists();
fetchLists.execute(10, 0);
}
public class FetchLists extends AsyncTask<Integer, Void, String> {
#Override
protected String doInBackground(Integer... params) {
String urlString = "http://aptronnoida.com/Aditya_July4/Demo/JAVA_FETCH.php";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("data");
JSONObject list = (JSONObject) jsonArray.get(first_question_index);
Log.d("ashu","JsonObject "+list);
question_name= list.getString("Question");
option1=list.getString("A1");
option2=list.getString("A2");
option3=list.getString("A3");
option4=list.getString("A4");
} catch (Exception e) {
e.printStackTrace();
}
return "quiz";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
questionName.setText(question_name);
((RadioButton) radioGroup.getChildAt(0)).setText(option1);
((RadioButton) radioGroup.getChildAt(1)).setText(option2);
((RadioButton) radioGroup.getChildAt(2)).setText(option3);
((RadioButton) radioGroup.getChildAt(3)).setText(option4);
}
}
}

How to call Login Web Services in Android

I am new in android and try to develop android application for login system. I have written web services in Java for login and call it in android but I am not able to call these web services in android please help me.
My Java Web Services:-
public class Login {
public String authentication(String userName,String password){
String retrievedUserName = "";
String retrievedPassword = "";
String status = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin","root","root");
PreparedStatement statement = con.prepareStatement("SELECT * FROM user WHERE username = '"+userName+"'");
ResultSet result = statement.executeQuery();
while(result.next()){
retrievedUserName = result.getString("username");
retrievedPassword = result.getString("password");
}
// System.out.println(retrievedUserName);
// System.out.println(retrievedPassword);
if(retrievedUserName.equals(userName)&&retrievedPassword.equals(password)){
status = "Success!";
}
else{
status = "Login fail!!!";
}
}
catch(Exception e){
e.printStackTrace();
}
return status;
}
}
My android mainActivity is:-
public class MainActivity extends Activity {
private final String NAMESPACE = "http://ws.webapp.org/";
private final String URL = "http://localhost:8086/WebApp/services/Login?wsdl";
private final String SOAP_ACTION = "http://ws.webapp.org/authentication";
private final String METHOD_NAME = "authentication";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction() {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText userName = (EditText) findViewById(R.id.tf_userName);
String user_Name = userName.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
// Pass value for userName variable of the web service
PropertyInfo unameProp = new PropertyInfo();
unameProp.setName("userName");// Define the variable name in the web
// service method
unameProp.setValue(user_Name);// set value for userName variable
unameProp.setType(String.class);// Define the type of the variable
request.addProperty(unameProp);// Pass properties to the variable
// Pass value for Password variable of the web service
PropertyInfo passwordProp = new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
} catch (Exception e) {
}
}
}
In android many ways you can call a web service
Volley
Retrofit
HTTP URL Connection
Volley Example
private void callWebServicePost() {
String postUrl = "http://URL";
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, postUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("inc_id", "0");
params.put("device_date", "");
params.put("device_name", "");
params.put("mac_address", "");
return params;
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
Retrofit Post Example
private void RetroWebServicePost() {
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http:/URL").build();
WeatherInterface weatherInterface = restAdapter.create(WeatherInterface.class);
weatherInterface.getAttendance(new Callback<AttendancePojo>() {
#Override
public void success(AttendancePojo attendancePojo, retrofit.client.Response response) {
try {
Attendance_data data[];
data = attendancePojo.getPostModel().getAttendance_data();
List<String> attendence = new ArrayList<>();
for (int i = 0; i < data.length; i++) {
attendence.add(data[i].toString());
}
Log.e("response", attendence.toString());
reponseData.setText(attendence.toString());
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
HTTP Url connection post Example
private void reqPost() throws IOException {
String postWebUrl = "http:URL";
URL url = new URL(postWebUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
String urlParameters = "inc_id=" + URLEncoder.encode("0", "UTF-8")
+ "&device_date="
+ URLEncoder.encode("", "UTF-8")
+ "&device_name="
+ URLEncoder
.encode("",
"UTF-8") + "&mac_address="
+ URLEncoder.encode("", "UTF-8");
//SEND REEQUEST
DataOutputStream dataOutputStream = new DataOutputStream(
connection.getOutputStream());
dataOutputStream.writeBytes(urlParameters);
dataOutputStream.flush();
dataOutputStream.close();
//GET RESPONSE
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
webResponse = response.toString();
Log.e("response", response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
}
By going through this examples you can call web service.And get a response

Android, Read timed auto and soap

Ksoap2 trying to connect to the web service. However, the "read timed out" error getting. I do not know what to do.
Ksoap2 'There is an error too? where is the error
Ksoaps libs version: 3.0.1
Emulator 2.2
MainActivity.java
public class MainActivity extends Activity {
static final String METHOD_NAME = "GetTableUpdateVersionByTableName";
static final String NAMESPACE = "http://tempuri.org/";
static final String URL = "https://app.xxx.com/IntSecureFlight/SFInternal.svc";
static final String DOMAIN = "app.xxx.com";
static final String SOAP_ACTION = "http://tempuri.org/IOperationSvc/GetTableUpdateVersionByTableName";
TextView sonuc;
EditText tableName;
String message;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sonuc = (TextView) findViewById(R.id.textView1);
tableName = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), tableName.getText(),
Toast.LENGTH_LONG).show();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// uzun islem oncesi yapilacaklar
}
#Override
protected String doInBackground(String... strings) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("tableName", tableName.getText().toString());
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
soapEnvelope.headerOut = new Element[1];
soapEnvelope.headerOut[0] = buildAuthHeader();
try {
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 2000);
transportSE.call(SOAP_ACTION, soapEnvelope);
Object result = soapEnvelope.getResponse();
if (result instanceof SoapFault12) {
SoapFault12 soapResult = (SoapFault12) result;
message = soapResult.getLocalizedMessage();
} else if (result instanceof SoapObject) {
SoapObject soapResult = (SoapObject) result;
message = soapResult.getProperty(0).toString();
}
} catch (SoapFault12 e) {
message = e.getMessage();
} catch (XmlPullParserException e) {
message = e.getMessage();
} catch (Exception e) {
message = e.getMessage();
}
return message;
}
#Override
protected void onPostExecute(String result) {
sonuc.setText(message);
super.onPostExecute(result);
}
}
public Element buildAuthHeader() {
Element h = new Element().createElement(NAMESPACE, "UsernameToken");
Element username = new Element().createElement(NAMESPACE, "Username");
username.addChild(Node.TEXT, "genel");
h.addChild(Node.ELEMENT, username);
Element pass = new Element().createElement(NAMESPACE, "KurumKod");
pass.addChild(Node.TEXT, "050");
h.addChild(Node.ELEMENT, pass);
return h;
}
#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;
}
}
HttpTransportSEImpl
public class HttpTransportSEImpl extends HttpTransportSE {
public HttpTransportSEImpl(String url) {
super(url);
}
#Override
public ServiceConnection getServiceConnection() throws IOException {
ServiceConnection connection = super.getServiceConnection();
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
return connection;
}
}
AndroidManifest add <uses-permission android:name="android.permission.INTERNET"/>
read timed out error and socket time out errors will come on low internet connections
check your internet connection strength
or check the server response string, you may mismatch the data-type on reading.
and add permissions to listen network_state and
access_fine_location
edit your code:
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 60000);

Error to connect with a web service in android.. HTTP reqest failed,HTTP status 400

I have this code to call a donNet web servise on localhost. The web service take 5 values and return a string.. I took this error: Error HTTP request failed, HTTP status 400.. What is the problem here?
public class MainActivity extends Activity {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://10.0.2.2:6371/Service1.asmx";
int IDocID;
String SName,SDate,STime,SReason;
TextView txt;
private PropertyInfo AppDoctor,AppDate,AppTime,AppName,AppReason;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sent=(Button)findViewById(R.id.button1);
txt=(TextView)findViewById(R.id.textView6);
sent.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
EditText DocID=(EditText)findViewById(R.id.editTextDoc);
IDocID = Integer.parseInt(DocID.getText().toString());
EditText Date= (EditText)findViewById(R.id.editTextDate);
SDate = Date.getText().toString();
EditText Time=(EditText)findViewById(R.id.editTextTime);
STime = Time.getText().toString();
EditText Name=(EditText)findViewById(R.id.editTextName);
SName = Name.getText().toString();
EditText Reason=(EditText)findViewById(R.id.editTextReason);
SReason = Reason.getText().toString();
new InsertTask().execute();
}
});
}
private String doInsert(String SName,String SDate,String STime,String SReason, int IDocID ) {
String result="";
final String SOAP_ACTION = "http://tempuri.org/InsertAppointment";
final String METHOD_NAME = "InsertAppointment";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("AppDoctor",IDocID);
request.addProperty("AppDate",SDate);
request.addProperty("AppTime",STime);
request.addProperty("AppName",SName);
request.addProperty("AppReason",SReason);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
System.out.println(request);
System.out.println(envelope.toString());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.i("myApp", response.toString());
/
if(response != null)
{
String resp= response.toString();
result = resp;
txt.setText(resp);
}
}catch(SocketException ex)
{
Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
txt.setText(ex.toString());
}
catch (Exception e) {
Log.e("Error : " , "Error on soapPrimitiveData() " + e.getMessage());
e.printStackTrace();
}
return result;
}
private class InsertTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Logging in...");
this.dialog.show();
}
protected Void doInBackground(final Void... unused) {
String auth=doInsert( SName, SDate, STime, SReason, IDocID);
System.out.println(auth);
return null;// don't interact with the ui!
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
Try to add "" to your SOAP_ACTION:
final String SOAP_ACTION = "\"http://tempuri.org/InsertAppointment\"";

How to make a TextView show a value from a AsynTask class

I have an AsynTask which retrieve data from a web service and with this data to be viewed on the UI. So, in my MainActivity, I have a textView.
This is the data I received from the webservice:
{"name":"ezio","country":"italy"}{"name":"fufu","country":"tutu"}{"name":"chikaka","country":"aceVentura"}
The problem is, I do not know how to set the textView with the value of 'result' from the ClientConnection class. When I run the application, the textView is empty.
public class ClientConnection extends AsyncTask {
public static final String URL = "http://192.168.0.15/test.php";
static JSONObject jObj = null;
public static String result = "";
#Override
protected String doInBackground(Void... voids) {
// public JSONObject connect(){
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.e("HTTPStatus error:","Status not okay");
}
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
JSONObject jsonObject = convertToJson(result);
// jsonObject.get()
//result = jsonObject.getString("name");
//JSONArray google = jsonObject.getJSONArray("");
} catch (Exception e) {
//Toast toast = Toast.makeText(null, e.getMessage(), Toast.LENGTH_LONG);
Log.e("Error","don't know what exception though");
}
return result;
}
private JSONObject convertToJson(String test){
JSONArray clients = new JSONArray();
try{
jObj = new JSONObject(test);
}catch (JSONException e){
Log.e("JSON Parser", "Error parsing data" + e.toString());
}
return jObj;
}
public String getResult(){
return result;
}
public JSONObject getjObj(){
return jObj;
}
}
And this is the Main Activity
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.textViewTest);
ListView listView = (ListView) findViewById(R.id.listView);
Button buttonConnect = (Button) findViewById(R.id.buttonConnect);
final ClientJSONParsingActivity clientJSONParsingActivity = new ClientJSONParsingActivity();
buttonConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ClientConnection().execute();
textView.setText(new ClientConnection().getResult());
}
});
}
}
Thank you for your help
You can display the result in the onPostExecute in the AsyncTask.
You should update textview in your asynctask. onPostExecute() method runs on UI thread
protected void onPostExecute(String result) {
textView.setText(result);
}
Pass the text view as an argument to the asynctask and set it in onPostExecute. On my mobile so no code, sorry ;-)
add this code under your doinbackground;
protected void onPostExecute(Long result) {
(find your text view here from the context where textview it is)
textView.setText(result);
}

Categories

Resources