a real amateur developer here in dire need of some assistance. I've been trying to parse JSON data and turn it into a list of items, but I am having difficulties attempting to use the setListAdapter method despite importing it into the class. Any help would be massively appreciated.
Here is my main activity, error is in the onPostExecute method
import java.io.IOException;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class JSON extends Activity {
// Coordinates used for centering the Map
private final static String UNAME = "aporter";
private final static String URL = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username="
+ UNAME;
public static final String TAG = "MapsEarthquakeMapActivity";
// Set up UI and get earthquake data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new HttpGetTask().execute(URL);
}
private class HttpGetTask extends
AsyncTask<String, Void, List<GeonameRec>> {
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected List<GeonameRec> doInBackground(String... params) {
HttpGet request = new HttpGet(params[0]);
JSONResponseHandler responseHandler = new JSONResponseHandler();
try {
// Get Earthquake data in JSON format
// Parse data into a list of EarthQuakeRecs
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException");
} catch (IOException e) {
Log.i(TAG, "IOException");
}
return null;
}
#Override
protected void onPostExecute(List<GeonameRec> result) {
if (null != mClient)
mClient.close();
setListAdapter(new ArrayAdapter<String>(
JSON.this,
R.layout.listitem, result));
}
}
}
}
And here is my class where I format the JSON response.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JSONResponseHandler implements
ResponseHandler<List<GeonameRec>> {
#Override
public List<GeonameRec> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<GeonameRec> result = new ArrayList<GeonameRec>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
JSONObject object = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
JSONArray earthquakes = object.getJSONArray("earthquakes");
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject tmp = (JSONObject) earthquakes.get(i);
result.add(new GeonameRec(
tmp.getDouble("lat"),
tmp.getDouble("lng")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
setListAdapter method is available in ListActivity not in Activity.
to do so in an Activity sub class, you should define your ListView and call listView.setAdapter
Related
This is my first time working with Android and I need to parse the JSON nested from the API. In the example below I managed to parse one JSON object, the value "title" is https://jsonplaceholder.typicode.com/posts/1. How do I change the code to look through all the JSON objects in the loop and extract "title" from them - https://jsonplaceholder.typicode.com/posts/?
P.S. If possible, I would not like to use the new Maven/Gradle dependencies.
package org.newwheel.app;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.JsonReader;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new RequestAsync().execute();
}
public class RequestAsync extends AsyncTask<String,String,List<String>> {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected List<String> doInBackground(String... strings) {
List<String> projectList = new ArrayList<>();
try {
// Create URL
URL newWheelEndpoint = new URL("https://jsonplaceholder.typicode.com/posts/1");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) newWheelEndpoint.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, StandardCharsets.UTF_8);
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("title")) { // Check if desired key
// Fetch the value as a String
String value = jsonReader.nextString();
// Do something with the value
// ...
projectList.add(value);
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
}
return projectList;
}
#Override
protected void onPostExecute(List<String> list) {
if(list!=null){
String[] array = list.toArray(new String[0]);
// Get element ListView
ListView countriesList = (ListView) findViewById(R.id.countriesList);
// Create adapter
ArrayAdapter<String> adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, array);
// Install for list adapter
countriesList.setAdapter(adapter);
}
}
}
}
I am new to Android so I am sorry if this is a mundane question. I am working on one of the exercises in a tutorial and I have a simple list which is supposed to display the data I got from a website. My listview is empty despite my adapter being populated correctly. I tried printing the adapter objects and it is working fine. Please help. Thanks in advance.
MainAcitvity.java
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
private static String USGS_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-12-01&minmagnitude=7";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
ArrayList<String> place = new ArrayList<>();
try {
place = task.execute(USGS_URL).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ArrayAdapter<String> placesAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,place);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(placesAdapter);
}
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>>
{
#Override
protected ArrayList<String> doInBackground(String... strings) {
ArrayList<String > place = QueryUtils.fetchData(strings[0]);
}return place;
}
}
}
QueryUtils.java
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
public final class QueryUtils {
private QueryUtils() {
}
protected static ArrayList<String> fetchData(String rawStream) {
URL newUrl = null;
try {
newUrl = createUrl(rawStream);
Log.i("QueryUtils.java", newUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
ArrayList<String> values = QueryUtils.makeHttpRequest(newUrl);
}return values;
}
private static URL createUrl(String rawStream) throws MalformedURLException {
URL url = new URL(rawStream);
return url;
}
public static ArrayList<String> makeHttpRequest(URL newUrl) {
HttpsURLConnection url = null;
InputStream in = null;
ArrayList<String> values = new ArrayList<>();
try {
url = (HttpsURLConnection) newUrl.openConnection();
in = url.getInputStream();
String data = fetchJsonData(in);
values = fetchOutput(data);
} }catch (IOException e) {
e.printStackTrace();
}
finally {
if(url !=null)
url.disconnect();
}
return values;
}
private static ArrayList<String> fetchOutput(String data) {
String place = null;
ArrayList<String> values = new ArrayList<>();
try {
JSONObject baseJsonObject = new JSONObject(data);
JSONArray featuresAray =baseJsonObject.getJSONArray("features");
for(int i=0;i<featuresAray.length();i++) {
JSONObject firstArray = featuresAray.getJSONObject(i);
JSONObject properties = firstArray.getJSONObject("properties");
place = properties.getString("place");
values.add(place);
}
} catch (JSONException e) {
e.printStackTrace();
}
return values;
}
private static String fetchJsonData(InputStream in) throws IOException {
StringBuilder output = new StringBuilder();
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
return output.toString();
}
}
So the solution was really really stupid. I cant believe I wasted so much time over this. Apparently the text was white and that's why my listView seemed empty :(:(
I want to display JSON data in textView and i do that but the problem is when i create a separate class for lood JSON data and Store into A ArrayList, it doesn"t work.
Here is my code please help me what i can do to solve that problem.
My inner class code
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.mdashikurrahman.transactions.AppController;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeJsonArrayRequest();
}
});
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
Separate class code
BackgroundTask
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by MD ASHIKUR RAHMAN on 9/24/2016.
*/
public class BackgroundTask {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
/**
* Method that return a arraylist which made by jsonArray
* */
public ArrayList<HouseOrPerson> makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
return arrayList;
}
}
InsertActivity class where i create a object ob BackGround class and call makeJsonArrayRequest method
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.mdashikurrahman.transactions.BackgroundTask;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask bg = new BackgroundTask();
arrayList=bg.makeJsonArrayRequest();
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
}
});
}
}
Arent you missing a constructor in your BackgroundTask?
Try putting System.out.println(arrayList.size()) before you return it in your BackgroundTask. What is the size of it?
I have to retrieve json object from json file from this url.
My code is throwing java.lang.RuntimeException in doInBackground() and string to jsonObject conversion exception.
Can anyone help me at this? I am new to Android programming.
package course.examples.networkingearthquake;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.net.http.AndroidHttpClient;
public class HttpActivity extends ActionBarActivity {
TextView mTextView;
EditText etInput;
TextView input;
String number;//edited
int num;//edited
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
mTextView = (TextView)findViewById(R.id.text1);
input = (TextView)findViewById(R.id.input);
etInput = (EditText)findViewById(R.id.etInput);
input.setText("Input");
//number = etInput.getText().toS();
final Button btDisplay = (Button)findViewById(R.id.btDisplay);
btDisplay.setText("DISPLAY");
btDisplay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new HttpGetTask().execute();
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String>{
private static final String TAG = "HttpGetTask";
private static final String URL = "http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params){
HttpGet request = new HttpGet(URL);
JSONResponseHandler responseHandler = new JSONResponseHandler();
// ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
return mClient.execute(request,responseHandler);
}catch(ClientProtocolException exception){
exception.printStackTrace();
}catch(IOException exception){
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
if(null != mClient)
mClient.close();
mTextView.setText(result);
}
}
private class JSONResponseHandler implements ResponseHandler<String>{
#Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
String result = null;
String JSONResponse = new BasicResponseHandler().handleResponse(response);
JSONResponse = JSONResponse.substring(17, JSONResponse.length()-3);
num = Integer.parseInt(number);// edited
try {
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue();
JSONArray features = responseObject.getJSONArray("features");
JSONObject retObject = (JSONObject)features.get(num);//edited
// JSONObject geometry = (JSONObject)retObject.get("geometry");
result = retObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
The JSON returned by the URL you specify containts eqfeed_callback() which needs to be stripped in order to make it valid JSON.
It seems like you have done this in your response handler, but you are cutting off one character too much at both the start and the end.
Try this:
JSONResponse = JSONResponse.substring(16, JSONResponse.length()-2);
after searching around im able to retreive a response from my servlet , but i cant send a parameter (a username and a password parameter) from android to a servlet! My logcat shows this error:
04-0java.lang.ClassCastException: org.apache.http.client.methods.HttpGet cannot be cast to org.apache.http.HttpResponse
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:76)
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
and i cant understand why!
Here it is my android main activity:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
nameValue =URLEncoder.encode(name.getText().toString(), "UTF-8");
passValue =URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
List<NameValuePair> postParameters =
new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("user",nameValue));
postParameters.add(new BasicNameValuePair("pass",passValue));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
((HttpResponse) httpGet).setEntity(formEntity);
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
Does anyone have any idea?
UPDATE:
now i have changed my android code like this:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
String nameValue ="user="+URLEncoder.encode(name.getText().toString(), "UTF-8");
String passValue ="&pass="+URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web?"+nameValue+passValue;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
this time runs without logcat errors but the parameters does not come to the servlet!
Looking at the stack trace, I guess your problem is at this line.
((HttpResponse) httpGet).setEntity(formEntity);
Why are you casting it to HttpResponse?
OK. You want to send user/pass parameters using HTTP GET. For HTTP GET, all parameters are part of the URL. Maybe this can give you some help on how to perform a HTTP GET and pass parameters in. But in general, URL would look like this
http://www.blah.com/servlet?user="1234"&pass="password"
The stuff after the ? in the URL contains all the parameters. But there is a length limit in the URL, if you exceed that length, you'll have to use HTTP POST.
Try this link to see if it can help you
http://androidexample.com/How_To_Make_HTTP_Get_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=63&aaid=88
i have modified the activity and the problem was that the URL and nameValue and passValue was declared on the wrong section of the code ! Here it is the right android code:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
content.setText("Vendosni Perdoruesin dhe Fjalekalimin");
Button button=(Button)findViewById(R.id.but);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameValue="&user="+name.getText().toString();
passValue ="&pass="+pass.getText().toString();
URL = "http://10.0.2.2:8080/login/web2?activitetiNR=1"+nameValue+passValue;
AsyncTaskRunner runner = new AsyncTaskRunner();
Log.i("url",URL);
Log.i("url",nameValue);
Log.i("url",passValue);
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}