I am trying to get the data from URL and convert it into String Array, but when I try to show it on TextView its show nothing. The link and itemId that I use is already right.
There's no Error warning on logcat.
I can't figure it out why.
Is there anyone can't help me?
Here's my json data
[{"image":"http://cdn-data.apps.com/category_item/05d92b217f916c9b9d87ab9121662d87.jpg"},
{"image":"http://cdn-data.apps.com/category_item/0424ef5a980255ff989fe5b20eaa5dcd.jpg"},
{"image":"http://cdn-data.apps.com/category_item/02b5bce4a9ca8fa3e53ceea2c7e273ff.jpg"},
{"image":"http://cdn-data.apps.com/category_item/dd15419113c091c93eafb3695eb65153.jpg"},
{"image":"http://cdn-data.apps.com/category_item/1ddfd2d7a489678e3c66e7f012ceb951.jpg"}]
Here's my Java code
if(in.getStringExtra("TAG_IMAGE_COUNT").equals("0")) {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.GONE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.GONE);
}
else {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.VISIBLE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.VISIBLE);
try {
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String json = reader.readLine();
//JSONObject jsonObject = new JSONObject(json);
JSONArray arr = new JSONArray(httpResponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
String[] stringArr = list.toArray(new String[list.size()]);
TextView array = (TextView)findViewById(R.id.testarray);
array.setText(Arrays.toString(stringArr));
Log.d("", json);
//Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I try to show it on testarray but its show nothing.
First of all your have to parse a String not Httpresponse:
here you do:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
JSONArray arr = new JSONArray(httpResponse);
Change a little like:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
And finally set the list data as you want in your textView out of the background thread.
you should not use any UI thread views (e.g button, textview, edittext ..) in background thread.
EDIT:
private class GetImages extends AsyncTask<String, Integer, ArrayList<String>>{
ArrayList<String> list = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(String... params) {
try {
HttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
//use this result and put in your textView
}
}
Related
I´m new in Java programming and have a question. I found this post and tried to use this method to pass my values from doInBackground method to onPostExecute method. But Android Studio 2.3 does not allow it.
Android Studio underline my #Override at onPostExecute:
#Override
protected void onPostExecute(String s){
//super.onPreExecute();
// Create adapter for ListView (Universal Image Loader)
AngeboteListAdapter adapter = new AngeboteListAdapter(this, R.layout.angebote_list_view_adapter, dataList);
mListView.setAdapter(adapter);
Toast.makeText(AngeboteActivity.this,"onPostExecute",Toast.LENGTH_LONG).show();
}
and my QueryResult in doInBackground:
#Override
protected QueryResult doInBackground(String... params){
try
{
Here is all the code:
public class MultiplyTask extends AsyncTask<String,Void,ArrayList<Artikel>>{
private class QueryResult {
ArrayList<Artikel> dataList;
public QueryResult(ArrayList<Artikel> dataList) {
this.dataList = dataList ;
}
}
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected void onPostExecute(String s){
//super.onPreExecute();
// Create Adapter for ListView (UniversalImageLoader)
AngeboteListAdapter adapter = new AngeboteListAdapter(this, R.layout.angebote_list_view_adapter, dataList);
mListView.setAdapter(adapter);
Toast.makeText(AngeboteActivity.this,"onPostExecute",Toast.LENGTH_LONG).show();
}
String data ="";
#Override
protected QueryResult doInBackground(String... params){
try
{
URL url = new URL("https://myjson.com");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][5];
//Fill Array with response
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("Artikelnummer"));
matrix[i][1] = String.valueOf(obj.getDouble("Preis"));
matrix[i][2] = obj.getString("Von");
matrix[i][3] = obj.getString("Bis");
matrix[i][4] = obj.getString("art_link");
}
//new Arrays
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
//Array sort
for (int i = 0; i < matrix.length; i++) {
all_art_nr[i] = matrix[i][0];
all_preis[i] = matrix[i][1];
all_von[i] = matrix[i][2];
all_bis[i] = matrix[i][3];
all_link[i] = matrix[i][4];
}
//Fill Arraylist
ArrayList<Artikel> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
Artikel angebote = new Artikel(all_art_nr[i], all_preis[i], all_von[i], all_bis[i], all_link[i]);
dataList.add(angebote);
}
return new QueryResult(dataList);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Android Studio want to change QueryResult into Arraylist and the #Override does not override method from his superclass, if i take QueryResult in doINBackground out, he can override the superclass method. Thanks in advance.
When you extends the Asynctask check the parameter:
extends Asynctask<Params, Progress, Result>
So if you want to pass a String to your doInBackround which will return a QueryResult to your onPostExecute you should extends like this:
extends Asynctask<String, Void, QueryResult>
I have some issues with using multiple jsonobjects I want to use "posts" and "attachments" jsonobjects.
but I tried to use the line and another for loop for attachments jsonObject but it doesnt work.
String postInfo = jsonObject.getString("attachments");
My Json looks like this:
{"posts":[
{"title":"Title","content":"Post content"}
]
}
{"attachments":[
{"url":"http://www.something.com"}
]
}
Java code:
public class NewsActivity extends FragmentActivity {
ViewPager viewPager;
int category;
ArrayList titleList;
ArrayList postList;
ArrayList imgList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent i = getIntent();
category=i.getIntExtra("locationInfo",-1);
try {
String encodedCatName = URLEncoder.encode(Integer.toString(category), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://www.something.co/api/get_category_posts/?id=" + encodedCatName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
postList = new ArrayList();
titleList = new ArrayList();
imgList = new ArrayList();
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not find", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String postInfo = jsonObject.getString("posts");
Log.i("Content", postInfo);
JSONArray arr = new JSONArray(postInfo);
JSONArray attachments = jsonObject.getJSONArray("attachments");
for(int i=0; i< attachments.length(); i++){
String url = "";
url = attachments.getJSONObject(i).getString("url");
imgList.add(url);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = "";
String post = "";
title = jsonPart.getString("title");
post = jsonPart.getString("content");
if (title != "" && post != "") {
message += title + ": " + post + "\r\n";
titleList.add(title);
postList.add(post);
}
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager(),category,titleList,postList,imgList);
viewPager.setAdapter(swipeAdapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find ", Toast.LENGTH_LONG);
}
}
}
}
The type related to 'attachments' is an array, therefore you should call something like:
JSONArray attachments = jsonObject.getJSONArray("attachments")
for(int i=0; i< attachments.length(); i++){
attachments.getJSONObject(i).getString("url");
}
I have data coming in as a JSON Array and I am parsing it. Here is an example:
[{"Tag":"Amusement Parks","Category":"Attractions"},{"Tag":"Restaurant","Category":"Food"}, etc]
What I want to do is to make every "Category" a Header in the ListView and every "Tag" a child of that Header. Right now I am hard coding the Header's and adding the Tags like this:
listDataHeader.add("Attractions");
listDataHeader.add("Food");
listDataHeader.add("Lodging");
...
JSONArray jArray = new JSONArray(result);
Log.d("Array Length: ", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
if (json.getString("Category").equals("Attractions")) {
tempAttractions.add(json.getString("Tag"));
}
if (json.getString("Category").equals("Food")) {
tempFood.add(json.getString("Tag"));
}
if (json.getString("Category").equals("Lodging")) {
tempLodging.add(json.getString("Tag"));
}
}
}
protected void onPostExecute(Void... params) {
listDataChild.put(listDataHeader.get(0), tempAttractions);
listDataChild.put(listDataHeader.get(1), tempFood);
listDataChild.put(listDataHeader.get(2), tempLodging);
But instead of hard coding the categories, I want to dynamically add categories from the JSON data.
So basically, something like this...
//obviously pseudo code...
if (json.getString("Category") exists as a header already) {
add json.getString("Tag") as a child under that group
//or if it doesn't exist
} else {
add a header header and add json.getString("Tag") as a child under that group
}
I think this is more of a conceptual problem, I can't seem to grasp a way to get this done. Any ideas? Thanks!
Full Code
public class CategorySelect extends BaseActivity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
List<String> listAttractions;
List<String> listFood;
List<String> listLodging;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_select);
// initialize Nav Drawer
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
progress = new ProgressDialog(this);
progress.setMessage("Loading...Please Wait");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Attractions");
listDataHeader.add("Food");
listDataHeader.add("Lodging");
listAttractions = new ArrayList<String>();
listFood = new ArrayList<String>();
listLodging = new ArrayList<String>();
new FillCategories().execute();
}
private class FillCategories extends
AsyncTask<Integer, Void, Void> {
List<String> tempAttractions = new ArrayList<String>();
List<String> tempFood = new ArrayList<String>();
List<String> tempLodging = new ArrayList<String>();
#Override
protected ArrayList<Location> doInBackground(Integer... params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
String action = "nav";
nameValuePairs.add(new BasicNameValuePair("action", action));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = 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(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
Log.d("Array Length: ", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
//Log.d("Text", json.getString("Txt"));
if (json.getString("Cat").equals("Attractions")) {
tempAttractions.add(json.getString("Txt"));
if (json.getString("Tag").equals(null)) {
tempAttractionsTags.add(json.getString("Txt"));
} else {
tempAttractionsTags.add(json.getString("Tag"));
}
}
if (json.getString("Cat").equals("Food")) {
tempFood.add(json.getString("Txt"));
if (json.getString("Tag").equals(null)) {
tempFoodTags.add(json.getString("Txt"));
} else {
tempFoodTags.add(json.getString("Tag"));
}
}
if (json.getString("Cat").equals("Lodging")) {
tempLodging.add(json.getString("Txt"));
if (json.getString("Tag").equals("")) {
tempLodgingTags.add(json.getString("Txt"));
Log.d("Tag", "Is Null");
} else {
tempLodgingTags.add(json.getString("Tag"));
Log.d("Tag Not Null", json.getString("Tag"));
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
protected void onPostExecute(Void... params) {
listDataChild.put(listDataHeader.get(0), tempAttractions);
listDataChild.put(listDataHeader.get(1), tempFood);
listDataChild.put(listDataHeader.get(2), tempLodging);
}
}
}
You can do something like this
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
if (listDataChild.get(json.getString("Category")) == null) {
tempList = new ArrayList<String>();
tempList.add(json.getString("Tag"));
listDataChild.put(json.getString("Category"), tempList );
}else{
tempList = listDataChild.get(json.getString("Category"));
tempList.add(json.getString("Tag"));
listDataChild.put(json.getString("Category"), tempList );
}
You can use this library : library, it is very simple and very efficient
How can I remove any null values from an array.
public class RecipeMethodActivity extends ListActivity {
Intent myIntent;
String value;
TextView editvalue;
TextView buttonPressed;
Intent intent;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result2 = null;
final Recipe[] mRecipesArray = { new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
if(!recipes[i].name.equals(value)){
recipes[i].steps = null;
Recipe[] tmp = new Recipe[recipes.length - 1];
//int j = 0;
//for (int k = 0; k < recipes.length; k++) {
// if (j != 1) {
// tmp[j++] = recipes[i];
// }
//}
recipes = tmp;
} else {
ret.add(recipes[i].name);
}
}
return ret;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
value = getIntent().getStringExtra("searchValue");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_name=json_data.getString("recipename");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, MethodActivity.class);
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
it returns a list view which when clicked should take you to the matching recipe but if i ask for Earth Destruction I get the portal cake recipe methods.
Thanks
This line of code is a problem
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
Instead of using mRecipesArray[position] use ret.get(position).steps
and declare ArrayList<Recipe> ret = new ArrayList<Recipe>(); outside of the FetchRecipesRawArray() method so that it can be accessed inside onListItemClick() method.
also modify your code in FetchRecipesRawArray()
else {
ret.add(recipes[i]);
}
Hope this will help you..
I have the following class:
public class RandomDrunkQuotes extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("uDrew Debug", "Made it into onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("uDrew Debug", "main Layout Loaded");
//Add AdMob viewer
AdView adViewer = (AdView)this.findViewById(R.id.adViewer);
adViewer.loadAd(new AdRequest());
Log.i("uDrew Debug", "Calling getServerData");
//Get Server Data and handle
getServerData();
}
public static final String KEY_121 = "http://www.url.com/android.php"; //i use my real ip here
private void getServerData() {
//Declare variables
InputStream is = null;
String result = "";
String strQuote = "";
String strID = "";
String strFName = "";
String strLInitial = "";
String strCity = "";
String strState = "";
String strDate = "";
Integer intLikes = 0;
Integer intHates = 0;
String strFNameSaid = "";
String strLInitialSaid = "";
Integer intBuzz = 0;
String strBuzzed = "";
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
Log.i("uDrew Debug", "Declared variables");
//Declare inflater in order to inflate a layout for each quote
LinearLayout l = (LinearLayout) findViewById(R.id.myMainLayout);
LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.url.com/android.php");
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());
}
//parse json data
try{
Log.i("uDrew Debug", "Trying to Parse JSON Data");
//Place JSON data into array one item at a time
JSONArray jArray = new JSONArray(result);
//Loop through each record in the database
//Get ListView
ListView lv= (ListView)findViewById(R.id.listview);
// create the grid item mapping
String[] from = new String[] {"lblQuote", "lblBuzzed", "lblShared", "lblSaid", "lblLikes", "lblHates", "lblLocation", "lblDate"};
int[] to = new int[] { R.id.lblQuote, R.id.lblBuzzed, R.id.lblShared, R.id.lblSaid, R.id.lblLikes, R.id.lblHates, R.id.lblLocation, R.id.lblDate };
for(int i=0;i<jArray.length();i++){
Log.i("uDrew Debug", "Made it into JSONArray Loop");
//Get this record
JSONObject json_data = jArray.getJSONObject(i);
//Put each result into variables for later handling
strFName = json_data.getString("FName");
strLInitial = json_data.getString("LInitial");
strCity = json_data.getString("City");
strState = json_data.getString("State");
strDate = json_data.getString("Date");
strQuote = json_data.getString("Quote");
intLikes = Integer.parseInt(json_data.getString("Likes"));
intHates = Integer.parseInt(json_data.getString("Hates"));
strFNameSaid = json_data.getString("FNameSaid");
strLInitialSaid = json_data.getString("LInitialSaid");
intBuzz = Integer.parseInt(json_data.getString("Buzz"));
Log.i("uDrew Debug", "Made it past JSON Parsing");
switch(intBuzz){
case 1:
strBuzzed = ("One Beer\nSyndrome");
break;
case 2:
strBuzzed = ("Buzzed");
break;
case 3:
strBuzzed = ("Drunk");
break;
case 4:
strBuzzed = ("Trashed");
break;
case 5:
strBuzzed = "Retarded";
break;
}
HashMap<String, String> map = new HashMap<String, String>();
map.put("lblQuote", strQuote);
map.put("lblBuzzed", strBuzzed);
map.put("lblShared", strFName + " " + strLInitial);
map.put("lblSaid",strFNameSaid + " " + strLInitialSaid);
map.put("lblDate", strDate);
map.put("lblLocation", strCity + ", " + strState);
map.put("lblLikes", intLikes.toString());
map.put("lblHates", intHates.toString());
fillMaps.add(map);
}//End For loop
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.myviews, from, to);
lv.setAdapter(adapter);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
I'd like to know how to refresh the data retrieved from the server in the quickest fashion. Right now I have an Refresh button in the options button that calls getServerData(); but this seems to take a very long time. Any thoughts are welcome.
You should create an AsyncTask and call getServerData() method from its doInBackground() method. This method must return the data from the server. Then in onPostExecute() method you should populate the ListView with this data.