listview doesn't appear, no errors - android

I am making a listview, which shows data from a server. I get no errors in LogCat, but my ListView doesn't appear. This is my code:
package com.imptmd.charliemacdonald.desleutelaar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SlotenFragment extends ListFragment {
private ProgressDialog nDialog;
// URL to get contacts JSON
private static String url = "http://charlenemacdonald.com/sloten.json";
// JSON Node names
private static final String TAG_SLOTEN = "slotenlijst";
private static final String TAG_SLOT = "Slot";
// contacts JSONArray
JSONArray sloten= null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> slotenLijst;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);
slotenLijst = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Slot = ((TextView) rootView.findViewById(R.id.textviewslotnaam))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
SlotInfoScherm1.class);
in.putExtra(TAG_SLOT, Slot);
startActivity(in);
}
});
new GetSloten().execute();
// Calling async task to get json
return rootView;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetSloten extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
nDialog = new ProgressDialog(getActivity());
nDialog.setMessage("Even geduld a.u.b., studenten worden geladen...");
nDialog.setCancelable(false);
nDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
sloten = jsonObj.getJSONArray(TAG_SLOTEN);
// looping through All Contacts
for (int i = 0; i < sloten.length(); i++) {
JSONObject c = sloten.getJSONObject(i);
String Slot = c.getString(TAG_SLOT);
// tmp hashmap for single contact
HashMap<String, String> sloten = new HashMap<String, String>();
// adding each child node to HashMap key => value
sloten.put(TAG_SLOT, Slot);
// adding contact to contact list
slotenLijst.add(sloten);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (nDialog.isShowing())
nDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});
setListAdapter(adapter);
}
}
}
The INTERNET permission is already added in the Manifest, just as WRITE EXTERNAL STORAGE and INTERNAL STORAGE. I get no errors in LogCat. The only error I get is in the ADB 'ADB rejected connection to client'. Is that why my ListView doesn't appear? Thanks in advance.

Hi can you update you code and test the below logic what you received.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (nDialog.isShowing())
nDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
Log.d("DataSize: ",""+slotenLijst.size());
ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});
setListAdapter(adapter);
}
Let us know what you get in log cat "DataSize".

Change your onCreateView(...) to be:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);
slotenLijst = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
new GetSloten().execute();
// Calling async task to get json
return rootView;
}
// ListFragment implement this in default
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
//getting values from selected ListItem
String Slot = ((TextView) rootView.findViewById(R.id.textviewslotnaam))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
SlotInfoScherm1.class);
in.putExtra(TAG_SLOT, Slot);
startActivity(in);
}
});
and your fragment layout fragment_sloten could be like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
... ...
</LinearLayout>
Hope this help!

Related

Issues with Listview in a Fragment in Android

I have a ListView in a ListFragment and in the code I wrote a code that says when an item of listview is clicked, open another activity.
The problem is when I click on an item, nothing happens!
This code works fine in an Activity, but not in a Fragment.
Code:
ListView lv = (ListView) v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity().getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
});
I replaced this code :
ListView lv = (ListView) v.findViewById(android.R.id.list);
with :
ListView lv = getListView();
Because it was giving me
content view not yet created
in logcat.
All the code:
package rappage.rapfarsi.media.appteam;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class tab1 extends ListFragment {
static final String url_all_products = "http://aliak.xzn.ir/rap/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_PRODUCTS = "products";
final String TAG_PID = "pid";
final String TAG_NAME = "name";
// JSON Node names
// products JSONArray
JSONArray products = null;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1, container, false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = (ListView) v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity().getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
});
return v;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I hope you can help me....thanks
Extending from ListFragment you only have to redefine this method:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//Handle click event
}
Instead of getting the list and setting its onItemClickListener

Change text colour in individual list view based on variable

I followed this tutorial about parsing JSON. All is working as it should have have edited it to more my needs. I am getting information about 'servers' and one of the fields is 'status' (either UP or DOWN).
EDIT: forgot to post tutorial link http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
It currently looks like this: http://puu.sh/8Ky0B.jpg
The above is what happens then the app is loaded. the on click is when a single item is clicked it starts a new activity and shows that information individually.
You can see the second server status is 'DOWN'. Based on this I want to change the text colour to RED for down and keep it green for up.
How can I do this when it goes through and adds each listview?
Here is the code which (currently) is basically the same as the tutorial:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String ip = ((TextView) view.findViewById(R.id.ipAddress))
.getText().toString();
String status = ((TextView) view.findViewById(R.id.serverStatus))
.getText().toString();
// Starting single server activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_IP, ip);
in.putExtra(TAG_STATUS, status);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jArray = new JSONArray(jsonStr);
// looping through All Servers
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String ip = c.getString(TAG_IP);
String status = c.getString(TAG_STATUS);
// tmp hashmap for single server
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_IP, ip);
contact.put(TAG_STATUS, status);
// adding server to server list
serverList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, serverList,
R.layout.list_item, new String[] { TAG_NAME, TAG_IP,
TAG_STATUS }, new int[] { R.id.name,
R.id.ipAddress, R.id.serverStatus });
setListAdapter(adapter);
}
}
You need to make a custom adapter and in the getView() you should check if the status of the server is down then set the color of corresponding textview to red else set it to green.
your getView() should like as following: (This is just a blueprint for your code)
getView(){
String serverstatus = server.getStatus();
// get status should be method in method in model class for server.
if(serverstatus.equals("DOWN")){
tv.setTextColor(Color.RED);
}else{
tv.setTextColor(Color.GREEN);
}
}
EDIT
Make a model class.
class Server{
String serverName, serverIp, serverStatus;
// getter and setter.
}
Make array adapter of Server type.
In Adapter's getView() inflate the row item, and set the details. For, red color font blueprint is already added.
In the definition of list Adapter, in the getView() method, find the textview and change the text color.
TextView tv = (TextView) listItem.findViewById(R.id.server_status);
tv.setTextColor(android.R.color.primary_text_dark);
Take the custom Adapter (a BaseAdapter) instead of simple adapter,
and there you perform your operation in getView() method.
You've done most of the hard work already :)
First create an object to store server details rather than a HashMap (which are slow and heavy) plus an object is more adaptable and fits your purpose better.
I've created a super fast example (not complete as to your details, but should be easy to expand).
package com.example.adaptertest;
public class HolderServer {
String serverName;
boolean isServerUp;
public HolderServer(String serverName, boolean isServerUp) {
this.serverName = serverName;
this.isServerUp = isServerUp;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public boolean isServerUp() {
return isServerUp;
}
public void setServerUp(boolean isServerUp) {
this.isServerUp = isServerUp;
}
}
Next you'll need to create a custom adapter. In your example you're actually using a simple adapter (ListAdapter adapter = new SimpleAdapter() which is a great first step, but we can improve on that a little by extending it. This will allow us to change what happens to each individual element in the listview. i.e. change the color etc.
Here's a quick example:
package com.example.adaptertest;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class AdapterServers extends ArrayAdapter<HolderServer>{
ArrayList<HolderServer> mServers = new ArrayList<HolderServer>();
private LayoutInflater mInflater;
Context mContext;
public AdapterServers(Context context, int resource, ArrayList<HolderServer> servers) {
super(context, resource, servers);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
mServers = servers;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Inflate view for each element in list.
convertView = mInflater.inflate(R.layout.server_list_item, null);
//Get details for current server
HolderServer server = mServers.get(position);
//Set server name
((TextView) convertView.findViewById(R.id.server_list_item_txt_servername)).setText(server.getServerName());
//Now we set the status text and color
TextView status = (TextView) convertView.findViewById(R.id.server_list_item_txt_serverstatus);
if(server.isServerUp){
status.setText(mContext.getResources().getString(R.string.up));
status.setTextColor(mContext.getResources().getColor(R.color.green));
}else{
status.setText(mContext.getResources().getString(R.string.down));
status.setTextColor(mContext.getResources().getColor(R.color.red));
}
return convertView;
}
}
Now back in your code, first in onCreate create a new list of objects:
ArrayList<HolderServer> mServerList = new ArrayList<HolderServer>();
then instead of this:
// tmp hashmap for single server
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_IP, ip);
contact.put(TAG_STATUS, status);
You'll create your new object & add it to the list. Obviously update it with your variables once your HolderServer object is updated:
HolderServer server = new HolderServer("Server1", true);
serverList.add(server);
Then apply that list to the adapter and apply the adapter to the listview:
AdapterServers adapter = new AdapterServers(this, 0, serverList);
((ListView) findViewById(R.id.fragment_main_listview)).setAdapter(adapter);
Good luck!

How to set onCLickListner for dynamic ListView

I am working on an android project. I want to add onClick event to listView so that whenever someone clicks on any item in the ListView new fragment showing further details is displayed.I am using Mysql database.
package com.example.festipedia_logo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.example.festipedia_logo.Searchpage.LoadAllProducts;
//import com.example.connection.disp;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class details1 extends SherlockFragment {
ArrayAdapter<String> adapter;
String[] city;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
EditText b;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.43.185:8080/festipedia/get_all_products.php";
Button a;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "eventname";
// products JSONArray
JSONArray products = null;
ListView l;
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.second);
View rootView = inflater.inflate(R.layout.home2, container, false);
// setContentView(R.layout.all_products);
l = (ListView) rootView.findViewById(R.id.myListView);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
return rootView;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
//l.setFilterText(id);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[] {
TAG_NAME},
new int[] { R.id.name });
// updating listview
l.setAdapter(adapter);
}
});
}
}
}
Try this..
Add below ItemClickListener Codes before return rootView;
l.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do something
}
});
You need to use OnItemClickListener and add/replace existing fragment in the container.
l.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Toast.makeText(getActivity(), "Clicked at" + position, Toast.LENGTH_SHORT).show();
}
});
Also you need not have runOnUiThread in onPostExecute as it is invoked on the ui thread.
You also need to use interface as a call back to the Activity and then add/replace fragment to the container in Activity
Exmple #
How to send data from fragment to fragment within same fragment activity?
Add ItemClickListener below
l = (ListView) rootView.findViewById(R.id.myListView);
in function onCreateView();
l.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do something
}
});

Creating a ListView in Fragment that Retrieves Data from a Server

I've been attempting to create a ListView in a fragment that gets data from a server, but so far have been unsuccessful. I've been using the following site: Vogella for learning on how to implement ListView in a fragment, but I am having difficulties when trying to populate data from a server.
package com.example.ips_alpha;
import java.util.ArrayList;
import java.util.HashMap;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
public class Gold_Visitors2 extends ListFragment{
//JSON Node names (level, sensorID, value)
String SPACES = "spaces"; //String array name of php
String LEVEL = "level";
String SENSORID = "sensorID";
String VALUE = "value";
//pspace JSONArray
JSONArray pspace = null;
String[] levels = new String[]{LEVEL, SENSORID, VALUE};
int [] ids = new int[]{};
private static String url = "http://www.example.com/getUsers12.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_gold_visitors, null);
new MyAsyncTask().execute();
return view;
}
class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {
//Hashmap for ListView
ArrayList<HashMap<String, String>> levelList = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>>doInBackground(String... params) {
//Creating JSON Parser instance
JSONParser jParser = new JSONParser();
//getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
//Getting Array of spaces
pspace = json.getJSONArray(SPACES);
//looping through all spaces
for(int i = 0; i < pspace.length(); i++){
JSONObject p = pspace.getJSONObject(i);
//Storing each json item in variable
String level = p.getString(LEVEL);
String sensorID = p.getString(SENSORID);
String value = p.getString(VALUE);
//creating new HashMap
HashMap<String, String> map = new HashMap <String, String>();
//adding each child node to HashMap Key =>
map.put(LEVEL, level);
map.put(SENSORID, sensorID);
map.put(VALUE, value);
//adding HashList to ArrayList
}
}catch(JSONException e){
e.printStackTrace();
}
return levelList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> levelList) {
ListAdapter adapter = new SimpleAdapter(getActivity(), levelList, R.layout.fragment_gold_visitors, levels, ids);
setListAdapter(adapter);
}
}
}
The following is the layout file:
<?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" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
Currently my app is compiling and does not crash, but when accessing the fragment that is supposed to display the ListView, it's blank. I believe I'm messing up in the ASyncTask and the adapter, any help would greatly be appreciated.
You return levelList in doInBackground, but you never added any items to it from the retrieved JSON. All you have is an empty ArrayList, so the ListView is empty.

Android Activity to Fragments listview

Hello i've build already smartphone apps but now i'm starting working on a project to make my app compatible with tablets. Now i'm using fragments this is my first using fragments so thats why i need your advice, please help or give me examples with my code. Many thanks already
my code my "news" class:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Nieuws extends FragmentActivity{
// Connection detector
//ConnectionDetector cd;
// Alert dialog manager
//AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
//private ProgressDialog pDialog;
private static String URL = "http://localhost/fetch.php?page=2&android";
// JSON Node namen
static final String TAG_DATA = "data";
static final String TAG_ID = "id";
static final String TAG_CATEGORY = "category";
static final String TAG_TITLE = "title";
static final String TAG_AUTHOR = "author";
static final String TAG_DATE = "date";
static final String TAG_INTRODUCTION = "introduction";
static final String TAG_CONTENT = "content";
static final String TAG_THUMBNAIL = "thumbnail";
static final String TAG_MEDIA = "media";
static final String TAG_SOURCE = "source";
static final String TAG_LINKEDMEDIA = "linkedMedia"; //array waarin de plaatjes zitten*/
// Nieuws JSONArray
JSONArray newsArray;
ListView list;
LazyAdapter adapter;
private PullToRefreshListView mPullRefreshListView;
ArrayList<HashMap<String, String>> newsList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nieuws);
//list=(ListView)findViewById(R.id.list);
mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);
/* FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
StartFragment myFragment = new StartFragment();
ft.add(R.id.myFragment, myFragment);
ft.commit();*/
/* cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Nieuws.this, "Internet Connectie Error", "Zorg voor een werkende internet connectie", false);
// stop executing code by return
return;
}*/
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetJSONData().execute();
}
});
//Async
new GetJSONData().execute();
}
class GetJSONData extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>{
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute(){
super.onPreExecute();
//pDialog = new ProgressDialog(Nieuws.this);
//pDialog.setMessage("Nieuws laden ...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
}
/**
* Get de json
*/
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
// Hashmap voor listView
final ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
// Maak een JSON Parser instance
JSONParser jParser = new JSONParser();
// Pakt JSON string uit URL
JSONObject json = jParser.getJSONFromUrl(URL);
try{
// Pakt de Array van Nieuwsartikelen
newsArray = json.getJSONArray(TAG_DATA);
// Loop door alle Nieuwsartikels
for(int i=0; i < newsArray.length(); i++){
JSONObject c = newsArray.getJSONObject(i);
// Het plaatsen van elk json item in variabele
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String date = c.getString(TAG_DATE);
//String introduction = c.getString(TAG_INTRODUCTION);
String thumbnail = c.getString(TAG_THUMBNAIL);
String linkedMedia = c.getString(TAG_LINKEDMEDIA);
//String thumbnailName = c.getString(TAG_THUMBNAIL);
//String thumbnailFormat = "http://iappministrator.com/mooiwark/media/%s";
//String thumbnail = String.format(thumbnailFormat, thumbnailName);
// maak een nieuwe HashMap
HashMap<String, String> map = new HashMap<String, String>();
// voeg elk item child node in de Hashmap -> value
map.put(TAG_TITLE, title);
map.put(TAG_CONTENT, content);
map.put(TAG_DATE, date);
//map.put(TAG_INTRODUCTION, introduction);
map.put(TAG_THUMBNAIL, thumbnail);
map.put(TAG_LINKEDMEDIA, linkedMedia);
// voeg de HashList toe aan ArrayList
newsList.add(map);
// Click event for single list row
mPullRefreshListView.setOnItemClickListener(new OnItemClickListener(){
//list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = newsList.get(position - 1);
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//Intent in = new Intent(SingleMenuItemActivity.this, org.scout.android.library.LibraryDetail.class);
in.putExtra(TAG_TITLE, map.get(TAG_TITLE));
in.putExtra(TAG_CONTENT, map.get(TAG_CONTENT));
in.putExtra(TAG_DATE, map.get(TAG_DATE));
//in.putExtra(TAG_INTRODUCTION, map.get(TAG_INTRODUCTION));
in.putExtra(TAG_THUMBNAIL, map.get(TAG_THUMBNAIL));
in.putExtra(TAG_LINKEDMEDIA, map.get(TAG_LINKEDMEDIA));
startActivity(in);
}
});
}
} catch(JSONException e){
e.printStackTrace();
}
return newsList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
//De items worden ingeladen
adapter=new LazyAdapter(Nieuws.this, result, R.layout.list_row,
new String[]{TAG_TITLE, TAG_CONTENT, TAG_DATE, TAG_THUMBNAIL}, new int[] {
R.id.title, R.id.subtitle, R.id.date, R.id.list_image}); //TAG_INTRODUCTION mist nog
//list.setAdapter(adapter);
mPullRefreshListView.setAdapter(adapter);
// dismiss the dialog after getting all deelnemers
//pDialog.dismiss();
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
}
in this activity it would normally load the content when on click. this class is the one which i've tried to turn into a fragments class
"SingleMenuItemActivity" class :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class SingleMenuItemActivity extends Fragment {
// JSON node keys
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
private static final String TAG_DATE = "date";
private static final String TAG_LINKEDMEDIA = "linkedMedia";
//private static final String TAG_THUMBNAIL = "thumbnail";
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
/*#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);*/
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.single_list_item, container, false);
return view;
cd = new ConnectionDetector(getActivity().getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(), "Internet Connectie Error", "Zorg voor een werkende internet connectie", false);
// stop executing code by return
return;
}
// getting intent data
Intent in = getIntent().getExtras();
//final String image_url = in.getStringExtra(TAG_THUMBNAIL);
final String image_url = in.getStringExtra(TAG_LINKEDMEDIA);
ImageView imgv = (ImageView) getView().findViewById(R.id.images_label);
ImageLoader imageLoader = new ImageLoader(getActivity().getApplicationContext());
imageLoader.DisplayImage(image_url, imgv);
// Get JSON values from previous intent
String title = in.getStringExtra(TAG_TITLE);
String date = in.getStringExtra(TAG_DATE);
String message = in.getStringExtra(TAG_CONTENT);
//String images = in.getStringExtra(TAG_IMAGES);
//Bitmap bitmap = in.getParcelableExtra(TAG_IMAGES);
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image);
// Displaying all values on the screen
TextView lblTitle = (TextView)getView().findViewById(R.id.title_label);
TextView lblDate = (TextView) getView().findViewById(R.id.date_label);
TextView lblMessage = (TextView) getView().findViewById(R.id.message_label);
//ImageView lblImages = (ImageView) findViewById(R.id.images_label);
//TextView lblImages = (TextView) findViewbyId(R.id.images_label);
// loader image
//int loader = R.drawable.loader;
System.out.println("Ja en nu werkt het niet meer");
// image url
//String image_url = "http://d24w6bsrhbeh9d.cloudfront.net/photo/5614379_460s.jpg";
//ImageLoader imgLoader = new ImageLoader(getApplicationContext());
//-imgLoader.DisplayImage(song.get(CustomizedListView.TAG_IMAGES), lblImages);
System.out.println("Error? haha bam jammer dan:");
//imgLoader.DisplayImage(images, lblImages);
//System.out.println("Plaatjes?:"+ images);
lblTitle.setText(title);
lblDate.setText(date);
lblMessage.setText(message);
//lblImages.setImageURI(Uri.parse(images));
//ImageLoader imageLoader = new ImageLoader(getApplicationContext());
//imageLoader.DisplayImage(images,lblImages);
//lblImages.setImageResource(images);
//imageLoader.displayImage(images);
//lblImages.setImageBitmap(bitmap);
//lblImages.setImageResource(R.drawable.bitmap);
//lblImages.setImageResource(images);
/*if (d instanceof BitmapDrawable) {
Bitmap bm = ((BitmapDrawable)d).getBitmap();
//Maybe more code here?
lblImages.setImageBitmap(bm);
}*/
//lblImages.setImageResource(images);
//lblImages.DisplayImage(images);
//lblImages.DisplayImage(images);
}
}
Now i'm getting to the part which i don't understand my Intent in = getIntent() doesn't work i get errors. Can someone guide me on turning from code form a activity to a fragment many thanks already
Screenshot:
Left the "news class" right "SingleMenuItemActivity"
It's going wrong when i click the onclick in the class on the left.
First of all i advise you to use a ListFragment for your list and define a listerner for onclick event (this listener could be your Nieuws activity).
Then you will need to have 2 layouts. The classic one with one fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/onepane_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
</LinearLayout>
and the other one with two fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/towpane_layout">
<fragment android:id="#+id/listFragment"
android:layout_height="fill_parent"
android:name="com.example.MyListFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="#+id/displayFragment"
android:layout_height="fill_parent"
android:name="com.example.MyDisplayFragment"
android:layout_width="fill_parent" />
</LinearLayout>
in your Nieuws Activity you will check if the layout loaded has two fragments if not you will load the ListFragment using the fragment manager
//Check that the activity is not using the layout with fragment;
if(findViewById(R.id.onepane_layout) != null) {
if (savedInstanceState != null) {
return;
}
MyListFragment lFragment = new MyListFragment ();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
lFragment .setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction()
.add(R.id.onepane_layout, lFragment ).commit();
}
Then in your on item selection method you need again to load the display fragment if you are in one pane mode:
MyDisplayFragment dispFrag = (MyDisplayFragment)
getSupportFragmentManager().findFragmentById(R.id.displayFragment);
if (dispFrag != null) {
// If display frag is available, we're in two-pane layout...
// Call a method in the DisplayFragment to update its content
dispFrag.updateView(position);
} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
MyDisplayFragment newFragment = new MyDisplayFragment ();
Bundle args = new Bundle();
args.putInt(MyDisplayFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
There is more to explain but this is the basics. You may need to check these two usefull links:
http://developer.android.com/training/multiscreen/adaptui.html
http://developer.android.com/training/basics/fragments/fragment-ui.html
You will need also to handle screen rotation.
In your FragmentActvity, instead of creating Intent, you need to create object of Bundle
mPullRefreshListView.setOnItemClickListener(new OnItemClickListener(){
//list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = newsList.get(position - 1);
Bundle in = new Bundle();
in.putString("TAG_TITLE",map.get(TAG_TITLE));
in.putString(TAG_TITLE, map.get(TAG_TITLE));
in.putString(TAG_CONTENT, map.get(TAG_CONTENT));
in.putString(TAG_DATE, map.get(TAG_DATE));
//in.putExtra(TAG_INTRODUCTION, map.get(TAG_INTRODUCTION));
in.putString(TAG_THUMBNAIL, map.get(TAG_THUMBNAIL));
in.putString(TAG_LINKEDMEDIA, map.get(TAG_LINKEDMEDIA));
SingleMenuItemActivity singleMenu = new SingleMenuItemActivity(in);
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(android.R.id.content, SingleMenuItemActivity);
fragmentTransaction.addToBackStack("");//if needed
fragmentTransaction.commit();
}
});
}
In your SingleMenuItemActivity class create constructor, which accept the parameter a Bundle object
public DetailActvity(Bundle bundle)
{
this.bundle=bundle;//update global Bundle object
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mView= inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container,false);
imgView = (ImageView)mView.findViewById(R.id.imageView1);
tvDetail = (TextView)mView.findViewById(R.id.tvDetail);
String detail=bundle.getString("KEY");
tvDetail.setText(detail);
String image=bundle.getString("KEY");
return mView;
}

Categories

Resources