I have a ListView with a SimpleAdapter. The Data for the ListView comes from json. I want to update the ListView every 5 min.
That works fine... But the ListView is allway a double. All items are to times in the ListView. Why? And wenn I update then 3 times....
I try
setListAdapter(null);
and
mylist.clear();
no effect
public class StartActivity extends ListActivity {
TextView text_1,text_2 ;
private Timer autoUpdate;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
Button btnShowLocation;
// GPSTracker class
GpsData gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
btnShowLocation = (Button) findViewById(R.id.report_btn);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(StartActivity.this, ReportActivity.class);
startActivity(intent);
}
});
new task().execute();
}
#Override
public void onResume() {
super.onResume();
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
new task().execute();
}
});
}
}, 0, 300000); // updates each 5 min
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(StartActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Status Update...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
//mylist.clear();
JSONObject json = jsonFunctions.getJSONfromURL("http://my.de", mlat, mlon);
try{
//String text = getString(R.string.report_TJ);
JSONArray earthquakes = json.getJSONArray("uTraf");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("first", "Stau: " + e.getString("road") + ", " + e.getString("county"));
map.put("second", e.getString("timestamp") + ", " + e.getString("suburb"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
//setListAdapter(null);
ListAdapter adapter = new SimpleAdapter(StartActivity.this, mylist , R.layout.main,
new String[] { "first", "second" },
new int[] { R.id.item_title, R.id.item_subtitle });
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(StartActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
this.progressDialog.dismiss();
}
}
#Override
public void onPause() {
autoUpdate.cancel();
super.onPause();
}
}
Your problem is with the call mylist.add(map); inside your for loop in doInBackground.
Your creating a map is fine but by calling the add function on mylist you are appending it to the list and not overriding the current map with the same keys. If you want to update existing items in the listview as opposed to just overwriting with fresh data then the mylist variable should probably be a HashMap also.
EDIT - Solution:
In doInBackground, just before you enter the loop to process data
(for(int i=0;i<earthquakes.length();i++))
call mylist.clear(). This will empty your array list before you start to add new data to it.
add mylist = new ArrayList<HashMap<String, String>>(); in doInBackGround() method
try{
//String text = getString(R.string.report_TJ);
JSONArray earthquakes = json.getJSONArray("uTraf");
mylist = new ArrayList<HashMap<String, String>>();
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("first", "Stau: " + e.getString("road") + ", " + e.getString("county"));
map.put("second", e.getString("timestamp") + ", " + e.getString("suburb"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
Related
I'm working on an Android app that uses information form an API and displays it in a list view. It works, but I can't figure out how to implement Swipe to Refresh properly. Right now when it refreshes it doesnt update the data in the lists TextView fields, but adds more of them underneath. I'm very new to this and would appreciate help figuring it out.
Here is the code I have so far.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, R.id.list);
lView.setAdapter(adp);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "URL";
String url2 = "URL";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try { /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try { /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lv.setAdapter(adapter);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
Hope this makes some sense and would really apreciate any help! If I can get that working, I will probably have more questions, but right now one thing at a time. :P
Thanks! :)
In your swipe refresh listener when you call your async task, your are creating a new adapter every time. simply call notifyDataChanged on your data.
In your on background task first check if the data is already present in your priceList then don't add the item in your list.
Or you can first clear the list and then add all the result from json in to price list.
Here is the code which clears list on swipe refresh:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ListAdapter adapter;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lView.setAdapter(adapter);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "https://miningpoolhub.com/index.php?page=api&action=getuserallbalances&api_key=MyApiKey";
String url2 = "https://api.coinmarketcap.com/v1/ticker/";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try {
coinList.clear(); /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
Coin coinObj= new Coin(/*pass the arguments*/);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try {
priceList.clear(); /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
// ListAdapter adapter = new SimpleAdapter(
// MainActivity.this, coinList,
// R.layout.list_item, new String[]{"coin", "confirmed",
// "exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
// R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
adapter.notifyDataSetChanged();
}
}
}
I'm fresher to android. I created android ListView using JSON WebService. I want old ListView data to be clear and reset again new data when getdata button is clicked again . Help me, thanks in advance.
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
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();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
JobNo =(EditText)findViewById(R.id.editText1);
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();
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.clear();
params.add(new BasicNameValuePair("JobNo",JobNo.getText().toString()));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
if (JobNo.getText().toString().equals(""))
{
Toast.makeText(MainActivity.this, "You did not enter a JobNo", Toast.LENGTH_SHORT).show();
}
else {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime); HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
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 "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
Whenever you want to update your list clear the old data by
if(CargoTracklist != null){
CargoTracklist.clear();
// Add new Data to CargoTracklist
CargoTracklist.add("new data");
if(adapter != null){
adapter.notifyDataChaned();
}
}
i have done JSON parsing without using async task, it is working fine in gingerbread(2.3)
but when i am running the same project on ICS(ice cream sandwich) application is crashing, i heard somewhere that i will have to do the parsing in asynctask but i am new to android and unable to do that can someone help me ............
here's my JSON class :-
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//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){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
and here's my MAinActivity which is using JSON class :-
public class MainActivity extends ListActivity {
Context context;
ArrayList<String> contentList,slugList;
ArrayList<HashMap<String, String>> mylist;
JSONObject json;
JSONArray latest;
ImageView bck;
String shareUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
bck = (ImageView) findViewById(R.id.bckbtn);
mylist = new ArrayList<HashMap<String, String>>();
contentList=new ArrayList<String>();
slugList=new ArrayList<String>();
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");
context=this;
try{
latest = json.getJSONArray("posts");
for(int i=0;i<latest.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = latest.getJSONObject(i);
String name = e.getString("title_plain");
String content = e.getString("content");
contentList.add(content);
String chng = "–";
String fnl_Str = name.replace(chng, "");
String slug = e.getString("slug");
slugList.add(slug);
map.put("id", String.valueOf(i));
map.put("name", fnl_Str);
map.put("date", e.getString("date"));
shareUrl ="http://madhuridixit-nene.com/latest/post/";
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_latest_tab,
new String[] { "name"},
new int[] { R.id.item_title});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position); */
//Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(context,WebViewActivity.class);
intent.putExtra("content", contentList.get(position));
intent.putExtra("shareUrl", shareUrl+slugList.get(position));
intent.putExtra("tab_value", 1);
startActivity(intent);
}
});
}
plz help me to get this working using AsyncTask .......
Change your code Using AsyncTask as for Getting data from server :
private class LongOperation extends AsyncTask<String, Void,
ArrayList<HashMap<String, String>>> {
ArrayList<String> contentList,slugList;
ArrayList<HashMap<String, String>> mylist;
JSONObject json;
JSONArray latest;
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>>
doInBackground(String... params) {
mylist = new ArrayList<HashMap<String, String>>();
contentList=new ArrayList<String>();
slugList=new ArrayList<String>();
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com"+
"/wp/?json=get_category_posts&slug=latest");
try{
latest = json.getJSONArray("posts");
for(int i=0;i<latest.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = latest.getJSONObject(i);
String name = e.getString("title_plain");
String content = e.getString("content");
contentList.add(content);
String chng = "–";
String fnl_Str = name.replace(chng, "");
String slug = e.getString("slug");
slugList.add(slug);
map.put("id", String.valueOf(i));
map.put("name", fnl_Str);
map.put("date", e.getString("date"));
shareUrl ="http://madhuridixit-nene.com/latest/post/";
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return mylist;
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(this, result ,
R.layout.activity_latest_tab,
new String[] { "name"},
new int[] { R.id.item_title});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Intent intent=new Intent(MainActivity.this,WebViewActivity.class);
intent.putExtra("content", contentList.get(position));
intent.putExtra("shareUrl", shareUrl+slugList.get(position));
intent.putExtra("tab_value", 1);
startActivity(intent);
}
});
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
and execute AsyncTask from onCreate of Activity as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
bck = (ImageView) findViewById(R.id.bckbtn);
new LongOperation().execute(""); // execute here
// your code here.....
finally you must read about AsyncTask for next use from here
http://developer.android.com/reference/android/os/AsyncTask.html
The problem is not with parsing of json data. The problem here is that you've been trying to make network connection on the Main thread. Network connections are long tasks and should be run in a separate thread. What you have to do here is basically put your
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");
line in the AsyncTask
I hope this helps!
First of all, consider to post Logcat output whenever you are facing issue/getting exceptions in Android.
Now, your current exception is NetworkOnMainThreadException, which is just because of you are making a web call directly on Main Thread.
From Android 3.0, Android has announced you can't do it directly on Main Thread.
To resolve this issue, you can either implement AsyncTask or write down the below code before making a web call:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Read more: Android StrictMode – NetworkOnMainThreadException
yes finally i have done it thanks for all the ideas ......
I have created another class for asynctask like this :-
class MyAsyncTask extends AsyncTask> > {
ArrayList> mylist = new ArrayList>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
// TODO Auto-generated method stub
mylist = new ArrayList<HashMap<String, String>>();
contentList=new ArrayList<String>();
slugList=new ArrayList<String>();
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");
try{
latest = json.getJSONArray("posts");
for(int i=0;i<latest.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = latest.getJSONObject(i);
String name = e.getString("title_plain");
String content = e.getString("content");
contentList.add(content);
String chng = "–";
String fnl_Str = name.replace(chng, "");
String slug = e.getString("slug");
slugList.add(slug);
map.put("id", String.valueOf(i));
map.put("name", fnl_Str);
map.put("date", e.getString("date"));
shareUrl ="http://madhuridixit-nene.com/latest/post/";
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
showProgress.setVisibility(View.VISIBLE);
return mylist;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(LAtestTab.this, result , R.layout.activity_latest_tab,
new String[] { "name" },
new int[] { R.id.item_title});
LAtestTab.this.setListAdapter(adapter);// If Activity extends ListActivity
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
showProgress.setVisibility(View.GONE);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(context,WebViewActivity.class);
intent.putExtra("content", contentList.get(position));
intent.putExtra("shareUrl", shareUrl+slugList.get(position));
intent.putExtra("tab_value", 1);
startActivity(intent);
}
});
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgress.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
showProgress.setVisibility(View.VISIBLE);
}
}
I have an EditText which takes a String from the user and a searchButton.
When the searchButton is clicked, it will search through the XML file and display it in the ListView.
I am able to take input from the user, search through the XML file and display the usersearched value in the ListView also.
What I want is to display a ProgressDialog after the searchButton is clicked like "PLEASE WAIT...RETRIEVING DATA..." or something like that and dismiss it when the data is shown.
public class Tab1Activity extends ListActivity {
private Button okButton;
private Button searchButton;
Toast toast;
String xml;
private TextView searchText;
private String searchTextString;
HashMap<String, String> o;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
searchButton = (Button) findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.print("hello");
searchText = (TextView) findViewById(R.id.search_text);
searchTextString = searchText.getText().toString();
readXml(searchTextString);
}
});
}
private void readXml(String searchTextString1) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
//Here XMLfunctions is class name which parse xml
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if ((numResults <= 0)) {
Toast.makeText(Tab1Activity.this, "Testing xmlparser",
Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
String nameMapString = XMLfunctions.getValue(e, "name");
if ( nameMapString.toLowerCase().indexOf(searchTextString1.toLowerCase()) != -1 ) // != -1 means string is present in the search string
{
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", XMLfunctions.getValue(e, "name"));
map.put("Score", XMLfunctions.getValue(e, "score"));
mylist.add(map);
}
}
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.parsexml, new String[] { "name", "Score" }, new int[] {
R.id.item_title, R.id.item_subtitle });
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(Tab1Activity.this,
"Name "+o.get("name")+" Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
Declare your progress dialog:
ProgressDialog progress;
When you're ready to start the progress dialog:
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
and to make it go away when you're done:
progress.dismiss();
Here's a little thread example for you:
// Note: declare ProgressDialog progress as a field in your class.
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new Thread(new Runnable() {
#Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
#Override
public void run()
{
progress.dismiss();
}
});
}
}).start();
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
try {
String xmlUrl = urls[0];
URL u = new URL(xmlUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lengthOfFile = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; // total = total + len1
publishProgress("" + (int) ((total * 100) / lengthOfFile));
xmlContent += buffer;
}
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Retrieving latest announcements...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
While creating the object for the progressbar check the following.
This fails:
dialog = new ProgressDialog(getApplicationContext());
While adding the activities context works..
dialog = new ProgressDialog(MainActivity.this);
You should not execute resource intensive tasks in the main thread. It will make the UI unresponsive and you will get an ANR. It seems like you will be doing resource intensive stuff and want the user to see the ProgressDialog. You can take a look at http://developer.android.com/reference/android/os/AsyncTask.html to do resource intensive tasks. It also shows you how to use a ProgressDialog.
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
private class GetData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Calendar.this,
"", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
String status = jobj.getString("status");
if(status.equals("true"))
{
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", array.getJSONObject(x).getString("name"));
map.put("date", array.getJSONObject(x).getString("date"));
map.put("description", array.getJSONObject(x).getString("description"));
list.add(map);
}
CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);
list_of_calendar.setAdapter(adapter);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
and execute it in OnCreate Method like new GetData().execute();
where Calendar is my calendarActivity and i have also created a CalendarAdapter to set these values to a list view.
Hello i have this Json output and i am calling in my android app. I am able to get picture path but how can i display picture instead of path . here is the code
public class Test extends ListActivity {
Prefs myprefs = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
this.myprefs = new Prefs(getApplicationContext());
// install handler for processing gui update messages
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/proj/androidjson.php?identifier=" +
Test.this.myprefs.getPersonalno());
try{
JSONArray earthquakes = json.getJSONArray("services");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("pic", "Picture : " + e.getString("employeepic"));
map.put("serviceinfo", "" + e.getString("employeename")+ " : "+ e.getString("starttime")
+" To " + e.getString("endtime"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "pic", "serviceinfo" },
new int[] { R.id.item_title, R.id.item_subtitle });
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(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
This is path which i am getting in my android app
pictures/file83915.jpg
Here i am calling picture
map.put("pic", "Picture : " + e.getString("employeepic"));
I have used this class for downloading image from server
Hope it will help you...!! When you have got your image URLs list from your server or any source, then used it like this to download that particular Image.
GetImage.downloadFile("pictures/file83915.jpg", new ImageDownloaded()
{
#Override
public void imageDownloaded(Bitmap result){
image.setImageBitmap(result);
}
#Override
public void imageDownloadedFailed(){
}
});
Where the GetImage class is:
public class GetImage
{
public static void downloadFile(final String fileUrl, final ImageDownloaded img)
{
AsyncTask<String , Void, Bitmap> task = new AsyncTask<String , Void, Bitmap>()
{
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bmImg;
URL myFileUrl =null;
if(fileUrl.equals(""))
{
return null;
}
try
{
myFileUrl= new URL("http://yourURl/" +fileUrl.replace(" ", "%20"));
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
return bmImg;
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap results)
{
if(results != null)
img.imageDownloaded(results);
else
img.imageDownloadedFailed();
}
};
task.execute("");
}
public static abstract class ImageDownloaded
{
public abstract void imageDownloaded(Bitmap result);
public abstract void imageDownloadedFailed();
}
}
I used CustomAdapter class to show the data in the list with Images like this.
in the method getView() I used this thread like this.
public View getView(params....)
{
View row ;//Inflataion blah blah
Bitmap thumb = myCustomObject.getBitmap();
final ImageView image = (ImageView) row.findViewById(R.id.image);
if(thumb == null)
{
GetImage.downloadFile(myCustomObject.getImagePath(), new ImageDownloaded()
{
#Override
public void imageDownloaded(Bitmap result){
myCustomObject.setBmp(result);
image.setImageBitmap(myCustomObject.getBitmap());
}
#Override
public void imageDownloadedFailed(){
}
});
}
else
image.setImageBitmap(thumb);
}
MyCustomObject is my class that encapsulates the data from server as well as Image from server and implements Parcelable interface. First I get data through JSON and then get Image in Adapter. It can also be passed to the any DetailActivity