I am working on JSON data fetching and displaying but before that I store it in Sqlite.
After fetching from that Sqlite table, it works fine when internet is available but app automatically closed when internet connection is not available. I am using hash-map custom adapter to showing data in listview. I have created a fetchdata method from SqlHelper class
protected Void doInBackground(Void... params)
{
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
int state = NetworkUtilClass.checkInternetConenction(getActivity());
if (state == 1) {
// jsonobject = new JSONObject(str1);
jsonobject = JSONFunction.getJSONfromURL("url");
JSONObject collection = null;
try {
collection = jsonobject.getJSONObject("collection");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray response = null;
try {
response = collection.getJSONArray("response");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobject1 = null;
try {
jsonobject1 = (JSONObject) response.get(i);
noticeId = jsonobject1.getString("id").toString();
noticeTitle = jsonobject1.getString("title").toString();
noticeDescription = jsonobject1.getString("description").toString();
noticePublishedBy = jsonobject1.getString("publishedBy").toString();
noticeValidFrom = jsonobject1.getString("validFrom").toString();
noticeValidTo = jsonobject1.getString("validTo").toString();
Log.e(noticeId, "show");
Log.e(noticeTitle, "show");
Log.e(noticeDescription, "show");
//demo_database.insertData(noticeTitle,noticeDescription,noticePublishedBy,noticeValidFrom,noticeValidTo);
demo_database.insertNoticeData(noticeId,noticeTitle,noticeDescription, noticePublishedBy,
noticeValidFrom, noticeValidTo);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else{
onPostExecute(null);
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
// Locate the listview in listview_main.xml
getData();
demo_database.close();
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void getData() {
// TODO Auto-generated method stub
try {
arraylist = demo_database.fetchNoticeData();
} catch (Exception e) {
e.printStackTrace();
}
listview = (ListView) getActivity().findViewById(R.id.listview);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Toast.makeText(getActivity(), "ListView clicked", Toast.LENGTH_SHORT).show();
}
});
// Pass the results into ListViewAdapter.java
adapter = new NoticeListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
Actually the thing is that when you are trying to access the json through url when internet is not available so the json Array with name response get no items in that so it got Null and when you try to execute For loop in which you give the length of json array it would be crash because of null pointer exception..
Your App is Crashing on the for Loop Right?
Related
I am parsing a JSON Data with Volley library and I retrieve the data in ListView but only the last value is printed.. Here is my implementation :
public void getListElem(final Context context) {
apws = new APWSManager(context, new APWSRequestState() {
#Override
public void customURLFinishedDownload(String response) {
// TODO Auto-generated method stub
Log.i("RESPONSE LISTVIEWPARSER : ", response);
try {
JSONObject json = null;
JSONArray array = new JSONArray(response);
for (int j = 0; j < array.length(); j++) {
json = array.getJSONObject(j);
Log.i("JSONOBJECT : ", json.toString());
parseJsonItem(json);
/* myItemList = new ItemObject(json.getString("title"),
json.getString("value_out"), json.getString("picture")); */
// m_ListItem.add(myItemList);
myList.setAdapter(myAdapter);
Log.i("LISTVIEW TITLE", array.getJSONObject(j).getString("title"));
Log.i("LISTVIEW VALUE", array.getJSONObject(j).getString("value_out"));
Log.i("LISTVIEW PICTURE", array.getJSONObject(j).getString("picture"));
}
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void customURLFailedDownload(String errorMessage) {
// TODO Auto-generated method stub
Log.i("ERROR REQUEST : ", errorMessage.toString());
}
});
apws.callAPWSRequest("getnews", null, null, TypeMethod.GET, true);
}
private void parseJsonItem(JSONObject item) {
try {
ItemObject itemObject = new ItemObject(item.getString("title"), item.getString("value_out"), item.getString("picture"));
// Ici à la place tu ajoutes ton objet dans ton array
m_ListItem.add(itemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
My ListView is printed correctly but always with the same value (the last value in json). How Can I do to retrieve each value in each item of my ListView ?
Thank you guys !
I want to get data from SQL Server and set it to list.
1. I already have data in my current Activity. _I printed it on Logcat_ .
2. Now I want to set that data to my list.
Basically I have taken a static list of data for the basic view, that I mention there
How to set that data to list ?
Here is my Code that will show content how i did code :
public class menus extends Activity {
ListView list;
ArrayAdapter<String> adapter = null;
Editor edit1;
SharedPreferences pref;
SharedPreferences.Editor editor;
int i = 0,count = 0;
String[] listOfMenus;
String listdetails;
Connection xyz;
Statement st;
ResultSet rs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_item);
list=(ListView)findViewById(R.id.menulistblank);
editor = getPreferences(MODE_PRIVATE).edit();
/////// This is my Static data that I stored in list.
String[] values = new String[]{"Adroid Developer",".Net Developer","Java Developer","BA"};
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
list.setAdapter(adapter);
// Object of connection for getting content.
xyz = MainActivity.conn;
MyNetworkTask myWebFetch = new MyNetworkTask();
myWebFetch.execute();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "You click "+arg2, Toast.LENGTH_SHORT).show();
}
});
}
//////// ASYNC TASK ////////
private class MyNetworkTask extends AsyncTask<Void, Void, Void> {
protected void onProgressUpdate(Integer... progress) {
Log.w("Process completed", "In XXXXXXXX");
}
protected void onPostExecute(Long result) {
Log.w("Process completed", "aaaaaaaaaa");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.w("Process completed", "In doInBackground..");
try {
st = MainActivity.conn.createStatement();
rs = st.executeQuery("SELECT * FROM lalit_db;");
while(rs.next()){
// ***** It prints my required data in Logcat
Log.w(rs.getString(2), rs.getString(3));
}
Thread.sleep(5000);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}// Main Program Ends..
Please tell me what should i do to
set this data of logcat Log.w(rs.getString(2), rs.getString(3)); in List.
add strings in values while fetching data
st = MainActivity.conn.createStatement();
rs = st.executeQuery("SELECT * FROM lalit_db;");
values=new String[st.getFetchSize()]; //total number of rows
int index=0;
while(rs.next()){
values[index]=rs.getString(2);
index++;
// ***** It prints my required data in Logcat
Log.w(rs.getString(2), rs.getString(3));
}
Display in onPostExecute()
protected void onPostExecute(Void result) {
Log.w("Process completed", "aaaaaaaaaa");
adapter = new ArrayAdapter<String>(menus.this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
list.setAdapter(adapter);
}
Edit
add #Override annotation to onPostExecute() method
#Override
protected void onPostExecute(Void result) {
Log.w("Process completed", "aaaaaaaaaa");
}
if you want multicolumn ListView , try this :
public void fillList(ResultSet rs,ListView list_head,ListView list,int layout,int to[],String columns[],String titles[])
{
ArrayList<HashMap<String, String>> mylist, mylist_title;
ListAdapter adapter_title, adapter;
HashMap<String, String> map1, map2;
mylist = new ArrayList<HashMap<String, String>>();
mylist_title = new ArrayList<HashMap<String, String>>();
/**********Display the headings************/
map1 = new HashMap<String, String>();
for (int i = 0; i < columns.length; i++)
map1.put(columns[i], titles[i]);
mylist_title.add(map1);
try
{
adapter_title = new SimpleAdapter(context, mylist_title,layout,columns, to);
list_head.setAdapter(adapter_title);
} catch (Exception e) {
Log.w("Error1","" + e.getMessage());
e.printStackTrace();
}
/**********Display the contents************/
try
{
while(rs.next())
{
map2 = new HashMap<String, String>();
for (int i = 0; i < columns.length; i++)
map2.put(columns[i], rs.getObject(columns[i]).toString());
mylist.add(map2);
}
} catch (SQLException e1)
{
// TODO Auto-generated catch block
Log.w("Error2","" + e1.getMessage());
e1.printStackTrace();
}
try
{
adapter = new SimpleAdapter(context, mylist, layout,columns, to);
list.setAdapter(adapter);
}
catch (Exception e)
{
Log.w("Error3","" + e.getMessage());
e.printStackTrace();
}
}
im writing an app for a site which uses JSON API. Im trying to parse the JSON but i get:
Error parsing data org.json.JSONException: Value error of type
java.lang.String cannot be converted to JSONArray
This is due its a string, i've tried other methods but i can only get information from the first string, because each string has its own randomly generated "filename/id", you can take a look at the json output:
{"error":"","S8tf":{"infoToken":"wCfhXe","deleteToken":"gzHTfGcF","size":122484,"sha1":"8c4e2bbc0794d2bd4f901a36627e555c068a94e6","filename":"Screen_Shot_2013-07-02_at_3.52.23_PM.png"},"S29N":{"infoToken":"joRm6p","deleteToken":"IL5STLhq","size":129332,"sha1":"b4a03897121d0320b82059c36f7a10a8ef4c113d","filename":"Stockholmsyndromet.docx"}}
Im trying to get it to show both of the "objects" from the json string. How can i make a lopp for it to find all the items or simply make it list all the "objects" contained in the "error" identifier?
My Main Activity:
public class FilesActivity extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
ActionBar ABS;
TextView session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
TextView txt = (TextView)findViewById(R.id.nodata);
/**String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = null;
try {
jObject = new JSONObject(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject menu = null;
try {
menu = jObject.getJSONObject("menu");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String,String> map = new HashMap<String,String>();
Iterator<String> iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = null;
try {
value = menu.getString(key);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map.put(key,value);
txt.setText(value);
} **/
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/files?session=" + PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
//session = (TextView)findViewById(R.id.textView1);
//session.setText(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String files = null;
try {
int id;
String name;
JSONArray array = new JSONArray("error");
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
//JSONArray shows = object.getJSONArray("");
/*String shows = object.getString("S*");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
//JSONObject e = shows.getJSONObject(i);
files = shows;
//map.put("video_location", "" + e.getString("video_location"));
//TextView txt = (TextView)findViewById(R.id.nodata);
//txt.setText(files);
mylist.add(map); *
}*/
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { files, "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
//Intent myIntent = new Intent(ListShowsController.this,
// TestVideoController.class);
//myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("video_channel", o.get("video_channel"));
//myIntent.putExtra("video_location", o.get("video_location"));
//startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
Any help is much appreciated!
You're trying to get the error field as a JSONArray. Its a string. You can't process a string as an array, it throws that exception. In fact, I don't see any arrays in there at all.
I would look into using a JSon library like Gson (https://code.google.com/p/google-gson/). You are able to deserialize collections, which is much easier than doing it yourself.
I use this code to load the nearby places of any particular location by setting the** data using an Array Adapter. There are two issues that I face:
1. The spinner doesn't stop even after the data is loaded. (There should be no spinner. But I am not sure how does Fragment when it comes to this.)
I'm going to implement AsyncTask to get the places so that it doesn't slow down the Activity. The mini problem I face is this: How do I notify the user (update the view) with new date when he/she has changed his location. Let's assume that that the user is walking. Thus the lat/lon will change. So, how can I use onChangeNotify() and change the value of the List.
public class FragmentMap extends ListFragment {
ArrayList<Place> places = new ArrayList<Place>();
//List<String> val = new List<String>()
//#InjectView(R.id.explorePlacesListView) ListView placesListView;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView = (ListView) getActivity().findViewById(R.id.explorePlacesListView);
getPlaces();
PlacesAdapter placesAdapter = new PlacesAdapter(getActivity(),R.layout.user_list_item, places);
listView.setAdapter(placesAdapter);
}
public void getPlaces(){
URL yahoo;
String key,latitude,longitude;
key = "AIzaSyAZgD01sj3jssaYCmkLL8c7Z4qPTEdt6xU";
latitude = "37.77264";
longitude ="-122.409915";
try {
yahoo = new URL("https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyB2SGEmOLDGB_f0bp1PGTjQqTw2VuDcaM8");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
String jsonLine = new String();
while ((inputLine = in.readLine()) != null) {
Log.d("inputLine",inputLine);
jsonLine = jsonLine + inputLine;
}
in.close();
Object jsonResponse = parseResponse(jsonLine);
parseJSONPlaces((JSONObject)jsonResponse);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Object parseResponse(String responseBody) throws JSONException {
return new JSONTokener(responseBody).nextValue();
}
private void parseJSONPlaces(JSONObject json){
try {
JSONArray jsonArray = json.getJSONArray("results");
for (int j = 0; j < json.length(); j++) {
Place place = new Place();
place.name = jsonArray.getJSONObject(j).getString("name");
place.icon = jsonArray.getJSONObject(j).getString("icon");
// JSONObject locationObject = jsonArray.getJSONObject(j).getJSONObject("location");
// place.latitude = locationObject.getString("latitude");
// place.longitude = locationObject.getString("longitude");
Log.d("name",place.name);
places.add(place);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(json.optJSONObject("results") != null){
}
}
There are a few things in your code that looks a bit strange to me.
You never call setListAdapter() which binds an adapter to the internal ListView of the ListFragment. Instead, you are fetching another ListView and set an adapter to that one. That is probably why no data gets displayed in the list, and you will instead se a progress indicator.
I'm not sure I understand your second question, but you should put your UI updates in the onPostExecute method of AsychTask.
basically I have some data stories in an API in JSON format.
I have managed to get the data from the JSON, loop through the, put them into a TextView, add onClick() on the textView.
but I want to be able to use the optical button on the phone to scroll, so I been told I need a ListView()
So I put the text I want into an array and added the array to the listView
As the example shows below
But how do I add onClick for each Item and pass the ID (intStoryID)?????????
My Code Example
BufferedReader jsonBr = null;
ArrayList arrStoryList = null;
public void onCreate(Bundle savedInstancesState){
super.onCreate(savedInstancesState);
setContentView(R.layout.stories_main);
if(setTopStoryData()){
setStoriesArray();
buildPage();
}else{
// TODO add Error Handling
}
}
public boolean setTopStoryData(){
String strURL = "http://www.example.com/api/index.php?my=params";
JSONConn jsonConn = new JSONConn();
JSONConn.setURL(strURL);
if(jsonConn.setData()){
jsonBr = jsonConn.Br();
return true;
}else{
// my Error Handling
return false;
}
}
public void setStoriesArray(){
String line;
String strAddDate;
String strCurrentStatus;
String strStatusRead;
int intStoryID;
int intNumStories;
arrStoryList = new ArrayList();
JSONObject arrStories;
JSONObject arrAllStories;
JSONObject arrSingleStory;
try{
while((line = jsonBr.readLine()) != null){
arrStories = new JSONObject(line);
intNumStories = Integer.parseInt(arrStories.optString("NumStories"));
arrAllStories = arrStories.getJSONObject("StoryData");
if(intNumStories > 0){
for(int i = 0; i < intNumStories; i++){
arrSingleStory = arrAllStories.getJSONObject("Story"+i);
intStoryID = Integer.parseInt(arrSingleStory.getString("ID"));
strAddDate = arrSingleStory.getString("ADDEDDATE");
strCurrentStatus = arrSingleStory.getString("CURRENTSTATUS");
if(strCurrentStatus.equals("y")){
strStatusRead = "Online";
}else if(strCurrentStatus.equals("n")){
strStatusRead = "Offline";
}else{
strStatusRead = "Pending";
}
String strStoryText = strAddDate+" - " +strCurrentStatus;
arrStoryList.add(strStoryText));
} // end FOR loop
}
} //End while loop
} catch (IOException e) {
// TODO Auto-generated catch block
strDEBUG += "Error (2)";
} catch (JSONException e) {
// TODO Auto-generated catch block
strDEBUG += "Error (3) "+e.getLocalizedMessage()+"\n";
}
}
public void buildPage(){
if(this.arrStoryList != null){
ListView lv1 = (ListView)findViewById(R.id.listView1);
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,this.arrStoryList));
}
}
use onItemClickListener() to the list view to get click event on each item
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
// do whatever you want here
}
});