I am converting my HTTP calls to asynchronous calls from synchronous ones. Because the connection is running in the background the data isn't there when I originally set my list adaptor. How can I get the list adaptor to update after my HTTP call? I've tried a few things like not setting the adaptor until data gets sent back and setting the adaptor again, but nothing has worked. Here's my current oncreate code
protected void onCreate(Bundle savedInstanceState) {
overridePendingTransition(R.layout.anim_out,R.layout.anim_in);
setTheme(R.style.Theme_D_theme);
setContentView(R.layout.news_fragment);
super.onCreate(savedInstanceState);
text = (TextView) this.findViewById(R.id.nomore);
list = (ListView) this.findViewById(R.id.newslist);
list.setDividerHeight(2);
new MyAsyncTask().execute("THIS");
list.setOnItemClickListener(this);
list.setCacheColorHint(Color.WHITE);
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
}
And my AsyncTast
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}
in on post execution add this line. in the end.
x.add(temp);
adapter.notifyDataSetChanged();
Do this way
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
//UPDATE HERE
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
list.setAdapter(adapter);
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}
Related
I am new in android, i want to update my list view when ever data is inserted in mysql database.I have searched in internet and i have used adapter.notifyDataSetChanged(); but i keep getting the error "The method notifyDataSetChanged() is undefined for the type ListAdapter"
Code:
public class Messages extends BaseActivity{
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_RESULTS="result";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "message_recd";
private static final String TAG_ADD ="message_sent";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
TextView textView = (TextView) findViewById(R.id.fname);
textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
editTextName = (EditText) findViewById(R.id.editTextName);
b=(Button)findViewById(R.id.button1);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etname=(EditText)findViewById(R.id.editTextName);
if( etname.getText().toString().trim().equals("")){
etname.setError( "Cannot be left empty!" );
}
// TODO Auto-generated method stub
else{
Intent intent = getIntent();
String fName = intent.getStringExtra("fname");
String message = etname.getText().toString();
insertToDatabase(message, fName);
}
etname.setText("");
}
});
}
//send messages start
private void insertToDatabase(String message, String fName1){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String fname = params[1];
//InputStream is = null;
String message = editTextName.getText().toString();
Intent intent1 = getIntent();
String fName = intent1.getStringExtra("fname");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("message", message));
nameValuePairs.add(new BasicNameValuePair("username", fName));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/test/test.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
//is = entity.getContent();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(message, fName1);
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
if(c.has("message_recd"))
name = c.getString("message_recd");
else
address = c.getString("message_sent");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
/*ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);*/
ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);
// http://www.vogella.com/tutorials/AndroidListView/article.html
// http://stackoverflow.com/questions/8166497/custom-adapter-for-list-view
list.setAdapter(adapter);
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://10.0.2.2/progress_card/messages/get_messages.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
The notifyDataSetChanged method is defined and implemented in BaseAdapter, the supertype of SimpleAdapter. So just add a cast to BaseAdapter or SimpleAdapter.
when you perfrom any add() or remove() operation to your personlist,
call adpater.notifyDataSetChanged(); method to Update ListView
Refernce : notifyDataSetChanged example
I've a problem with parsing json from facebook graph api.
When I'm using facebook URL:https://graph.facebook.com/interstacjapl/feed?access_token=MyTOKEN to grab json it's no working, but when I copied that json (it works in browser) and paste to my webiste http://mywebsite/fb.json and change site URL in the code, it works good.
When I'm using fb graph URL it shows error:
W/System.err(5534): org.json.JSONException: No value for data
Is this problem with parsing from https or URL or code?
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
MainActivity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "https://graph.facebook.com/interstacjapl/feed?access_token=CAACEdEose0cBANLR...";
//JSON Node Names
private static final String TAG = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "message";
private static final String TAG_API = "type";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_ID,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This works
String reply = "";
BufferedReader inStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
reply = buffer.toString();
} catch (Exception e) {
//Handle Execptions
}
In my application after parsing json data i want to send the data from one activity to another activity with the help of intents. but in my second activity it shows only last array json data. it is not showing all the json parsed data in second activity.
first activity:
private class GetData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SearchActivity.this, "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("FromCityid",fromcity_bus));
nameValuePair.add(new BasicNameValuePair("Tocityid",tocity_bus));
nameValuePair.add(new BasicNameValuePair("DOJ",journey_bus));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("Response");
String message = jobj.getString("Message");
String issuceess = jobj.getString("IsSuccess");
Log.v("TAG_Message",""+message);
Log.v("TAG_Message",""+issuceess);
if(issuceess.equals("true"))
{
JSONArray routearray = result.getJSONArray("Route");
for(int i = 0; i<routearray.length(); i++)
{
companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
arrtime =routearray.getJSONObject(i).getString("ArrTime");
fare =routearray.getJSONObject(i).getString("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString( "BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
intent.putExtra("COMPANYNAME", CompanyName);
Log.v("TAG_COMPANYNAME",""+CompanyName);
intent.putExtra("COMPANYID", companyid);
intent.putExtra("BUSFARE", fare);
intent.putExtra("BUSLABEL", buslabel);
intent.putExtra("BUSTYPENAME", bustypename);
intent.putExtra("AVALIABLESEATS", avaliableseats);
// intent.putExtra("arrayListIdentifier",);
startActivity(intent);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
secondActivity:
Intent intent = getIntent();
String company_name = intent.getStringExtra("COMPANYNAME");
String company_id = intent.getStringExtra("COMPANYID");
String bus_fare = intent.getStringExtra("BUSFARE");
String bus_typename = intent.getStringExtra("BUSTYPENAME");
String bus_label = intent.getStringExtra("BUSLABEL");
String avaliable_seats = intent.getStringExtra("AVALIABLESEATS");
BusData bs = new BusData();
bs.setCompanyname(company_name);
bs.setCompanyid(company_id);
bs.setFare(bus_fare);
bs.setBuslabel(bus_label);
bs.setBustypename(bus_typename);
bs.setAvaliableseats(avaliable_seats);
bdata.add(bs);
BusDataAdapter adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
fromto is a listview.
the size of bdata is 1.
Use Bundle to pass the value from current activity to next acivity
Current Activtiy to pass data
if(issuceess.equals("true"))
{
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
intent.putExtra("json_objcet", result.toString());//result is a json object
startActivity(intent);
}
In Next activity to receive data
Intent intent = getIntent();
String json_object = intent.getStringExtra("json_objcet");
try
{
JSONObject result = new JSONObject(json_object);
JSONArray routearray = result.getJSONArray("Route");
for (int i = 0; i < routearray.length(); i++) {
String companyid = routearray.getJSONObject(i).getString("CompanyId");
String CompanyName = routearray.getJSONObject(i).getString("CompanyName");
String deptime = routearray.getJSONObject(i).getString("DepTime");
String routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
String arrtime = routearray.getJSONObject(i).getString("ArrTime");
String fare = routearray.getJSONObject(i).getString("Fare");
String hasac = routearray.getJSONObject(i).getString("HasAC");
String hasnac = routearray.getJSONObject(i).getString("HasNAC");
String hasseater = routearray.getJSONObject(i).getString("HasSeater");
String hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
String isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
String buslabel = routearray.getJSONObject(i).getString("BusLabel");
String avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
String bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bs = new BusData();
bs.setCompanyname(CompanyName);
bs.setCompanyid(companyid);
bs.setFare(fare);
bs.setBuslabel(buslabel);
bs.setBustypename(bustypename);
bs.setAvaliableseats(avaliableseats);
bdata.add(bs);
}
BusDataAdapter adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
try this code
first activity
private class GetData extends AsyncTask<String, Void, JSONObject> {
ArrayList<BusData> arrayBusData = new ArrayList<BusData>();
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SearchActivity.this, "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("FromCityid",fromcity_bus));
nameValuePair.add(new BasicNameValuePair("Tocityid",tocity_bus));
nameValuePair.add(new BasicNameValuePair("DOJ",journey_bus));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("Response");
String message = jobj.getString("Message");
String issuceess = jobj.getString("IsSuccess");
Log.v("TAG_Message",""+message);
Log.v("TAG_Message",""+issuceess);
if(issuceess.equals("true"))
{
JSONArray routearray = result.getJSONArray("Route");
for(int i = 0; i<routearray.length(); i++)
{
companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
arrtime =routearray.getJSONObject(i).getString("ArrTime");
fare =routearray.getJSONObject(i).getString("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString( "BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bData = new BusData(companyid,CompanyName,fare,buslabel,bustypename,avaliableseats,);
arrayBusData.add(bData);
}
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("bus_data", arrayBusData);
intent.putExtras(bundleObject);
startActivity(intent);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
second activity
ArrayList<BusData> arrayBusData = new ArrayList<BusData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle bundleObject = getIntent().getExtras();
arrayBusData = (ArrayList<BusData>) bundleObject
.getSerializable("requestProductItem");
BusDataAdapter adapter = new BusDataAdapter(this, arrayBusData);
fromto.setAdapter(adapter);
}
BusData class also create constructor in BusData class
public class BusData implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
what is the correct way of fixing this problem?
This is my activity code
public class MainActivity extends Activity {
JSONParser jsonParser = new JSONParser();
ItemsAdapter adapter;
ListView list;
ListView list2;
HashMap<String, String> map;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://www.*************************************************";
String img_test_url = "http://*************************************************";
ImageView imageView;
String bName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
list2 = (ListView) findViewById(R.id.listView2);
accessWebService();
}
// Async Task to access the web
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar = new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
getImageData();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
LoadData task = new LoadData();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void getImageData() {
map = new HashMap<String, String>();
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
bName = jsonChildNode.optString("id");
//map.put(bName, test1);
listData.add(new Pair<String,String>(bName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
String id = item.first;
Log.d("Bank Name", id);
List<String> cards_name = new ArrayList<String>();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Bank_Name", id));
Log.d("request!", "starting");
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
Log.d("Credite Cards", jsonResponse.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String card = jsonChildNode.optString("name");
Log.d("Card_name", card);
cards_name.add(card);
}
ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
list2.setAdapter(adapter2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
I guess this where you go wrong
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
In onPostExecute you have
getImageData();
In getImageData() you have listview item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
// network operation on main thread
This getting json object must be doen in a background thread
Also you cannot update ui from background thread
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Must be removed
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
//this should be in a separate non ui thread
For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code
Check the following link.
http://loopj.com/android-async-http/
download the jar file and paste in the lib folder and then just write few lines like for simple get methods
});
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}