I want to put bitmap images into ImageView of ListView. i changed image from url to bitmap image. I have 10 images and i have to put the images in each item of the ListView. Is there any method other than Lazy Adapter ?? Thanks in advance!!!
this is my code
public class Propertylist extends ListActivity {
String proptype;
String prop;
String estimate;
String photo;
String get;
String[] data;
TextView text;
URL aURL;
InputStream is = null;
String result = "";
JSONObject jArray = null;
//Hashtable<String,Bitmap> imagemap;
private ArrayList<NameValuePair> nameValuePairs;
private LayoutInflater inflater;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
text = (TextView) findViewById(R.id.text);
Toast.makeText(getApplicationContext(), "Displaying popertylist for zipcode "+get, Toast.LENGTH_LONG).show();
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//ArrayList<Hashtable<String, Bitmap>> mylist1 = new ArrayList<Hashtable<String, Bitmap>>();
Bundle bundle = this.getIntent().getExtras();
get = bundle.getString("name");
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.propertyhookup.com/mobile/propertylist.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("zipcode", get.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
if(result.length()<= 7){
Toast.makeText(getApplicationContext(), "No properties for this zipcode or check your zipcode ", Toast.LENGTH_LONG).show();
text.setText("No properties for this zipcode or check your zipcode");
}
else{
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
//JSONObject json = JSONfunctions.getJSONfromURL("http://192.168.1.111/propertyhookup.com/mobile/propertylist.php");
try{
JSONArray earthquakes = jArray.getJSONArray("earthquakes");
for(int i=0;i<10;i++){
HashMap<String, String> map = new HashMap<String, String>();
//imagemap = new Hashtable<String, Bitmap>();
JSONObject e = earthquakes.getJSONObject(i);
if(e.getString("property_type").contains("1")) {
proptype ="Single Family Home";
}else if(e.getString("property_type").contains("2")) {
proptype="Condo";
}else if(e.getString("property_type").contains("3")) {
proptype="Townhouse";
}
if(e.getString("estimated_price").contains("0")) {
estimate = "Not Enough Market Value";
//estimat = (TextView) findViewById(R.id.estimat);
//estimat.setTextColor(Color.rgb(0, 0, 23));
}else {
estimate = "$"+e.getString("estimated_price");
}
photo = e.getString("photo1");
map.put("id", String.valueOf(i));
map.put("percent", e.getString("percentage_depreciation_value")+"%");
map.put("propertyid", "#"+e.getString("property_id")+" ");
map.put("cityname",e.getString("city_name")+",");
map.put("statecode",e.getString("state_code"));
map.put("propertytype","| "+ proptype);
map.put("footage", e.getString("house_square_footage")+" Sq.Ft");
map.put("bathroom", "| "+e.getString("bathrooms")+" Bath, ");
map.put("bedroom", e.getString("bathrooms")+" Bedrooms");
map.put("price", "List Price: $"+e.getString("property_price"));
map.put("estimated", "Base Market Value: "+estimate);
//map.put("photos",photo );
mylist.add(map);
}
}catch(JSONException e) {
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
try
{
aURL = new URL(photo);
}
catch (MalformedURLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection conn = null;
try
{
conn = aURL.openConnection();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
conn.connect();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is = null;
try
{
is = conn.getInputStream();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedInputStream bis = new
BufferedInputStream(is,8*1024);
Bitmap bm = BitmapFactory.decodeStream(bis);
//imagemap.put("im",bm);
// mylist1.add(imagemap);
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main4,
new String[] { "percent","propertyid", "cityname", "statecode", "propertytype", "footage", "bathroom", "bedroom", "price", "estimated" },
new int[] { R.id.percent, R.id.property_id, R.id.city_name, R.id.state_code, R.id.prop_type, R.id.foot, R.id.bath, R.id.bed, R.id.list, R.id.estimat});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Propertylist.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icon: //Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
displaylogin();
break;
case R.id.text: //Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
displayproperty();
break;
// case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
// break;
}
return true;
}
private void displaylogin() {
startActivity(new Intent(this,Changezip.class));
finish();
}
private void displayproperty() {
startActivity(new Intent(this,property.class));
}
}
You might want to check out the GreenDroid library; it makes doing things like this trivial.
Please note that you have asked 4 previous questions that received answers and you have not accepted any of them. This community functions based on people accepting answers and if you don't start accepting answers you've found useful, you may find that people stop answering you.
Related
Actually in my project, I'm blocked. So, for the first time I ask the community of Stackoverflow. I'm new in development.
So, I have a MySql with my datas and I wan't to see in my application the items of users.
For that, I've this :
public class SuccessActivity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private ListView listView;
protected String meubles[] = new String[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_success);
Intent intent = getIntent();
String id = intent.getStringExtra("id");
this.listView = (ListView) findViewById(R.id.liste);
new SuccessActivity.Recup().execute(id);
}
//PRIVATE CLASSE POUR AFFICHER LES MEUBLES
private class Recup extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
try {
//url d'ou reside mon fichier php
url = new URL("http://opix-dev.fr/mytinyhomme/personne/afficher.meuble.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// parametrage du HttpURLConnection pour recevoir et envoyer des donner à mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("id", params[0]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String resulta) {
//this method will be running on UI thread
if (resulta.equalsIgnoreCase("false")) {
} else if (resulta.equalsIgnoreCase("exception") || resulta.equalsIgnoreCase("unsuccessful")) {
} else {
try {
JSONArray nom = new JSONArray(resulta);
System.out.println(nom);
String meubles[] = new String[100];
for (int i = 0; i < nom.length(); i++){
JSONObject jsonobject = nom.getJSONObject(i);
meubles[i]= jsonobject.getString("nom");
System.out.println(jsonobject);
System.out.println(meubles);
item.setText( meubles[i]);
}
System.out.println(meubles);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
The file.php is correct because the JSONArray in System.print is ok But I've try with some TextView for display the board at the end, but I did not succeed.
How I can use the meuble[0] , meuble[1], meuble[2](it's board of String name of items) in a ListView ?
Here is what you need to do to show your data in a listview,
Modified onPostExecute() method:
#Override
protected void onPostExecute(String resulta) {
//this method will be running on UI thread
if (resulta.equalsIgnoreCase("false")) {
} else if (resulta.equalsIgnoreCase("exception") || resulta.equalsIgnoreCase("unsuccessful")) {
} else {
try {
JSONArray nom = new JSONArray(resulta);
System.out.println(nom);
String meubles[] = new String[100];
for (int i = 0; i < nom.length(); i++){
JSONObject jsonobject = nom.getJSONObject(i);
meubles[i]= jsonobject.getString("nom");
System.out.println(jsonobject);
System.out.println(meubles);
}
ArrayAdapter<String> listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,meubles);
listView.setAdapter(listAdapter);
System.out.println(meubles);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
What's added?
You need an adapter to show items in a listview. You can create your custom adapter class by extending an arrayadapter or you can use an arrayadapter without customizing it as shown.
Added code:
Create a new adapter,
ArrayAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
Set adapter for your listview,
listView.setAdapter(listAdapter);
I would like to retrieve the contents of my variable "$content" in my activity.
But I don't know how to use the return value of my doinbackground.
Can you help me ?
thank you in advance
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
RestOperation test = new RestOperation();
test.execute(restURL);
}
private class RestOperation extends AsyncTask<String, Void, String> {
//final HttpClient httpClient = new DefaultHttpClient();
String content;
String error;
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);
// EditText userinput = (EditText) findViewById(R.id.userinput);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait ...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
URL url;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
content = sb.toString();
} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(error!=null) {
serverDataReceived.setText("Error " + error);
} else {
serverDataReceived.setText(content);
String output = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(content);
JSONArray jsonArray = jsonResponse.names();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject child = jsonArray.getJSONObject(i);
String name = child.getString("name");
String number = child.getString("number");
String time = child.getString("date_added");
output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
output += System.getProperty("line.separator");
Log.i("content",content);
}
showParsedJSON.setVisibility(View.INVISIBLE);
showParsedJSON.setText(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You can directly call to the method which exist in activity, from onPostExecute method of asynctask by passing "content" value.
#Override
protected void onPostExecute(String content) {
Activity.yourMethod(content);
}
If you want to return the value from asynctask you can use
content = test.execute(url).get();
but it is not a good practice of asynctask, because it is working as serial execution. So it is not fulfill the use of asynctask for palatalization.Because get() will block the UI thread.
I am getting stuck in emulator whenever i try to do display list of images which is in my server on list view and button on click for sorting images.It is listing out images one by one,at the time when i try clicking on sorting button that time my emulator is getting stuck for a while.
I want to work on that simultaneously.
I have two buttons on click function, one is for Asynctask execution with background process and another one for normal button click listener for sorting input components for reading from UI components.
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this, "Loading.....");
wst.execute(new String[]{sampleURL});
try {
//Extract the data…
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("city", city_name));
nameValuePairs.add(new BasicNameValuePair("room_type", room_type));
nameValuePairs.add(new BasicNameValuePair("bed", no_bed));
nameValuePairs.add(new BasicNameValuePair("bedrooms", no_bedrooms));
nameValuePairs.add(new BasicNameValuePair("guest_allow", guest_allowed));
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
try {
// JSONArray jso = new JSONArray(json);
JSONObject object = new JSONObject(json);
JSONArray jso = object.getJSONArray("search_result");
Toast.makeText(this, "jso length" + jso.length(), Toast.LENGTH_LONG).show();
if (jso.length() != 0) {
for (int i = 0; i < jso.length(); i++) {
if (jso.getJSONObject(i).getString("city").equalsIgnoreCase(city_name)) {
Person resultRow = new Person();
resultRow.id = jso.getJSONObject(i).getString("user_id");
resultRow.ProjectName = jso.getJSONObject(i).getString("user_name");
resultRow.Country = jso.getJSONObject(i).getString("bathrooms");
resultRow.city = jso.getJSONObject(i).getString("city");
resultRow.descrip = jso.getJSONObject(i).getString("price");
resultRow.bed = jso.getJSONObject(i).getString("bed");
resultRow.bedrooms = jso.getJSONObject(i).getString("bedrooms");
resultRow.guest_allow = jso.getJSONObject(i).getString("guest_allow");
resultRow.roomtype = jso.getJSONObject(i).getString("room_type");
resultRow.property_type = jso.getJSONObject(i).getString("property_type");
resultRow.logo = jso.getJSONObject(i).getString("property_image");
resultRow.user_ppty_id = jso.getJSONObject(i).getString("user_property_id");
resultRow.check_in_time = jso.getJSONObject(i).getString("check_in_time");
resultRow.check_out_time = jso.getJSONObject(i).getString("check_out_time");
resultRow.host_image = jso.getJSONObject(i).getString("host_image");
arrayOfwebData.add(resultRow);
Toast.makeText(this, "counting" + i, Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(this, "NOT found", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "NOT found", Toast.LENGTH_LONG).show();
Log.e(TAG, e.getLocalizedMessage(), e);
}
ListView myListView = (ListView) findViewById(R.id.listview);
Toast.makeText(this, "updated" + up, Toast.LENGTH_LONG).show();
aa = new FancyAdapter();
myListView.setAdapter(aa);
up++;
} else {
Toast.makeText(this, "NOT found", Toast.LENGTH_LONG).show();
}
// ViewHolder aa1= new ViewHolder();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
and button click
btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = (String) no_guest.getText();
int values = Integer.parseInt(val);
no_guest.setText("" + (values + 1));
guest_allowed = (String) no_guest.getText();
}
});
here my code for fetching values from web api. in my code no error is there. but in emulator doesn't show the values. please tell me where i done a mistake. let me know what is the correct code for that.
public class MainActivity extends ActionBarActivity {
Spinner sp1;
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=<random number>&action=Get Cities";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp1=(Spinner)findViewById(R.id.spinner1);
}
public class Mysync extends AsyncTask<List<String>, List<String>, List<String>>{
#Override
protected List<String> doInBackground(List<String>... arg0) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url1);
// Execute the request
HttpResponse response;
JSONArray arr = new JSONArray();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
arr=new JSONArray(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
//Log.e(TAG,e.toString());
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
try {
list.add(arr.getJSONObject(i).getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
protected void onPostExecute(List<String> result){
sp1=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
}
}
public String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// Log.e(TAG + "ERROR",e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
// Log.e(TAG + "ERRO",e.toString());
}
}
return sb.toString();
}
}
Define List under the line
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=&action=Get Cities";
like : List<String> list ;
And Try to Change the line
List list = new ArrayList();
Via
list = new ArrayList();
and Change
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
Via
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item,result);
Hope this may help you!
I have Service and AsyncTask in it, which due to check updatings on the server. It have to be reexecuted if it get some data and also if it doesn't. So my AsyncTask implementation is :
private class DklabExecute extends AsyncTask<Void, String, Void> {
int count;
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());
HttpGet rplPost = new HttpGet(url);
protected Void doInBackground(Void... args)
{
Log.i("service count", Integer.toString(count));
count ++;
Log.i("md5 func", md5(LoginActivity.passUserId));
String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";
JSONParser parser = new JSONParser();
DefaultHttpClient testClient = new DefaultHttpClient();
DefaultHttpClient rplClient = new DefaultHttpClient();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("", ""));
HttpGet httpTest = new HttpGet(testData);
httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
try {
httpResponse = rplClient.execute(rplPost);
}
catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Header[] head = httpResponse.getAllHeaders();
Log.i("http Response",httpResponse.toString());
for (Header one:head)
{
Log.i("headers",one.toString());
}
Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);// + "n");
}
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
json = sb.toString();
Log.i("rpl response",json);
if (new JSONArray(json) != null)
jArr = new JSONArray(json);
else
this.cancel(true);
JSONObject toObj = jArr.getJSONObject(0);
JSONObject data = toObj.getJSONObject(KEY_DATA);
if (data.has(KEY_ORDER))
{
for (Order a : ServiceMessages.orderExport)
{
Log.i("service before list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("before dashboard list", a.toString());
}
JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
Gson gson = new Gson();
Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
try
{
for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
{
Order a = itr.next();
Log.i("order count", a.toString());
if(orderObj.getOrderid()==a.getOrderid())
{
Log.i("Service","order was changed");
a = orderObj;
someMethod("Your order "+ orderObj.getTitle() + " was changed");
}
else
{
Log.i("Service","order"+ orderObj.getTitle()+" was added");
// DashboardActivityAlt.forPrint.add(0, orderObj);
ServiceMessages.orderExport.add(0,orderObj);
Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
someMethod("Your order "+ orderObj.getTitle() + " was added");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
for (Order a : ServiceMessages.orderExport)
{
Log.i("service after list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("after dashboard list", a.toString());
}
// intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
sendBroadcast(intentOrder);
Log.i("after parse order",orderObj.toString());
Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
}
else if (data.has(KEY_MESSAGE))
{
JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
Gson gson = new Gson();
Log.i("messages before parse", jsonMessage.toString());
for (Order a: DashboardActivityAlt.forPrint)
{
Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
}
Log.i("disparse message",jsonMessage.toString());
Message message = gson.fromJson(jsonMessage.toString(),Message.class);
Log.i("incomming message",message.toString());
JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
Threads thread = gson.fromJson(jsonThread.toString(),Threads.class);
Log.i("incomming thread",thread.toString());
Order orderChanged = new Order();
String orderName = null;
for(Order as : DashboardActivityAlt.forPrint)
{
if (as.getOrderid() == thread.getTreadOrder().getOrderid())
{
orderName = as.getTitle();
orderChanged = as;
Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
}
}
Log.i("orderchanged",orderChanged.toString());
someMethod("Your order "+ thread.getTreadOrder().getTitle() + " was changed. Message was added");
orderChanged.getCusThread().addMessage(message);
sendBroadcast(intentMessage);
Log.i("messages service", "before sleep");
Log.i("messages service", "after sleep");
}
else
{
this.cancel(true);
}
}
catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
rplClient.getConnectionManager().shutdown();
testClient.getConnectionManager().shutdown();
someMethod("You've lost internet connection. You should try later.");
e2.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void bitmap) {
this.cancel(true);
new DklabExecute().execute();
}
}
If I send some data to the server, it gives me back in JSON format via rpl server. Everything works good, but the problem is when I get some data from the server, AsyncTask reexecuted in onPostExecute() method and it is the same reapeted one or two times data in my list of orders. If I do not reexecute AsyncTask the listening happens only in onStartCommand() method but not permanently. Tell me please how can I implement this in the best manner...
if it's a service there's no reason to use an AsyncTask.
AyncTasks were build to deliver content back on the original thread (normally a UI thread), but services don't have those.
I suggest you use a ScheduledExecutorService instead http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
private ScheduledExecutorService executor;
// call those on startCommand
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);
and have a Runnable doing the work
private Runnable run = new Runnable() {
#Override
public void run() {
// do your network stuff
}
};
and don't forget to cancel everything when your service stops
executor.shutdown();
edit:
or to use a thread in loop you can:
boolean isRunning;
.
// this on your start
Thread t = new Thread(run);
isRunning = true;
t.start();
the runnable
private Runnable run = new Runnable() {
#Override
public void run() {
while(isRunning){
// do your network stuff
}
}
};
and again, don't forget to finish it whenever the service finishes with:
isRunning = false;