Refreshing screen which uses json in android - android

I have a module in my application which uses json.
The json gets updated always.
Here i want to refresh the screen as new data arrives.
Is there any method for this ?
I want to refresh the screen as new data arrives or once in every 5 seconds or something(a fixed amount of time).How to do this ?
I simply used a local json file to test this.
I just need the code for refreshing.
This is my code for json parsing :
public class MainActivity extends Activity
{
String myjsonstring;
ArrayList<Data> web = new ArrayList<Data>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JsonParser();
// Try to parse JSON
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
}
final customtest1 adapter = new customtest1(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "Test.........", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void JsonParser()
{
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"main.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjsonstring = sb.toString();
}
}

Do this.
create a class
public class Data
{
String name ="";
String viewers ="";
public Data(String n,String v)
{
name = n;
viewers=v;
}
}
then in MainActivity create only single arraylist with type Data
ArrayList<Data> web = new ArrayList<Data>();
and then parse your json like
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
now instead of passing two array list to your custom adapter , pass only single arraylist i.e web
customtest adapter = new customtest(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
in your customtest class , inside getview when you will bind data, you will do
Data dt = web.get(position);
String name = dt.name;
String viewers = dt.viewers;
and then do what you were doing before.
and after all this, now ehnever you want to update your list simply call
adapter.notifyDataSetChanged();
your customtest class now will be like
public class customtest extends ArrayAdapter<Data>{
Context context;
int layoutResourceId;
ArrayList<Data> data = null;
public customList(Context context, int layoutResourceId, ArrayList<Data> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CustomHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CustomHolder();
holder.txtName = (TextView)row.findViewById(R.id.txtName); //this is id of textview where you want to set name
holder.txtViewers = (TextView)row.findViewById(R.id.txtViewers); //this is id of textview where you want to set viewers
row.setTag(holder);
}
else
{
holder = (CustomHolder)row.getTag();
}
Data dt = data.get(postition);
holder.txtName.setText(dt.name);
holder.txtViewers.setText(dt.viewers);
return row;
}
static class CustomHolder
{
TextView txtName;
TextView txtViewers;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
new Thread(){
public void run()
{
While(true)
{
Thread.sleep(3000);
jsonParse(); //this is your method for parsing json
}
}
}.start();

Related

Android - Display data from Adapter in Listview

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

Reading JSON array to listview

I'm pretty new to android dev and I need some help.
I'm building an agenda that loads the information from a JSON then a ListView is inflated with a custom adapter. I've done this and works just fine.
My problem is the following when I click a contact another Activity is loaded with more information about the user, using the same JSON. I debug it and it recieves the information like this:
Example Item: [{"id":1,"name":"Leanne Graham","hobby":"Play soccer","address":"Kulas Light, Gwenborough","phone":"1-770-736-8031 x56442"}]
Because I sent the information as a JSONObject I cast it to be a JSONArray, but when I pass that array to my requestComplete my app breaks.
The error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
/**Main activity onclick listener*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("POSITION: " + position);
JSONObject jsonObject = (JSONObject)JSONadapter.getItem(position);
Intent intent = new Intent(this, InfoActivity.class);
String pos_json = jsonObject.toString();
intent.putExtra("pos_json",pos_json);
startActivity(intent);
}
/**Info activity*/
public class InfoActivity extends AppCompatActivity implements JSONRequest.JSONCallback {
AdapterInfo JSONAdapter;
private ListView listInfo;
private JSONObject json_object;
private JSONArray arrayMain;
private ArrayList<String> jsonarray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
JSONArray array = new JSONArray();
try {
json_object = new JSONObject(getIntent().getStringExtra("pos_json"));
arrayMain = array.put(json_object);
System.out.println("Example Item: "+ arrayMain.toString());
System.out.println(arrayMain.getClass().getName());
} catch (JSONException e) {
e.printStackTrace();
}
requestComplete(arrayMain);
this.listInfo = (ListView) findViewById(R.id.listView2);
}
#Override
public void requestComplete(JSONArray array) {
JSONAdapter = new AdapterInfo(InfoActivity.this,array);
this.listInfo.setAdapter(JSONAdapter);
}
/**Adapter*/
public class AdapterInfo extends BaseAdapter{
private JSONArray array;
private Activity infoAct;
public AdapterInfo(Activity infoAct, JSONArray array){
this.array = array;
this.infoAct = infoAct;
}
#Override
public int getCount() {
if(array == null){
return 0;
}else{
return array.length();
}
}
#Override
public JSONObject getItem(int position) {
if(array == null){
return null;
}else{
return array.optJSONObject(position);
}
}
#Override
public long getItemId(int position) {
JSONObject object = getItem(position);
return object.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = infoAct.getLayoutInflater().inflate(R.layout.row,null);
}
TextView name = (TextView)convertView.findViewById(R.id.infoName);
TextView hobby = (TextView)convertView.findViewById(R.id.infoHobby);
TextView address = (TextView)convertView.findViewById(R.id.infoAddress);
TextView phone = (TextView)convertView.findViewById(R.id.infoPhone);
JSONObject json_data = getItem(position);
if(json_data != null){
try {
String nombre = json_data.getString("name");
String pasatiempo = json_data.getString("hobby");
String direccion = json_data.getString("address");
String telefono = json_data.getString("phone");
name.setText(nombre);
hobby.setText(pasatiempo);
address.setText(direccion);
phone.setText(telefono);
} catch (JSONException e) {
e.printStackTrace();
}
}
return convertView;
}}
/**JSONRequest*/
public class JSONRequest extends AsyncTask<String, Void, JSONArray> {
private JSONCallback callback;
public JSONRequest(JSONCallback callback){
this.callback = callback;
}
#Override
protected JSONArray doInBackground(String... params) {
URLConnection connection = null;
BufferedReader br = null;
JSONArray result = null;
try{
URL url = new URL(params[0]);
connection = (URLConnection) url.openConnection();
InputStream is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = "";
while((line = br.readLine()) != null){
builder.append(line);
}
result = new JSONArray(builder.toString());
}catch (Exception e) {
e.printStackTrace();
} finally {
try{
if(br != null) br.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
callback.requestComplete(jsonArray);
}
public interface JSONCallback{
void requestComplete(JSONArray array);
}}
Your code:
requestComplete(arrayMain);
this.listInfo = (ListView) findViewById(R.id.listView2);
requestComplete() uses this.listInfo instance but this.listInfo is null because it is set after requestComplete(). So you need to switch their order.
this.listInfo = (ListView) findViewById(R.id.listView2);
requestComplete(arrayMain);
It is better if you just put it right after call to setContentView() just to make sure this.listInfo holds valid ListView instance.

How to add some parsed JSON objects into a custom listview?

Well, I don't know if the title is clear, so now I'll explain everything better.
I have parsed some JSON objects. After parsing, I need to show them into a custom listview.
The JSON objects are correctly parsed into string, because I have first show them into common textviews (just for a test).
Also the custom listview is working, because I have first added some values "manually" (again, just for testing it).
Here my problem:
Now I want to add the JSON objects (parsed into string) into my custom listview. I've tried every "tip and trick" I know, unsuccessfully. After two days of working, I've decided to ask you.
Before posting the code: the http request for parsing JSON objects is made with this library.
Here the code
Getprofiledata.java
public class Getprofiledata extends ActionBarActivity {
String num;
Boolean ok=true;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
String url = "URL FOR JSON OBJECTS";
ListView listadata = (ListView) findViewById(R.id.listadata);
final List<Data> datalist = new LinkedList <Data>();
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
/*********
* HERE WE CAN ADD VALUES TO MY CUSTOM LISTVIEW
* HOW CAN I PASS THE PREVIOUS STRING IN THIS STATEMENT?
*
* THIS IS THE METHOD:
* datalist.add(new Data(record1,record2,record3,record4,record5));
*********/
//HERE THE ADAPTER FOR MY CUSTOM LISTVIEW
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this, R.layout.data_riga, datalist);
listadata.setAdapter(adapter);
}
}
I hope I've been clear. Can you help me? I'm desperate! :(
Thanks in advance
Edit: here my Getprofiledata_customadapter.java
public class Getprofiledata_customadapter extends ArrayAdapter<Data>{
public Getprofiledata_customadapter(Context context, int textViewResourceId,
List <Data> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.data_riga, null);
TextView firstrecord = (TextView)convertView.findViewById(R.id.tv1);
TextView secondrecord = (TextView)convertView.findViewById(R.id.tv2);
TextView thirdrecord = (TextView)convertView.findViewById(R.id.tv3);
TextView forthrecord = (TextView)convertView.findViewById(R.id.tv4);
TextView fivethrecord = (TextView)convertView.findViewById(R.id.tv5);
Data c = getItem(position);
firstrecord.setText(c.getRecord1());
secondrecord.setText(c.getRecord2());
thirdrecord.setText(c.getRecord3());
forthrecord.setText(c.getRecord4());
fivethrecord.setText(c.getRecord5());
return convertView;
}
}
Basically you just pre-create the List first. Then with that data create an adapter and set it to your ListView.
At the moment you just loop through the data without saving it at all.
It would look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
mListView = (ListView) findViewById(R.id.listadata);
String url = "URL FOR JSON OBJECTS";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
// Save strings to your list
mData.add(new Data(record1,record2,record3,record4,record5));
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
// When the data loop is over create the adapter and set it to your ListView
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this,
R.layout.data_riga, mData);
mListView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
}

How to parse json from a local json file into a ListView in android?

I am creating an application which uses a local json file for displaying some information.So i parsed the data and a text view which displays the data.But what i actually want is that the parsed data has to be displayed in a Listview. How to do this ?
This is my code.
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsonshoutdata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjsonstring = sb.toString();
// Try to parse JSON
try {
urlist = new ArrayList<HashMap<String, String>>();
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("message");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
String message = jsonObj.getString("msg");
HashMap<String, String> map = new HashMap<String, String>();
map.put("msg", msg );
urlist.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my customList adapter
CustomList adapter = new CustomList(MainActivity.this,urlist);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();
}
});
This is my adapter class
public class CustomList extends ArrayAdapter<String>
{
public final ArrayList<HashMap<String, String>> urlist;
private Activity context;
public CustomList(Activity context,ArrayList<HashMap<String, String>> urlist)
{
super(context, R.layout.list_single);
this.context = context;
this.urlist=urlist;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText((CharSequence) urlist);
return rowView;
}
}
create a customList class(dont use hashmap)
change your custom list code (this is your code)
public class CustomList extends ArrayAdapter<String>
{
public final ArrayList<HashMap<String, String>> urlist;
private Activity context;
public CustomList(Activity context,ArrayList<HashMap<String, String>> urlist)
{
super(context, R.layout.list_single);
this.context = context;
this.urlist=urlist;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText((CharSequence) urlist);
return rowView;
}
}
to
public class customList extends ArrayAdapter<String>{
Context context;
int layoutResourceId;
ArrayList<String> data = null;
public customList(Context context, int layoutResourceId, ArrayList<String> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CustomHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CustomHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (CustomHolder)row.getTag();
}
String s = data.get(postition);
holder.txtTitle.setText(s);
return row;
}
static class CustomHolder
{
TextView txtTitle;
}
}
and change your json parsing code and parse your json like
// JSONArray has four JSONObject
ArrayList<String> messages = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
String message = jsonObj.getString("msg");
messages.add(message);
}
and finally replace your this code
CustomList adapter = new CustomList(MainActivity.this,urlist);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();
}
});
with this one
customList adapter = new customList(MainActivity.this,R.layout.list_single,messages); //messagses is your arraylist in which you added string by parsing your json (see before this code mean upward)
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();
}
});
Solution 2
since you are showing only single text , you dont need to create your own custom adapter instead you can simply do.
ArrayList<String> messages = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
String message = jsonObj.getString("msg");
messages.add(message);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, messages);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();
}
});
Use this .
try {
urlist = new ArrayList<HashMap<String, String>>();
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("message");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
String message = jsonObj.getString("msg");
HashMap<String, String> map = new HashMap<String, String>();
map.put("msg", message );
urlist.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here globally declare before onCreate()
ArrayList<HashMap<String, String>> urlist;
Now you have to pass urList arraylist to your CustomAdapter of your ListView as a parameter and after that set that adapter to your ListView.

Not able to display some JSON data for views in the list view

I am trying to Parse the JSON to list view
There is no error in log cat
The image is getting parsed but the data which should be displayed in
front of rank and country is not getting displayed
Why is the error occuring
How to resolve this
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("name", resultp.get(MainActivity.NAME));
// Pass all data country
intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://54.218.73.244:7002/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("name", jsonobject.getString("restaurantNAME"));
map.put("type", jsonobject.getString("restaurantTYPE"));
map.put("flag", jsonobject.getString("restaurantIMAGE"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
output
The image is getting parsed but the data which should be displayed in front of rank and country is not getting displayed
Any Ideas
hope i am clear
The image is getting parsed but the data which should be displayed in
front of rank and country is not getting displayed
because you are storing values in HashMap with different keys and trying to get values with different keys in Adapter so change it as inside doInBackground method for storing values with keys :
map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("restaurantIMAGE"));
try below code:
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
and your map key also different: see restaurantNAME...

Categories

Resources