Update CustomArrayAdapter after AsyncTask in Android - android

I m having a CustomArrayAdapter which I m using to update a a custom ListView.
This is working fine but when I m trying to update the view
after getting results in AsyncView onPostExecute using notifyDataSetChanged it is not updating nor it is returning any exceptions.
The code for onCreate -
public class MainActivity extends ListActivity {
String[] presidents = {"Dwight D. Eisenhower","John F. Kennedy","Lyndon B. Johnson","Richard Nixon","Gerald Ford","Jimmy Carter","Ronald Reagan","George H. W. Bush","Bill Clinton","George W. Bush","Barack Obama"};
String[] pics = {"5237","5438", "184", "184", "184", "184", "184", "184", "184", "184", "184", "184"};
private String[] names;
private String[] pid;
ListActivity obj;
CustomArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obj = this;
try {
adapter =new CustomArrayAdapter(obj, presidents, pics);
setListAdapter(adapter);
new DownloadTextTask().execute("http://nvoids.com/rest/hello/users/");
} catch(Exception e) {
Log.d("Listview1", "Exception: " + e.getLocalizedMessage());
}
}
The AsyncTask's onPostExecute -
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result.substring(1, 10) ,Toast.LENGTH_SHORT).show();
try
{
JSONArray jarr = new JSONArray(result);
names = new String[jarr.length() -1];
pid = new String[jarr.length() -1];
for (int i =0; i< jarr.length(); i++) {
JSONObject jObj = new JSONObject(jarr.get(i).toString());
names[i] = jObj.getString("value");
pid[i] = jObj.getString("pid");
}
super.onPostExecute(result);
adapter =new CustomArrayAdapter(obj, names, pid);
adapter.notifyDataSetChanged();
} catch(Exception e) {
Log.d("ListView1", "after getting string: " + e.getLocalizedMessage());
}
}
By the way the CustomArrayAdapter class if required -
public class CustomArrayAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] presidents;
private final String[] imageIds;
public CustomArrayAdapter(Activity context,String[] presidents, String[] imageIds) {
super(context, R.layout.lvrowlayout, presidents);
this.context = context;
this.presidents = presidents;
this.imageIds = imageIds;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
//---print the index of the row to examine---
Log.d("Listview1",String.valueOf(position));
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.lvrowlayout, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtPresidentName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
txtTitle.setText(presidents[position]);
//imageView.setImageResource(imageIds[position]);
new DownloadImageTask((ImageView) imageView )
.execute("http://nvoids.com/dir/image_" + imageIds[position] + ".jpeg");
return rowView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Log.d("CustomArrayGetImage Error", urldisplay);
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("CustomArrayGetImage Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
EDIT -
As in the answers passing the parameters also does not work -
try {
adapter =new CustomArrayAdapter(obj, presidents, pics);
setListAdapter(adapter);
new DownloadTextTask(adapter).execute( "http://nvoids.com/rest/hello/users/");
} catch(Exception e) {
Log.d("Listview1", "Exception: " + e.getLocalizedMessage());
}
In the DownloadAsyncTask -
private class DownloadTextTask extends AsyncTask<String, Void, String> {
CustomArrayAdapter ca;
public DownloadTextTask(CustomArrayAdapter ca) {
this.ca = ca;
}
......
protected void onPostExecute(String result) {
//Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), result.substring(1, 10) ,Toast.LENGTH_SHORT).show();
try
{
JSONArray jarr = new JSONArray(result);
names = new String[jarr.length() -1];
pid = new String[jarr.length() -1];
for (int i =0; i< jarr.length(); i++) {
JSONObject jObj = new JSONObject(jarr.get(i).toString());
names[i] = jObj.getString("value");
pid[i] = jObj.getString("pid");
ca.addAll(names[i] , pid[i]);
}
/*
super.onPostExecute(result);
adapter =new CustomArrayAdapter(obj, names, pid);
lv.setAdapter(adapter);
obj.setListAdapter(adapter);
*/
ca.notifyDataSetChanged();
} catch(Exception e) {
Log.d("ListView1", "after getting string: " + e.getLocalizedMessage());
}
}

Because, You are creating new object of Custom Adapter in AsyncTask's onPostExecute()
Like,
adapter =new CustomArrayAdapter(obj, names, pid);
adapter.notifyDataSetChanged();
Which is not set to ListView. So either write syntax for setListAdapter() to ListView in onPostExecute() (For this you need ListView reference in AsyncTask) or
Use the same object which you have created in onCreate() of Your ListActivity, Pass that adapter object in Constructor of AsyncTask and use Object in onPostExecute().

adapter =new CustomArrayAdapter(obj, names, pid);
adapter.notifyDataSetChanged();
notifyDataSetChange notify observers to update data.
So in your example you notify new adapter to update their data, but you don't attach adapter to your list.
But create each time new adapter - is not a good practise, you have to update data in your adapter (in your case list of presidents) and then call notifyDataSetChange on your existing adapter.
PS ArrayAdapter already have a list under it and you can call add and don't need to store list of presidents. In your case i think it's better to create
class PresidentsWrapper {
String name,
String photoUrl
}
And create ArrayAdapter<PresidentWrapper>
In this case you don't need any underlying structures and can do like this:
getItem(position);
add(new PresidentWrapper(...));

Related

How do I pass a JSON value to another class [duplicate]

This question already has answers here:
Passing JSONObject into another activity
(7 answers)
How to pass JSON Object to new activity [duplicate]
(3 answers)
Closed 5 years ago.
I have this class (TodosOsPaises) where I get the data from json and I want to show images from the JSON in the listView for that I'm using a custom adapter (MyAdapter) and on it picasso. The problem is I can't access the "URL_IMAGEM" in the MyAdapter class
TodosOsPaises class:
public class TodosOsPaises extends AppCompatActivity{
private String TAG = TodosOsPaises.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://**********/api/continent/any/country/all?id=siF1uXXEsltXOi5CWlSIzy7EABlnE5iF33bnNmfAHJiYXYNmjY";
ArrayList<HashMap<String, String>> listaPaises;
public String URL_IMAGEM;
String Designacao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todos_os_paises);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("PaĆ­ses");
listaPaises = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetPaises().execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
menu.findItem(R.id.spinner_cat).setVisible(false);
menu.findItem(R.id.spinner_pais).setVisible(false);
return true;
}
private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TodosOsPaises.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
final String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
String K_PAIS = jsonObject1.getString("K_PAIS");
Designacao = jsonObject1.getString("Designacao");
//String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
URL_IMAGEM = ("http://**********t" + jsonObject1.getString("URL_IMAGE_SMALL")).toString();
String Coord_LAT = jsonObject1.getString("Coord_LAT");
String Coord_LONG = jsonObject1.getString("Coord_LONG");
String Coord_Zoom = jsonObject1.getString("Coord_Zoom");
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
//pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
pais.put("Coord_LAT", Coord_LAT);
pais.put("Coord_LONG", Coord_LONG);
pais.put("Coord_Zoom", Coord_Zoom);
listaPaises.add(pais);
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin 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 for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ListView list= (ListView) (TodosOsPaises.this).findViewById(R.id.list);
ListAdapter adapter =
new MyAdapter(
(TodosOsPaises.this),
listaPaises,
R.layout.list_item,
new String[]{Designacao},
new int[]{R.id.Designacao});
list.setAdapter(adapter);
/*ListAdapter adapter = new SimpleAdapter(
TodosOsPaises.this,
listaPaises,
R.layout.list_item,
new String[]{"Designacao", },
new int[]{R.id.Designacao, });
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
Intent intent = new Intent(TodosOsPaises.this, MapsActivity.class);
intent.putExtra("data", listaPaises.get(position));
startActivity(intent);
}
});*/
Collections.sort(listaPaises, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> first, HashMap<String, String> second) {
String firstValue = first.get("Designacao");
String secondValue = second.get("Designacao");
return firstValue.compareTo(secondValue);
}
});
}
}
}
MyAdapter class:
public class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
public View getView(int position, View convertView, ViewGroup parent){
View v = super.getView(position, convertView, parent);
ImageView img = (ImageView) v.getTag();
if (img == null){
img = (ImageView) v.findViewById(R.id.imageView7);
v.setTag(img);
}
String imageFlag = (String) ((Map)getItem(position)).get(URL_IMAGEM); <<-- here it says "Cannot resolve symbol 'URL_IMAGEM'"
Picasso.with(v.getContext()).load(imageFlag).into(img);
return v;
}
}
That happens, because I don't have URL_IMAGEM defined, I think I need to get it from the TodosOsPaises.
I'm a beginner in android so I'm sorry if I made something wrong
String imageFlag = (String) ((Map)getItem(position)).get("URL_IMAGEM");
thats because their is no string varible of that name in your adapter.You have to supply the string name itseld

Android - Display data from Adapter in Listview

I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}

onResume Does Not Update ListView With New Data

I am trying to update a ListView on previous fragment after back button press. The onResume is called (verified with Toast) and the webservice runs (listView is displayed after it is cleared). The problem is that the ListView is still showing old values and not new value after accessWebService_getUsername is called. I verify the values from MySQL and even though the DB is updated, the ListView only returns old values.
#Override
public void onResume() {
Toast.makeText(getActivity(), "onResume", Toast.LENGTH_SHORT).show();
super.onResume();
adapter.clear();
getIMEI();
accessWebService_getUsername();
adapter.notifyDataSetChanged();
}
Update:
//ListView
ListView lv =(ListView)view.findViewById(R.id.listView);
adapter = new ContactsAdapter(getActivity(), arrRequest_Contact, arrRequest_NameSurname, arrRequest_MessageCount, arrRequest_Time, arrRequest_Image);
lv.setAdapter(adapter);
// Json
private class JsonGetUsername extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Contacts, Please Wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = 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(getActivity(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
//Pending 02
if (dialog.isShowing()) {
dialog.dismiss();
}
adapter.notifyDataSetChanged();
try{
ListDrawer_getUsername(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getActivity(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService_getUsername() {
JsonGetUsername task = new JsonGetUsername();
// passes values for the urls string array
task.execute(new String[] { "http://mywebsite/php/get_username.php?pIMEI="+IMEI});
}
// build hash set for list view
public void ListDrawer_getUsername() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("username_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
request_username = jsonChildNode.optString("Username");
}
accessWebService_getContacts();
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
}
UPDATE 2:
//ContactsAdpater
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Request_Contact;
List<String> Request_NameSurname;
List<String> Request_MessageCount;
List<String> Request_Time;
List<String> Request_Image;
ContactsAdapter(Context c, List<String> Request_Contact, List<String> Request_NameSurname, List<String> Request_MessageCount, List<String> Request_Time, List<String> Request_Image)
{
super(c, R.layout.activity_contacts_single, R.id.textContact, Request_Contact);
this.context=c;
this.Request_Contact=Request_Contact;
this.Request_NameSurname=Request_NameSurname;
this.Request_MessageCount=Request_MessageCount;
this.Request_Time=Request_Time;
this.Request_Image=Request_Image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtContact = (TextView) row.findViewById(R.id.textContact);
TextView txtNameSurname = (TextView) row.findViewById(R.id.textNameSurname);
TextView txtMessageCount = (TextView) row.findViewById(R.id.textMessageCount);
TextView txtTime = (TextView) row.findViewById(R.id.textTime);
ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
txtContact.setText(Request_Contact.get(position));
txtNameSurname.setText(Request_NameSurname.get(position));
txtMessageCount.setText(Request_MessageCount.get(position));
txtTime.setText(Request_Time.get(position));
Picasso.with(context).load(arrRequest_Image.get(position)).transform(new CircleTransform()).placeholder(R.drawable.ic_launcher).into(imageView);
return row;
}
}
You'll need to override the clear method in your ContactsAdapter to actually clear the lists you are storing your data in.
It looks like you'll need to clear all your lists, so if you add this to ContactsAdapter, your code should work as expected:
#Override
public void clear() {
super.clear();
Request_Contact.clear();
Request_NameSurname.clear();
Request_MessageCount.clear();
Request_Time.clear();
Request_Image.clear();
}

OnPostExecute item to ListView

Here is OnPostExecute That retuns Listitem [name1,name2,name3]:
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String result = json.getString(KEY_SUCCESS);
if (Integer.parseInt(result) == 1) {
pDialog.setMessage("Loading View");
pDialog.setTitle("Getting Friends");
//JSONArray root = new JSONArray(json);
JSONArray friend = json.getJSONArray("users");
List<String> item = new ArrayList<String>();
for (int i = 0; i < friend.length(); i++) {
JSONObject att = (JSONObject) friend.getJSONObject(i);
String res = att.getString("username");
item.add(res);
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = FriendList.edit();
edit.putString("KEY_FRIENDS", item.toString());
edit.commit();
} else {
pDialog.dismiss();
}
}else {
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
I want it In List View but im stucked, because i cant use ListAdapter in OnPostExecute.
public class FriendList extends ListActivity { ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_friend_list);
// listt = (TextView) findViewById(R.id.testyL);
// list = (TextView) findViewById(R.id.textView4);
// list = (ListView) findViewById(R.id.label);
try {
new GetFriends().execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
String u = FriendList.getString("KEY_FRIENDS", "0");
I tried to put item to SharedPref but it seems i dont know how to properly retrevie it and conter to variable that can be used by Array/List Adapter.
Here is the problem :)
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, item ));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), Logged.class);
// sending data to new activity
i.putExtra("friend", product);
startActivity(i);
}
});
}
Change GetFriends constructor add reference to FriendList object:
try {
new GetFriends(FriendList.this).execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
class:
public class GetFriends extends [...]{
private ListActivity mList;
public GetFriends(ListActivity list){
mList = list;
}
[...]
#Override
protected void onPostExecute(JSONObject json) {
//set Adapter to list
mList.
}
}

calling image from server in android

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

Categories

Resources