Android Multiple AsyncTasks from a listview row click - android

I have an issue with with multiple clicks on a ListView using custom adapter.
I'm catching the onClick events all fine, the problem is that I need to start an AsyncTask on each row click that calls a webservice.
Its the same AsyncTask, just with different params.
If the user clicks on multiple rows fast, only the last AsyncTask is fired and that row is only updated.
Code to handle onClick()
myListView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Item item = (Item) mylLstView.getAdapter().getItem(position);
//execute AsyncTask
}
});
My AsyncTask
private class CheckItemInOrOutTask extends AsyncTask<Context, Void, Boolean>
{
private int position;
Item singleItem;
public CheckItemInOrOutTask(int position, Item singleItem)
{
this.position = position;
this.singleItem = singleItem;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Context... params)
{
try
{
HttpClient client = HttpUtil.getHttpClient();
String reqString = "Items?action=checkin";
HttpPost post = HttpUtil.makePost(reqString);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("item_id", singleItem.getId()));
nameValuePairs.add(new BasicNameValuePair("type_id", singleItem.getTypeId()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200)
{
String result = HttpUtil.responseToString(response);
JSONObject jsonItem = new JSONObject(result);
Item item = new Item();
// parse json
// set item properties
itemList.set(position,item);
}
}
catch (Exception e)
{
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
//if (result)
{
updateAdapter();
}
}
}
Can someone shed some light on it?
Thanks a lot.

Figured out it wasn't the AsyncTask that was the culprit.
It was because I was reusing my HttpClient.

Related

How to get Json object using UrlConnection in android?

Hi I am very for android just one week ago I come into this technology and in my app I am integrating services.
Here I have used HttpClient for that, but in android 6 I was deprecated.
That's why we have to use URlconnection, but how can we use this Url connection instead of HttpClient?
My code is below.
Please help me.
my code:-
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
Use Volley instead. Volley is compatible with almost all APIs.
See here on how to do this.

Android Spinner with custom java object showing key value pairing instead of value

So, I used Android - configure Spinner to use array to try and display just one field of a custom java class. My Java class is as follows (it is a part of my Google App Engine backend)
public class CropVariety {
private String varietyId;
private String varietyName;
public String getVarietyId() { return varietyId; }
public String getVarietyName() {
return varietyName;
}
public void setVarietyId(String data) {varietyId = data; }
public void setVarietyName(String data) {
varietyName = data;
}
public String toString()
{
return varietyName;
}
}
and then in the activity Async task, I have the following in Post Execute
super.onPostExecute(result);
varietyList = result;
spinner = (Spinner) findViewById(R.id.variety_spinner);
spinner.setSelection(0);
dataAdapter = new ArrayAdapter(context,android.R.layout.simple_spinner_item, varietyList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
The OnItemSelectedListener is implemented as follows:
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
// String selectedItem = parent.getItemAtPosition(pos).toString();
CropVariety selectedItem = (CropVariety) parent.getItemAtPosition(pos);
//check which spinner triggered the listener
switch (parent.getId()) {
case R.id.variety_spinner:
selectedVarietyName = selectedItem.getVarietyName();
selectedVarietyId = selectedItem.getVarietyId();
break;
}
So while selectedVarietyName and selectedVarietyId get the right values, each item on the drop down list looks as follows:
{"varietyId":"sefs","varietyName":"asfd"}
I followed the link and don't know why the variety name isn't being displayed in the spinner. Thank you
you are downloading json Object from that link .. you have to parse th json in your doInBackground .. and store the result in a list to use it later in the postExecute here is an exemple:
class ModifierParam extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityMed.this);
if (action.equals("rdvmed")) {
pDialog.setMessage(getString(R.string.enrParam));
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
}
protected String doInBackground(String... args) {
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
//here are the password and email for login
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Mdp", mdp));
json = jsonParser.makeHttpRequest(url_parametres,
"POST", params);
}
try {
if(json != null && !json.isNull("yourArrayName")){
list.clear();
if (json.has("yourArrayName")) {
JSONArray ja = json.getJSONArray("yourArrayName");
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
String varietyNames= String.valueOf(c.getInt("varietyName"));
String varietyId= c.getString("varietyId"));
//store data in the list
list.add(new YourObjectName(varietyName, varietyId));
}
}
}
}
}} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
//here you create your adapter from that list
// and then Spinner.setAdapter(the Adapter);
}
}
you need jsonParser i think you have it... if you dont here it is :
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
now your data will be displayed correctly

android AsyncTask and UI thread interaction

I'm using the AsyncTask to open a URL, access the server, fetch the content and display them in a list view in the main activity. The content extracted consists of a title of the newspaper and a URL to the website, which will be displayed on a WebView in a second activity, if a "read" button is clicked. I coded out the program straight away and it works, but when I looked back at it, I found something that seems unreasonable, so mainly I want to make clear how the code works. Here is the code for the main activity:
package com.example.newsapp;
public class MainActivity extends Activity {
static final private String LOG_TAG = "main";
private ArrayList<Content> aList;
private class Content{
Content() {};
public String title;
public String url;
}
private class MyAdapter extends ArrayAdapter<Content>{
int resource;
public MyAdapter(Context _context, int _resource, List<Content> titles) {
super(_context, _resource, titles);
resource = _resource;
// this.context = _context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout newView;
final Content content = getItem(position);
// Inflate a new view if necessary.
if (convertView == null) {
newView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(inflater);
vi.inflate(resource, newView, true);
} else {
newView = (LinearLayout) convertView;
}
// Fills in the view.
TextView tv = (TextView) newView.findViewById(R.id.listText);
ImageButton b = (ImageButton) newView.findViewById(R.id.listButton);
b.setBackgroundResource(0);
tv.setText(content.title);
Typeface type = Typeface.createFromAsset(getAssets(),"LiberationSerif-BoldItalic.ttf");
tv.setTypeface(type);
// Sets a listener for the button, and a tag for the button as well.
b.setTag(Integer.toString(position));
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Reacts to a button press.
Intent intent = new Intent(MainActivity.this, WebPage.class);
Bundle bundle = new Bundle();
bundle.putString("URL", content.url);
intent.putExtras(bundle);
startActivity(intent);
}
});
return newView;
}
}
class MyAsyncTask extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
Content content;
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Downloading the news...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(String... params) {
String url_select = params[0];
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return result;
} // protected Void doInBackground(String... params)
protected void onPostExecute(String result) {
//parse JSON data
try {
super.onPostExecute(result);
Log.i(LOG_TAG, result);
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray("sites");
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
content = new Content();
if (jObject.has("title") && jObject.has("url")){
content.title = jObject.getString("title");
content.url = jObject.getString("url");
aList.add(content);
aa.notifyDataSetChanged();
}
} // End Loop
progressDialog.dismiss();
} catch (JSONException e) {
// progressDialog.dismiss();
Log.e("JSONException", "Error: " + e.toString());
}
} // protected void onPostExecute(String result)
}
private MyAdapter aa;
private MyAsyncTask loadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadTask = new MyAsyncTask();
loadTask.execute("http://luca-ucsc.appspot.com/jsonnews/default/news_sources.json");
aList = new ArrayList<Content>();
aa = new MyAdapter(this, R.layout.list_element, aList);
ListView myListView = (ListView) findViewById(R.id.listView1);
myListView.setAdapter(aa);
aa.notifyDataSetChanged();
}
public void refresh(View v){
if (loadTask.getStatus() == AsyncTask.Status.FINISHED){
aList.clear();
aa.notifyDataSetChanged();
new MyAsyncTask().execute("http://luca-ucsc.appspot.com/jsonnews/default/news_sources.json");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
So you can see that only after loadTask.execute() in onCreate(), do I create the object for alist and aa, but I'm already using them in onPostExecute() in the AsyncTaks class, so I'm not very clear what happens here, because onPostExecute() and the UI are on the same thread, so the code in onPostExecute() should be executed first.
I thought I should put
aList = new ArrayList<Content>();
aa = new MyAdapter(this, R.layout.list_element, aList);
into onPostExecute(), which is more logical to me, but the app crashes this way. Also I think deleting aa.notifyDataSetChanged(); in onPostExecute() shouldn't be a problem because it's also in the onCreate() method, but this actually causes the list view to be blank, without any content. Actually, putting any of the codes after loadTask.execute() into the if block of the onPostExecute() method causes some problem, or crashes the app. That would be great if somebody can give some insight or hint. Thanks for reading.
onPostExecute is called on the UI thread after the background task completes its work. You cannot guarantee the timing of this call in relation to other calls on the UI thread.
Since you are already implementing getView yourself, I recommend you extend BaseAdapter instead of ArrayAdapter and implement the other few required methods. It's not hard and you can use whatever data structure you want to back the adapter. Assuming you use a List<Content> to back the adapter, you can write a method to swap the list in place like so:
public void swapList(List<Content> newList) {
this.list = newList;
notifyDataSetChanged();
}
In your AsyncTask, you have complete control of the Params, Progress, and Result parameterized types. They don't all have to be String. You can do this instead:
private class myAsyncTask extends AsyncTask<String, Void, List<Content>> {
/* ... */
}
The String for Params is the URL (same as you do now). Void for Progress because you don't publish progress anyway. List<Content> for Result because that's the thing you actually want to end up with after doing your task.
You should do ALL of your work in doInBackground. There is no reason to deserialize a String into a JSONArray and mess around with that in onPostExecute, particularly since that is happening on the main thread. Rewrite doInBackground to return a List<Content>, and all you need in onPostExecute is this:
public void onPostExecute(List<Content> result) {
adapter.swapList(result);
}
Now you can create the adapter once (in onCreate()) and just swap the list whenever it's appropriate.

android input validation not working as expected

I am trying to perform simple form validation whereby I use EditText.setError() to notify the user of the wrong input or blank field. Unfortunately, when I do that it only shows error when I click on the field again after incomplete form submission. This is weird because I want it to show as soon as I click button and form incomplete.
I believe it has something to do with the placement of the code that does the validation? Following is my code:
public class AddDiscountActivity extends Activity implements OnItemSelectedListener{
String shopCategory;
Spinner spinner;
String shopName;
String shopCity;
String shopLocation;
String discountRate;
String discountDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adddiscount_activity);
spinner = (Spinner) findViewById(R.id.categoriesSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.categoriesArray, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void SubmitData(View view)
{
new PostDataAsyncTask().execute();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
// TODO Auto-generated method stub
shopCategory = spinner.getItemAtPosition(pos).toString();
Log.v("SHOP CATEGORY***********: ", shopCategory);
}
public class PostDataAsyncTask extends AsyncTask<String, String, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(AddDiscountActivity.this, "Please Wait","Update Ads listings", true);
//do initialization of required objects objects here
};
#Override
protected String doInBackground(String... strings) {
// TODO Auto-generated method stub
try {
postAdData();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
super.onPostExecute(lenghtOfFile);
progressDialog.dismiss();
//Intent intent = new Intent(MainActivity.this, ThankYouAcitivty.class);
// startActivity(intent);
}
}
private void postAdData() throws JSONException{
try{
// url where the data will be posted
String postReceiverUrl = "http://hye.com/displaypost.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//All user input
EditText shopNameEditText = (EditText)findViewById(R.id.shopName);
EditText shopLocationEditText = (EditText)findViewById(R.id.shopLocation);
EditText shopCityEditText = (EditText)findViewById(R.id.shopCity);
EditText discountRateEditText = (EditText)findViewById(R.id.shopDiscount);
EditText discountDurationEditText = (EditText)findViewById(R.id.shopDiscountDuration);
shopNameEditText.getText().toString();
shopLocationEditText.getText().toString();
shopCityEditText.getText().toString();
discountRateEditText.getText().toString();
discountDurationEditText.getText().toString();
/*******Fields Validation*********/
if(shopNameEditText.getText().toString().length() == 0)
shopNameEditText.setError("يجب ادخال اسم المحل");
if(shopLocationEditText.getText().toString().length() == 0)
shopLocationEditText.setError("يجب ادخال العنوان");
if(shopCityEditText.getText().toString().length() == 0)
shopCityEditText.setError("يجب ادخال المدينة");
if(discountRateEditText.getText().toString().length() == 0)
discountRateEditText.setError("يجب ادخال نسبة التخفيض");
/*********************************/
nameValuePairs.add(new BasicNameValuePair("name", shopName));
nameValuePairs.add(new BasicNameValuePair("location", shopLocation));
nameValuePairs.add(new BasicNameValuePair("city", shopCity));
nameValuePairs.add(new BasicNameValuePair("rate", discountRate));
nameValuePairs.add(new BasicNameValuePair("duration", discountDuration));
nameValuePairs.add(new BasicNameValuePair("category", shopCategory));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("", "Response: " + responseStr);
// you can add an if statement here and do other actions based on the response
}
} catch (IOException e) {
e.printStackTrace();
}
}
try by putting // All user input // // Fields Validation // inside public void SubmitData(View view) and use if{} else{}
you will Also get null pointer Exception because you are not assigning any value to
String shopName;
String shopCity;
String shopLocation;
String discountRate;
String discountDuration;
so your public void SubmitData(View view) should be like :
public void SubmitData(View view)
{
//All user input
EditText shopNameEditText = (EditText)findViewById(R.id.shopName);
EditText shopLocationEditText = (EditText)findViewById(R.id.shopLocation);
EditText shopCityEditText = (EditText)findViewById(R.id.shopCity);
EditText discountRateEditText = (EditText)findViewById(R.id.shopDiscount);
EditText discountDurationEditText = (EditText)findViewById(R.id.shopDiscountDuration);
if(shopNameEditText.getText().toString().length() == 0)
shopNameEditText.setError("يجب ادخال اسم المحل");
else if(shopLocationEditText.getText().toString().length() == 0)
shopLocationEditText.setError("يجب ادخال العنوان");
else if(shopCityEditText.getText().toString().length() == 0)
shopCityEditText.setError("يجب ادخال المدينة");
else if(discountRateEditText.getText().toString().length() == 0)
discountRateEditText.setError("يجب ادخال نسبة التخفيض");
else
{
shopName = shopNameEditText.getText().toString();
shopLocation = shopLocationEditText.getText().toString();
shopCity = shopCityEditText.getText().toString();
discountRate = discountRateEditText.getText().toString();
discountDuration = discountDurationEditText.getText().toString();
new PostDataAsyncTask().execute();
}
}
What I would recommend doing is using TextWatcher. If you do it this way, I believe these steps will help:
First, implement android.text.TextWatcher
Second, implement the necessary methods, most importantly, afterTextChanged(Editable)
Third, add textlisteners for your EditText's
For example...
EditText shopNameEditText = (EditText)findViewById(R.id.shopName);
shopNameEditText.addTextChangedListener(this);
#Override
public void afterTextChanged(Editable s) {
//check validation
if(shopNameEditText.getText().toString().length() == 0){
...
}
}
This is the expected behavior. Note that EditText extends the TextView class. And, the method that you are using: setError(CharSequence) is inherited by EditText from TextView.
Here is what it is designed to do:
Sets the right-hand compound drawable of the TextView to the "error"
icon and sets an error message that will be displayed in a popup when
the TextView has focus. The icon and error message will be reset to
null when any key events cause changes to the TextView's text. If the
error is null, the error message and icon will be cleared.
When the click is encountered, the EditText loses focus and waits until it regains focus to post the error.
To show the user that an error has occured, instead of calling setError(CharSequence), you can set warning text inside the EditText using myEditText.setText("Required"). You can also call requestFocus() on the EditText to show the error immediately after setError(CharSequence), but I am not sure how this would behave in case of 2 or more errors.

Android asynchronous post blocks UI thread

I'm developing an Android app. I want to post to a server using asynctask. However, I still have an error which indicates that the UI thread is blocked.
I want to parse the XML response and display it in a list view, but I cannot proceed because the UI thread is still blocked.
public class AsynchronousPost extends ListActivity implements OnClickListener {
EditText SearchValue;
Button SearchBtn;
String URL = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_interface);
SearchBtn = (Button) findViewById(R.id.searchbtn);
SearchBtn.setOnClickListener(this);
}
public void onClick(View views) {
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Integer, Document> {
private final String URL = "url";
private final String username = "username";
private final String password = "password";
private EditText SearchValue;
#Override
protected Document doInBackground(String... arg0) {
// TODO Auto-generated method stub
getXmlFromUrl(URL); // getting XML
return null;
}
#Override
protected void onPostExecute() {
//want to parse xml response
//display on listview
}
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
SearchValue = (EditText) findViewById(R.id.search_item);
String Schvalue = SearchValue.getText().toString();
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
5);
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("searchItem",
Schvalue));
// response stored in response var
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
// return XML
return xml;
}
}
}
There are a couple problems that I see. First, you aren't passing anything in execute() but in your class declaration you are telling doInBackground() to expect a String. Secondly, you are telling onPostExecute() to expect a Document but you are returning null from doInBackground() and not taking any parameters in onPostExecute(). Unless I missed something, I don't see how this even compiles
protected Object doInBackground(String... params) {
//this method of AsyncTask is not running on the UI Thread -- here do just non UI taks
return result;
}
#Override
protected void onPostExecute(Object result) {
//I'm not sure but I think this method is running on the UI Thread
//If you have long operations here to do you will block UI Thread
//put the tasks in the doInBackground...
//to fill the elements in the UI elements use
//
runOnUiThread (new Runnable() {
#Override
public void run() {
//here fill your UI elements
}});
}

Categories

Resources