Image doesn't show in ImageView - android

I've tried may be every solution from here but nothing helped me. The image doesn't show on the listview only the text. I got only this in LogCat
11-04 14:46:29.319: I/(1225): {"Restaurants":[{"id":"1","name":"Restaurant- 1","menu":"Restaurant-1","image":"rest1.jpg"},{"id":"2","name":"Restaurant-2","menu":"Restaurant-2","image":"rest2.jpg"},{"id":"3","name":"Restaurant-3","menu":"Restaurant-3","image":"rest3.jpg"},{"id":"4","name":"Restaurant-4","menu":"Restaurant-4","image":"rest4.jpg"}]}
11-04 14:46:29.329: E/err(1225): rest1.jpg Restaurant-1 Restaurant-1
11-04 14:46:29.329: E/err(1225): rest2.jpg Restaurant-2 Restaurant-2
11-04 14:46:29.329: E/err(1225): rest3.jpg Restaurant-3 Restaurant-3
11-04 14:46:29.329: E/err(1225): rest4.jpg Restaurant-4 Restaurant-4
This is the code
public class Restaurants extends Activity {
ListView listView;
private StockAdaptor stockAdaptor;
String jsonResult = null;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurants);
listView = (ListView) findViewById(android.R.id.list);
image = (ImageView) findViewById(R.id.image);
new JsonReadTask().execute("http://link/GetRestaurants.php");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true; //No options
}
public void onStart() {
super.onStart();
stockAdaptor = new StockAdaptor(this); //Create a new StockAdaptor
}
public static String strFromStream(InputStream in) throws IOException { //Simple function, getting a String from an InputStream
StringBuilder out = new StringBuilder();
BufferedReader breader = new BufferedReader(new InputStreamReader(in));
String cline;
String newLine = System.getProperty("line.separator");
while ((cline = breader.readLine()) != null) {
out.append(cline);
out.append(newLine);
}
return out.toString();
}
private class StockAdaptor extends BaseAdapter { //The stocks list adaptor
class ViewHolder {
TextView name;
TextView menu;
ImageView image;
}
private LayoutInflater layoutInflater;
private RestaurantInformation[] stocks = null; //Array of stocks
private ListView stocksListView = null;
public StockAdaptor(Context context) {
super();
layoutInflater = LayoutInflater.from(context);
}
public void setStockList(RestaurantInformation[] stocksinfo) {
this.stocks = stocksinfo;
}
#Override
public int getCount() {
return stocks.length;
}
#Override
public Object getItem(int position) {
return stocks[position];
}
public RestaurantInformation[] getAll() { //Return the array of stocks
return stocks;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder; //New holder
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.restaurant_information, null);
holder = new ViewHolder();
// Creates the new viewHolder define above, storing references to the children
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.menu = (TextView) convertView.findViewById(R.id.menu);
holder.image = (ImageView) convertView.findViewById(R.id.image);
if (holder.image != null) {
if (holder.image.getDrawable() == null) {
new ImageDownloaderTask(holder.image, null)
.execute(stocks[position].image); //Download the image using the image
}
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(stocks[position].name);
holder.menu.setText(stocks[position].menu);
return convertView;
}
}
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
if (URLUtil.isValidUrl(params[0])) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(getRequest);
final HttpEntity httpentity = response.getEntity();
if (httpentity != null){
InputStream inputStream = null;
try {
inputStream = httpentity.getContent();
jsonResult = strFromStream(inputStream);
Log.i("", jsonResult);
return jsonResult;
} catch (IllegalArgumentException e) {
//
} finally {
httpentity.consumeContent();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.close();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
// build hash set for list view
public void ListDrwaer() {
//Log.d("data from server", "data: " + jsonResult.toString());
try {
if (jsonResult!=null) {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("Restaurants");
Vector<RestaurantInformation> vstocks = new Vector<RestaurantInformation>();
if(jsonMainNode == null)
{
Log.e("If is null", "jsonMainNode is null");
return;
}
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
RestaurantInformation stock = new RestaurantInformation();
stock.image = jsonChildNode.getString("image");
stock.name = jsonChildNode.optString("name");
stock.menu = jsonChildNode.optString("menu");
//stock.imgPath = jsonChildNode.getString("imgPath");
Log.e("err", stock.image + " " + stock.name + " " + stock.menu);
vstocks.add(stock);
}
RestaurantInformation[] stocks = new RestaurantInformation[jsonMainNode.length()];
int stockscount = jsonMainNode.length();
for (int n = 0; n < stockscount; n++)
{
stocks[n] = vstocks.get(n);
}
stockAdaptor.setStockList(stocks);
listView.setAdapter(stockAdaptor);
} else {
Toast.makeText(getApplicationContext(), "Error; jsonResult null",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView, View view) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return downloadBitmap(params[0]);
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
//
}
}
}
}
Bitmap downloadBitmap(String url) {
if(URLUtil.isValidUrl(url)){
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
try {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
}
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
return null;
}
}
}
I'm not so experienced in Java+Android and really have no idea what can be the problem.
This is the restaurants.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Activity" >
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp" />
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignLeft="#+id/image"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
UPDATE
The goal is something like this. I want to load image on the left side and next to it to have text and sub-text if is possible
UPDATE restaurant_information.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="3dp"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="" />
<TextView
android:id="#+id/menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="" />
</LinearLayout>

Your ListView is defined as layout_width="fill_parent" and layout_height="fill_parent". As such, it will take up the entire area of it's parent and since it is defined last in the layout, will be at the top of the z-order thereby obscuring your ImageView.
Give this a try:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Activity" >
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"/>
<ListView
android:id="#id/android:list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/image"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>

You're trying to download the picture from: "rest1.jpg". You need a complete URL.
You can either send the complete url inside the json response, or add it inside your code (if the part that comes before the filename is fixed)

Related

parse image from json but can not display in listview

i have json which contains image url and
i follow this tutorial ,i download source code,works fine, but when i implement same thing in my application it displays my listview is empty
when i'm debug the code i getting know ,the adapter which has to fill the list view is load the data ,but listview cant
this is my activity
public class ListNotificationActivity extends AppCompatActivity {
Toolbar toolbar;
private ProgressDialog pDialog;
private static String url = "http://staging.talentslist.com/api/user/24/notification";
ArrayList<NotificationData> notiList;
ListView listview;
NotificAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_notification);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.notification));
setSupportActionBar(toolbar);
notiList = new ArrayList<NotificationData>();
new GetList().execute(url);
listview = (ListView) findViewById(R.id.notificationList);
adapter = new NotificAdapter(getApplicationContext(), R.layout.list_item, notiList);
listview.setAdapter(adapter);
}
private class GetList extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListNotificationActivity.this);
pDialog.setMessage("Loading, please wait");
pDialog.setTitle("Connecting server");
pDialog.show();
pDialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
HttpGet httppost = new HttpGet(urls[0]);
URL urlObj = null;
try {
urlObj = new URL(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream is = urlConnection.getInputStream();
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
// int status = urlConnection.getResponseCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
NotificationData notidata = new NotificationData();
notidata.setId(object.getInt("id"));
notidata.setUser_name(object.getString("user_name"));
notidata.setTitle(object.getString("title"));
notidata.setIs_read(object.getString("is_read"));
notidata.setCreated_at(object.getString("created_at"));
notidata.setImage_link(object.getString("image_link"));
notiList.add(notidata);
}
return true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
pDialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
this is my adapter class
public class NotificAdapter extends ArrayAdapter<NotificationData> {
ArrayList<NotificationData> nDataAdapter;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public NotificAdapter(Context context, int resource, ArrayList<NotificationData> objects) {
super(context, resource);
vi = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
nDataAdapter = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.list_image);
holder.tvSender_name = (TextView) v.findViewById(R.id.sender_name);
holder.tvNoti_details = (TextView) v.findViewById(R.id.noti_details);
holder.tvDate = (TextView) v.findViewById(R.id.date);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.noimage);
new DownloadImageTask(holder.imageview).execute(nDataAdapter.get(position).getImage_link());
holder.tvSender_name.setText(nDataAdapter.get(position).getUser_name());
holder.tvNoti_details.setText(nDataAdapter.get(position).getUser_name());
holder.tvDate.setText(nDataAdapter.get(position).getCreated_at());
return v;
}
private class ViewHolder {
public ImageView imageview;
public TextView tvSender_name;
public TextView tvNoti_details;
public TextView tvDate;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
this is list item layout for listview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left sied Thumbnail image -->
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:background="#drawable/image_bg"
android:orientation="vertical"
android:padding="3dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/noimage" />
</LinearLayout>
<TextView
android:id="#+id/sender_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Notification from"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/noti_details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/thumbnail"
android:text="Notification details"
android:textColor="#343434"
android:textSize="10dip" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/name"
android:gravity="right"
android:text="Time"
android:layout_marginRight="5dip"
android:textSize="10dip"
android:textColor="#10bcc9"
android:textStyle="bold"/>
</RelativeLayout>
please help me!!
make some changes when you getting data to add all data into list.
and make separate method for set adapter like below ..
/**
* this method used set adapter into list view.
*/
private void setAdapter(){
if (adapter==null) {
adapter = new NotificAdapter(getApplicationContext(), R.layout.list_item, notiList);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else{
adapter.notifyDataSetChanged();
}
}
then after above method call in this block in your code ..
protected void onPostExecute(Boolean result) {
setAdapter();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}

ListView Not Working On Real Device

I have a problem with my listview, it works on emulator but not on real device. I tested with 2 real devices and it does not populate. I get listview data from database using json. Json result is ok as it prints to logcat and populates listview on emulator.
ListView Java:
public class ActivityRequestsFrom extends MainActivity implements AdapterView.OnItemClickListener {
______________________________________________________________________________
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_requests_from);
lv = (ListView) findViewById(R.id.listRequests);
RequestsAdapter adapter = new RequestsAdapter(this, arrRequest_Name, arrRequest_Number,
arrRequest_Username, arrRequest_Result, imageId);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
______________________________________________________________________________
class RequestsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Request_Name;
List<String> Request_Number;
List<String> Request_Username;
List<String> Request_Result;
Integer[] imgid;
RequestsAdapter(Context c, List<String> Request_Name,
List<String> Request_Number, List<String> Request_Username,
List<String> Request_Result, Integer[] imgid)
{
super(c, R.layout.activity_requests_single, R.id.textName, Request_Name);
this.context=c;
this.Request_Name=Request_Name;
this.Request_Number=Request_Number;
this.Request_Username=Request_Username;
this.Request_Result=Request_Result;
this.imgid=imgid;
}
#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_requests_single, parent, false); }
TextView txtName = (TextView) row.findViewById(R.id.textName);
TextView txtNumber = (TextView) row.findViewById(R.id.textNumber);
TextView txtUsername = (TextView) row.findViewById(R.id.textUsername);
TextView txtResult = (TextView) row.findViewById(R.id.textResult);
ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
Map<String, Integer> drawableMap = new HashMap<String, Integer>();
drawableMap.put("ok",R.drawable.request_pending_from);
drawableMap.put("pending",R.drawable.request_pending_from);
drawableMap.put("rejected",R.drawable.request_rejected_from);
drawableMap.put("blocked",R.drawable.request_blocked_from);
txtName.setText(Request_Name.get(position));
txtNumber.setText(Request_Number.get(position));
txtUsername.setText(Request_Username.get(position));
txtResult.setText(Request_Result.get(position));
//imageView.setImageResource(imgid[position]);
imageView.setImageResource(drawableMap.get(Request_Result.get(position).toLowerCase()));
return row;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView tvUsername = (TextView) view.findViewById(R.id.textUsername);
usernameSelected = tvUsername.getText().toString();
TextView tvResult = (TextView) view.findViewById(R.id.textResult);
resultSelected = tvResult.getText().toString();
if (resultSelected.equals("Pending"))
{
pendingOptions();
}
else if (resultSelected.equals("Rejected"))
{
rejectedOptions();
}
else if (resultSelected.equals("Blocked"))
{
blockedOptions();
}
else
{
}
}
ListView Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listRequest"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</ListView>
ListView Single Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/LLdummy"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="italic"
android:layout_marginLeft="10dp"
/>
<TextView
android:id="#+id/textUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textNumber"
android:layout_alignParentRight="true"
android:layout_below="#+id/textNumber"
android:text="Username"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textName"
android:layout_below="#+id/textName"
android:text="Number"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/LLdummy"
android:layout_centerVertical="true"
android:src="#drawable/request_pending_to" />
Json
private class JsonReadTask extends AsyncTask<String, Void, String> {
#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(getApplicationContext(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
try{
ListDrwaer(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getApplicationContext(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { "http://server/file.php?pIMEI="+IMEI });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("request_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String request_name = jsonChildNode.optString("Request_Name");
String request_number = jsonChildNode.optString("Request_Number");
String request_username = jsonChildNode.optString("Request_Username");
String request_result = jsonChildNode.optString("Request_Result");
arrRequest_Name.add(request_name);
arrRequest_Number.add(request_number);
arrRequest_Username.add(request_username);
arrRequest_Result.add(request_result);
System.out.println("Request_Name: "+request_name);
System.out.println("Request_Number: "+request_number);
System.out.println("Request_Username: "+request_username);
System.out.println("Request_Result: "+request_result);
}
} catch (JSONException e) {
System.out.println("Json Error Requests" +e.toString());
Toast.makeText(getApplicationContext(), "No Requests Pending", Toast.LENGTH_SHORT).show();
}
}
Call Async
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_requests_from);
...
accessWebService();
//ListView
lv = (ListView) findViewById(R.id.listRequests);
RequestsAdapter adapter = new RequestsAdapter(this, arrRequest_Name, arrRequest_Number, arrRequest_Username, arrRequest_Result, imageId);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
The problem here is that the data isn't received when the Adapter is set on the ListView. This is because the data is populated in an AysncTask which is async hronous by nature. This means that it will run in the background while the other code runs (i.e. the ListView populating.
So, in onPostExecute() you need to use notifyDataSetChanged() to let the ListView know that there is new items to populate.
#Override
protected void onPostExecute(String result) {
// your code
adapter.notifyDataSetChanged(); // this line here
}// end async task
In your example, this will obviously require you making the Adapter a member variable or passing it to your AsyncTask.

set ListView on setOnClickListener whit ID

I have listView which show image and text from MySQL DB. So far is ok but now I wonder how to make if some item is clicked to open that ID from database. Example ListView 1 is with id=1 from database ..ListView 2 is with id=2 and so on. When I click on item 2 to open that ID from DB. Any idea how can I do this?
This is xml which load the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/buttons"
android:layout_marginTop="10dp"
>
<ImageView
android:id="#+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
/>
<TextView
android:id="#+id/name"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:text="" />
</LinearLayout>
</LinearLayout>
This is the part of code which I believe I need to fix
public class Restaurants extends Activity {
ListView listView;
TextView textView, textView1;
private StockAdaptor stockAdaptor;
String jsonResult = null;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurants); //Just a listView, shown below
listView = (ListView) findViewById(android.R.id.list);
textView = (TextView) findViewById(R.id.name);
image = (ImageView) findViewById(R.id.image);
new JsonReadTask().execute("http://link/GetRestaurants.php");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(listView.getLayoutParams());
lp.setMargins(10, 10, 0, 0);
listView.setLayoutParams(lp);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Restaurants.this, RestaurantInformation.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true; //No options
}
public void onStart() {
super.onStart();
stockAdaptor = new StockAdaptor(this); //Create a new StockAdaptor
}
public static String strFromStream(InputStream in) throws IOException { //Simple function, getting a String from an InputStream
StringBuilder out = new StringBuilder();
BufferedReader breader = new BufferedReader(new InputStreamReader(in));
String cline;
String newLine = System.getProperty("line.separator");
while ((cline = breader.readLine()) != null) {
out.append(cline);
out.append(newLine);
}
return out.toString();
}
private class StockAdaptor extends BaseAdapter { //The stocks list adaptor
class ViewHolder {
TextView name;
//TextView menu;
ImageView image;
}
private LayoutInflater layoutInflater;
private RestaurantStrings[] stocks = null; //Array of stocks
private ListView stocksListView = null;
public StockAdaptor(Context context) {
super();
layoutInflater = LayoutInflater.from(context);
}
public void setStockList(RestaurantStrings[] stocksinfo) {
this.stocks = stocksinfo;// //////////////LITERALLY THIS
}
#Override
public int getCount() {
return stocks.length;
}
#Override
public Object getItem(int position) {
return stocks[position];
}
public RestaurantStrings[] getAll() { //Return the array of stocks
return stocks;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder; //New holder
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.restaurant_second, null);
holder = new ViewHolder();
// Creates the new viewHolder define above, storing references to the children
holder.name = (TextView) convertView.findViewById(R.id.name);
//holder.menu = (TextView) convertView.findViewById(R.id.menu);
holder.image = (ImageView) convertView.findViewById(R.id.image);
if (holder.image != null) {
if (holder.image.getDrawable() == null) {
new ImageDownloaderTask(holder.image, null)
.execute(stocks[position].image); //Download the image using the image
}
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(stocks[position].name);
//holder.menu.setText(stocks[position].menu);
return convertView;
}
}
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
if (URLUtil.isValidUrl(params[0])) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(getRequest);
final HttpEntity httpentity = response.getEntity();
if (httpentity != null){
InputStream inputStream = null;
try {
inputStream = httpentity.getContent();
jsonResult = strFromStream(inputStream);
Log.i("", jsonResult);
return jsonResult;
} catch (IllegalArgumentException e) {
//
} finally {
httpentity.consumeContent();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.close();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
// build hash set for list view
public void ListDrwaer() {
//Log.d("data from server", "data: " + jsonResult.toString());
try {
if (jsonResult!=null) {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
Vector<RestaurantStrings> vstocks = new Vector<RestaurantStrings>();
if(jsonMainNode == null)
{
Log.e("If is null", "jsonMainNode is null");
return;
}
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
RestaurantStrings stock = new RestaurantStrings();
stock.image = jsonChildNode.getString("image");
stock.name = jsonChildNode.optString("name");
//stock.menu = jsonChildNode.optString("menu");
//stock.imgPath = jsonChildNode.getString("imgPath");
Log.e("err", stock.image + " " + stock.name);
vstocks.add(stock);
}
RestaurantStrings[] stocks = new RestaurantStrings[jsonMainNode.length()];
int stockscount = jsonMainNode.length();
for (int n = 0; n < stockscount; n++)
{
stocks[n] = vstocks.get(n);
}
stockAdaptor.setStockList(stocks);
listView.setAdapter(stockAdaptor);
} else {
Toast.makeText(getApplicationContext(), "Error; jsonResult null",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView, View view) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return downloadBitmap(params[0]);
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
//
}
}
}
}
Bitmap downloadBitmap(String url) {
if(URLUtil.isValidUrl(url)){
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
try {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
}
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
return null;
}
}
}
If I try to put in onCreate() one setOnClickListener as you can see the app gives "Unfortunately your app has stopped"
UPDATE
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity"
android:background="#D3D3D3">
<ImageView
android:id="#+id/image"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
/>
<ListView
android:id="#id/android:list"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/image"
android:layout_alignParentTop="true"
android:divider="#android:color/transparent"
android:dividerHeight="5dp" >
</ListView>
</RelativeLayout>
Error
11-05 13:37:26.498: E/AndroidRuntime(1493): FATAL EXCEPTION: main
11-05 13:37:26.498: E/AndroidRuntime(1493): Process: com.reserveme, PID: 1493
11-05 13:37:26.498: E/AndroidRuntime(1493): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.reserveme/com.reserveme.Restaurants}: java.lang.NullPointerException
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.access$800(ActivityThread.java:135)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.os.Handler.dispatchMessage(Handler.java:102)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.os.Looper.loop(Looper.java:136)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.main(ActivityThread.java:5017)
11-05 13:37:26.498: E/AndroidRuntime(1493): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 13:37:26.498: E/AndroidRuntime(1493): at java.lang.reflect.Method.invoke(Method.java:515)
11-05 13:37:26.498: E/AndroidRuntime(1493): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-05 13:37:26.498: E/AndroidRuntime(1493): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-05 13:37:26.498: E/AndroidRuntime(1493): at dalvik.system.NativeStart.main(Native Method)
11-05 13:37:26.498: E/AndroidRuntime(1493): Caused by: java.lang.NullPointerException
11-05 13:37:26.498: E/AndroidRuntime(1493): at com.reserveme.Restaurants.onCreate(Restaurants.java:69)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.Activity.performCreate(Activity.java:5231)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
11-05 13:37:26.498: E/AndroidRuntime(1493): ... 11 more
I am using a ListView in one of my projects too. To get the touched/clicked position in my listview I have registered a ClickHandler to the ListView (not to the items of the list).
In your example the ID is equal to the position, so I think you could do the same.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
Intent intent = new Intent(Restaurants.this, RestaurantInformation.class);
intent.putExtra("myID", position);
startActivity(intent);
}
});
In the new Activity you can call the following to get the id:
Intent intent = getIntent();
if (intent.getExtras() != null) {
myID = (Integer) intent.getExtras().get("myID");
}

Parsing from JSON.txt file to a ListFragment

I am having some difficulties to extract info from JSON .txt file, and displaying that info into a ListFragment.
I am saving .txt file in assets folder and has the type:
{
"cities":
[
{
"name":"NAME",
"state":"STATE",
"latitude":45.000000,
"longitude":-102.089016,
},
{
"name":"NAME",
"state":"STATE",
"latitude":35.000000,
"longitude":-102.089016,
},
...
{
"name":"NAME",
"state":"STATE",
"latitude":15.000000,
"longitude":-102.089016,
}
]
}
I am using a public class for cities like: public class City implements Serializable {...}
which contains getters and setters for each field.
I am trying to load the data with a class LoadDataAsyncTask which extends AsyncTask<>:
I think that in order to load this data to the ListFragment I need to code it in doInBackground() method:
#Override
protected Void doInBackground(String... arg0) {
AssetManager manager = contexto.getAssets();
JSONArray jarray = null;
StringBuilder builder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader( new InputStreamReader( manager.open("jsonfile.txt") ) );
String line;
JSONObject jobject = new JSONObject();
// Read data
while((line = reader.readLine()) != null) {
builder.append(line);
String city = jobject.getString("name");
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Log.e("", e.toString());
}
return null;
}
Then having a class CitiesListFragment containing code like this:
public class CitiesListFragment extends ListFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<City> adapt = new ArrayAdapter<City>(getActivity(),
android.R.layout.simple_list_item_1, new ArrayList<City>());
LoadDataAsyncTask task = new LoadDataAsyncTask(getActivity(), adapt);
tarea.execute("jsonfile.txt");
setListAdapter(adaptador);
}
}
I think i am missing some coding, but i am not pretty sure on where to write it.
You should check your json reponse at jsonlint.com. Paste the json there and see if the json is in valid format.
If its valid then use this method and get a full jsonString response.
private String readJson() {
String jsonResponse = null;
try {
InputStream inputStream = context.getResources().openRawResource(R.raw.json);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder strBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
strBuilder.append(receiveString);
}
inputStream.close();
jsonResponse = strBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
}
catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return jsonResponse;
}
once you have the jsonReponse, simple use gson or any other mean to parse it.
First: Here's what I did with your json :
{
"cities":[
{
"name":"NAME",
"state":"STATE",
"latitude":"45.000000",
"longitude":"-102.089016"
},
{
"name":"NAME",
"state":"STATE",
"latitude":"35.000000",
"longitude":"-102.089016"
},
{
"name":"NAME",
"state":"STATE",
"latitude":"15.000000",
"longitude":"-102.089016"
},
]
}
I saved it as a JSON (yourjson.json) in the assets folder and here's how I am accessing it:
First: Just used activity instead of ListActivity.. You can use ListActivity in your case.
public class CitiesListFragment extends Activity {
ArrayList<String> QuestionForSliderMenu = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> STATE = new ArrayList<String>();
ArrayList<String> LATITUDE = new ArrayList<String>();
ArrayList<String> LONGITUDE = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.citieslayout);
ListView listView = (ListView) findViewById(R.id.listview1);
MyAdapter adapter = new MyAdapter(this, QuestionForSliderMenu);
listView.setAdapter(adapter);
try {
ParsedData();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ParsedData() {
NAME = new ArrayList<String>();
STATE = new ArrayList<String>();
LATITUDE = new ArrayList<String>();
LONGITUDE = new ArrayList<String>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray array = json.getJSONArray("cities");
QuestionForSliderMenu = new ArrayList<String>();
Log.d("Cities: ", array.toString());
for (int my = 0; my <= array.length(); my++) {
JSONObject c = array.getJSONObject(my);
String name = c.getString("name");
String state = c.getString("state");
String latitude = c.getString("latitude");
String longitude = c.getString("longitude");
NAME.add(name);
STATE.add(state);
LATITUDE.add(latitude);
LONGITUDE.add(longitude);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private class MyAdapter extends BaseAdapter {
private int lastPosition = -1;
private Context context;
private ArrayList<ModelClass> name;
private ArrayList<ModelClass> state;
private ArrayList<ModelClass> latitude;
private ArrayList<ModelClass> longitude;
private ArrayList<ModelClass> MainItems;
private ArrayList<String> mainList;
public MyAdapter(Context context, ArrayList<ModelClass> name,
ArrayList<ModelClass> state, ArrayList<ModelClass> latitude,
ArrayList<ModelClass> longitude) {
super();
this.context = context;
this.name = name;
this.state = state;
this.latitude = latitude;
this.longitude = longitude;
}
public MyAdapter(Context applicationContext,
ArrayList<String> questionForSliderMenu1) {
super();
this.mainList = questionForSliderMenu1;
}
#Override
public int getCount() {
return STATE.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cities_row, null);
}
TextView name = (TextView) convertView.findViewById(R.id.Name);
TextView state = (TextView) convertView.findViewById(R.id.State);
TextView latitude = (TextView) convertView
.findViewById(R.id.Latitude);
TextView longitude = (TextView) convertView
.findViewById(R.id.Longitude);
try {
name.setText(NAME.get(position));
state.setText(STATE.get(position));
latitude.setText(LATITUDE.get(position));
longitude.setText(LONGITUDE.get(position));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
}
//This is where I am getting the json from the assets and in the above method just using this method to get the json object.
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getApplicationContext().getAssets().open(
"yourjson.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
That's all. And in the last, the layouts:
cities_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cities"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/State"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="States"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
And, citieslayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listview1"
android:layout_width="match_parent"
android:layout_height="338dp"
android:layout_weight="0.36"
android:background="#333333">
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Hope this helps..:)

Parsing JSON Data to a list View

I am trying to parse the data into the list View in android
JSON:: http://54.218.73.244:7000/
It has a JSON output :: [{"restaurantID":1,"restaurantNAME":"CopperChimney"},{"restaurantID":2,"restaurantNAME":"Aroy"},{"restaurantID":3,"restaurantNAME":"MarkBoulevard"}]
I am trying to display the CopperChimney, Aroy, MarkBoulevard in a
list view
I figured some small parts but can someone help me fill
AndroidJSONParsingActivity.java part of the code which invoolves putting data in a collection and displaying it
Any ideas ?
JSONParser
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Item.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tt = null;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
}
return v;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
itemlistrow.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow android:layout_width="fill_parent"
android:id="#+id/TableRow01"
android:layout_height="wrap_content">
<TextView
android:id="#+id/RestaurantNameID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="name" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:height="40sp"/>
</TableRow>
</TableLayout>
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
private static String url = "http://54.218.73.244:7000/";
//
//
//
//
/------ CODE -Trying to ADD ------ /
//
//
}
CODE I TRIED FOR AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7000/";
List<Item> yourData = new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee1.class);
startActivity(myIntent);
}else if(position == 1)
{
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee2.class);
startActivity(myIntent);
}
}
});
}
}
public class AndroidJSONParsingActivity extends ListActivity {
ArrayList <Item> list = new ArraList <Item>();
#Override
public void onStart() {
super.onStart();
new GetHttpData().execute();
}
private class GetHttpData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
private static String url = "http://54.218.73.244:7000/";
JSONArray jArray = getJSONFromUrl(url);
int len = jArray.length();
for(int i = 0; i < len; i++) {
JSONObject restaurant = jArray.getJSONObject(i);
list.add(new Item(restaurant.getString("restaurantNAME"));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(new ListAdapter(AndroidJSONParsingActivity.this, android.R.layout.simple_list_item_1, list));
}
}
}
This is just one way to parse it, you should also do all HttpRequests and JSON parsing in a separate thread, see http://developer.android.com/reference/android/os/AsyncTask.html
Edited:
You can also check this Example

Categories

Resources