I'm attempting to locate a restaurant by name using an AutoCompleteTextView which successfully obtains the places id. I've also checked the http request manually in my browser which responds with the correct information. When this code is executed, a system.err is shown in the LogCat console in Eclipse. My code below;
public class AdvancedSearch extends Activity implements OnItemClickListener {
private static final String LOG_TAG = "com.lw276.justdine";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
// ------------ make your specific key ------------
private static final String API_KEY = "MyAPIKEY";
private Activity context = this;
static HashMap<String, String> place;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_search);
final AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this,
R.layout.list_item));
autoCompView.setOnItemClickListener(this);
Button btnAdvancedSearch = (Button) findViewById(R.id.advanced_search_btn);
btnAdvancedSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = autoCompView.getText().toString();
if(place.containsKey(str)){
String placeId = place.get(str);
Log.d("advancedSearchBtn: placeId = ", placeId);
Log.i("advancedSearchBtn", "Search button has been pressed");
Intent i = new Intent(context, GoogleMap.class);
i.putExtra("advancedSearch", placeId);
startActivity(i);
} else {
Toast.makeText(context, "Please select an item from the autocomplete list", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
// String str = (String) adapterView.getItemAtPosition(position);
// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE
+ TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: " + url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
resultList = new ArrayList<String>(predsJsonArray.length());
place = new HashMap<String, String>();
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString(
"description"));
System.out
.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString(
"description"));
String description = predsJsonArray.getJSONObject(i).getString("description");
String placeId = predsJsonArray.getJSONObject(i).getString("place_id");
place.put( description, placeId);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String>
implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context,
int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
// #Override
// public HashMap<String, String> getItem(int index) {
// return resultList.get(index);
// }
#Override
public String getItem(int index){
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
The googlePlaces example =
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJCSWGvY-FdUgRpGdg10FTIIg&key="MY_API_KEY"
Is it obvious to anyone why no markers are being placed on my map fragment?
Errors from LogCat:
http://pastebin.com/T1AFbw3s
Google Maps and Markers class:
http://pastebin.com/hT2XwuE2
The error you are having is due to parsing the Json incorrectly at line 193 of GoogleMap activity:
JSONArray placesArray = resultObject.getJSONArray("results");
I believe the key is result instead of results.
I can give you a better explanation if I could see the json response. Meanwhile,
I would also suggest you to use Gson Library to parse the json responses to objects instead of mapping them manually. It would be alot easier.
Markers need to be added manually:
private void addMarker(String name, double lat, double long){
LatLng latlong = LatLng.newInstance(lat, long);
MarkerOptions markerOptions = MarkerOptions.newInstance();
markerOptions.setIcon(Icon.newInstance("/img/icon.png"));
markerOptions.setTitle(name);
Marker marker = new Marker(latlong, markerOptions);
map.addOverlay(marker);
}
It turns out that because I was using the same code to add markers onto the Map, when the detail search was used to identify a single place, the JSONArray type was incompatible with the result set... If that makes sense.
I had to separate the two by checking if a nearby search was being performed or a details search. Below was the code for the details search only:
resultObject = resultObject.getJSONObject("result"); // <---
places = new MarkerOptions[1];
LatLng placeLL = null;
String placeName = "";
String vicinity = "";
try {
JSONObject placeObject = resultObject;
JSONObject loc = placeObject.getJSONObject(
"geometry").getJSONObject("location");
placeLL = new LatLng(Double.valueOf(loc
.getString("lat")), Double.valueOf(loc
.getString("lng")));
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
} catch (JSONException jse) {
missingValue = true;
jse.printStackTrace();
}
if (missingValue){
result = null;
} else {
places[0] = new MarkerOptions().position(placeLL)
.title(placeName).snippet(vicinity);
}
A large part of my app is grabbing data from a website. The data shows in my logcat, green with no errors but will not display in my android view. Ive tried and searched for a week or and have had no luck.
here is my class.
public class Json extends ListActivity {
ArrayList<HashMap<String, String>> jsonParser = new ArrayList<HashMap<String, String>>();
ListView lv ;
private static final String jsonFilePath = "http://xda.olinksoftware.com/leaderboard/all";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
new ProgressTask(Json.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(Json json) {
Log.i("1", "Called");
context = json;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonParser,
R.layout.listitem, new String[] { TAG_NAME, TAG_SCORE,
}, new int[] {
R.id.score, R.id.name,
});
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
#Override
protected Boolean doInBackground(final String... args) {
new JSONParser();
try {
BufferedReader reader = null;
String jsonString = "";
StringBuffer buffer = new StringBuffer();
try{
URL url = new URL(jsonFilePath);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
}finally {
if (reader != null)
reader.close();
}
jsonString = buffer.toString();
try{
JSONParser jsonParser = new JSONParser();
JSONArray leaderboard = (JSONArray)jsonParser.parse(jsonString);
for(int i = 0;i<leaderboard.size();i++){
JSONObject user = (JSONObject)leaderboard.get(i);
System.out.println((i+1) + ". " + user.get("forumName") + " (" + user.get("score") + ")");
}
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}}
}
and here are my xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/score"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingLeft="6dp"
android:textSize="17sp"
android:textStyle="bold"/>
</LinearLayout>
any help is greatly appreciated. I know I am doing something wrong with my listview as it also works as a straight java application run in eclipse.
here is the data i am grabbing, i am only taking two values at this time. "forumUser" and "score"
[{"userId":"3579348","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3579348","forumName":"newtoroot","totalPosts":"5074","postsPerDay":"5.14","totalThanks":"18302","joinDate":"2011-01-29","yearsJoined":"2","referrals":"4","friendCount":"38","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"48","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"302","userName":"","password":""},{"userId":"1596076","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1596076","forumName":"il Duce","totalPosts":"16335","postsPerDay":"9.75","totalThanks":"15799","joinDate":"2009-02-25","yearsJoined":"4","referrals":"2","friendCount":"83","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"1","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"1","tutorialCount":"0","modCount":"0","themeCount":"0","score":"132","userName":"","password":""},{"userId":"2930301","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2930301","forumName":"fernando sor","totalPosts":"8967","postsPerDay":"7.93","totalThanks":"4549","joinDate":"2010-09-07","yearsJoined":"3","referrals":"2","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"1","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"5","modCount":"2","themeCount":"15","score":"120","userName":"fernando sor","password":""},{"userId":"3220669","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3220669","forumName":"1975jamie","totalPosts":"582","postsPerDay":"0.56","totalThanks":"127","joinDate":"2010-11-23","yearsJoined":"2","referrals":"0","friendCount":"0","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"4","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"46","userName":"1975jamie","password":""},{"userId":"2552854","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2552854","forumName":"jeffsanace","totalPosts":"2797","postsPerDay":"2.25","totalThanks":"2836","joinDate":"2010-05-05","yearsJoined":"3","referrals":"0","friendCount":"12","recognizedDeveloper":"0","recognizedContributor":"1","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"37","userName":"","password":""},{"userId":"2067958","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2067958","forumName":"eg1122","totalPosts":"1200","postsPerDay":"0.82","totalThanks":"1695","joinDate":"2009-10-05","yearsJoined":"3","referrals":"0","friendCount":"6","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"2","themeCount":"0","score":"20","userName":"","password":""},{"userId":"3042344","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3042344","forumName":"dfuse06","totalPosts":"3331","postsPerDay":"3.08","totalThanks":"2270","joinDate":"2010-10-11","yearsJoined":"2","referrals":"1","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"17","userName":"","password":""},{"userId":"1070340","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1070340","forumName":"chrisloveskaos","totalPosts":"215","postsPerDay":"0.11","totalThanks":"8","joinDate":"2008-07-08","yearsJoined":"5","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"14","userName":"","password":""},{"userId":"2688514","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2688514","forumName":"GooTz66","totalPosts":"999","postsPerDay":"0.84","totalThanks":"70","joinDate":"2010-06-25","yearsJoined":"3","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"7","userName":"","password":""},{"userId":"2141845","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2141845","forumName":"Kush.Kush\u00c2\u0099","totalPosts":"86","postsPerDay":"0.06","totalThanks":"0","joinDate":"2009-11-09","yearsJoined":"3","referrals":"0","friendCount":"16","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"6","userName":"","password":""}]
Why is this line
setListAdapter(adapter);
Before this
// selecting single ListView item
lv = getListView();
Also, the LogCat you posted is showing the results using the "info" filter only. Try looking at the verbose view to make sure no exceptions that you're missing.
what i did to solve this was pretty much start over. i added a JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
and a JsonActivity
public class MainActivity extends ListActivity {
private static String url = "website";
private static final String TAG_VTYPE = "forumName";
private static final String TAG_VCOLOR = "score";
private static final String TAG_THANKS = "totalThanks";
private static final String TAG_POSTS = "totalPosts";
private static final String TAG_JOIN_DATE = "joinDate";
private static final String TAG_ROM_COUNT = "romCount";
private static final String TAG_THEME_COUNT = "themeCount";
private static final String TAG_MOD_COUNT = "modCount";
private static final String TAG_KERNEL_COUNT = "kernelCount";
private static final String TAG_TUTORIAL_COUNT = "tutorialCount";
private static final String TAG_DEV = "recognizedDeveloper";
private static final String TAG_THEMER = "recognizedThemer";
private static final String TAG_MODERATOR = "moderator";
private static final String TAG_RDEV = "recognizedEliteDeveloper";
private static final String TAG_RCOD = "recognizedContributor";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
private View header;
ListView lv ;
LayoutInflater Inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
Inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
View header = Inflater.inflate(R.layout.header_view_name, null);
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR, TAG_THANKS, TAG_POSTS, TAG_JOIN_DATE, TAG_ROM_COUNT,
TAG_THEME_COUNT, TAG_MOD_COUNT, TAG_KERNEL_COUNT, TAG_DEV, TAG_TUTORIAL_COUNT, TAG_THEMER, TAG_MODERATOR, TAG_RDEV, TAG_RCOD,
}, new int[] {
R.id.vehicleType, R.id.vehicleColor, R.id.totalThanks, R.id.totalPosts, R.id.joinDate, R.id.romCount,
R.id.themeCount, R.id.kernelCount, R.id.modCount, R.id.tutorialCount, R.id.moderator, R.id.rThemer, R.id.rDev,
R.id.rCon, R.id.rEliteDev,
});
lv = getListView();
lv.addHeaderView(header);
setListAdapter(adapter);
// selecting single ListView item
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// getting values from selected ListItem
String forumName = ((TextView) view.findViewById(R.id.vehicleType)).getText().toString();
String score = ((TextView) view.findViewById(R.id.vehicleColor)).getText().toString();
String totalThanks = ((TextView) view.findViewById(R.id.totalThanks)).getText().toString();
String totalPosts = ((TextView) view.findViewById(R.id.totalPosts)).getText().toString();
String joinDate = ((TextView) view.findViewById(R.id.joinDate)).getText().toString();
String romCount = ((TextView) view.findViewById(R.id.romCount)).getText().toString();
String themeCount = ((TextView) view.findViewById(R.id.themeCount)).getText().toString();
String kernelCount = ((TextView) view.findViewById(R.id.kernelCount)).getText().toString();
String modCount = ((TextView) view.findViewById(R.id.modCount)).getText().toString();
String tutorialCount = ((TextView) view.findViewById(R.id.tutorialCount)).getText().toString();
String moderator = ((TextView) view.findViewById(R.id.moderator)).getText().toString();
String recognizedThemer = ((TextView) view.findViewById(R.id.rThemer)).getText().toString();
String recognizedDeveloper = ((TextView) view.findViewById(R.id.rDev)).getText().toString();
String recognizedContributor = ((TextView) view.findViewById(R.id.rCon)).getText().toString();
String recognizedEliteDeveloper = ((TextView) view.findViewById(R.id.rEliteDev)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_VTYPE, forumName);
in.putExtra(TAG_VCOLOR, score);
in.putExtra(TAG_THANKS, totalThanks);
in.putExtra(TAG_POSTS, totalPosts);
in.putExtra(TAG_JOIN_DATE, joinDate);
in.putExtra(TAG_ROM_COUNT, romCount);
in.putExtra(TAG_THEME_COUNT, themeCount);
in.putExtra(TAG_MOD_COUNT, modCount);
in.putExtra(TAG_KERNEL_COUNT, kernelCount);
in.putExtra(TAG_TUTORIAL_COUNT, tutorialCount);
in.putExtra(TAG_DEV, recognizedDeveloper);
in.putExtra(TAG_THEMER, recognizedThemer);
in.putExtra(TAG_MODERATOR, moderator);
in.putExtra(TAG_RDEV, recognizedEliteDeveloper);
in.putExtra(TAG_RCOD, recognizedContributor);
startActivity(in);
}});}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String forumName = c.getString(TAG_VTYPE);
String score = c.getString(TAG_VCOLOR);
String totalThanks = c.getString(TAG_THANKS);
String totalPosts = c.getString(TAG_POSTS);
String joinDate = c.getString(TAG_JOIN_DATE);
String romCount = c.getString(TAG_ROM_COUNT);
String themeCount = c.getString(TAG_THEME_COUNT);
String modCount = c.getString(TAG_MOD_COUNT);
String kernelCount = c.getString(TAG_KERNEL_COUNT);
String tutorialCount = c.getString(TAG_TUTORIAL_COUNT);
String recognizedDeveloper = c.getString(TAG_DEV);
String recognizedThemer = c.getString(TAG_THEMER);
String moderator = c.getString(TAG_MODERATOR);
String recognizedEliteDeveloper = c.getString(TAG_RDEV);
String recognizedContributor = c.getString(TAG_RCOD);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_VTYPE, forumName);
map.put(TAG_VCOLOR, score);
map.put(TAG_THANKS, totalThanks);
map.put(TAG_POSTS, totalPosts);
map.put(TAG_JOIN_DATE, joinDate);
map.put(TAG_ROM_COUNT, romCount);
map.put(TAG_THEME_COUNT, themeCount);
map.put(TAG_MOD_COUNT, modCount);
map.put(TAG_KERNEL_COUNT, kernelCount);
map.put(TAG_TUTORIAL_COUNT, tutorialCount);
map.put(TAG_DEV, recognizedDeveloper);
map.put(TAG_THEMER, recognizedThemer);
map.put(TAG_MODERATOR, moderator);
map.put(TAG_RDEV, recognizedEliteDeveloper);
map.put(TAG_RCOD, recognizedContributor);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}}}
and tied it together with a list view and xml for all my values. turned out really cool. i added an onclick on each value to show more individual data
I want to store an json data to db,it has to display my apps has to display some previous data without internet time also.For that i want to create an db for json data to store.
This is the db part i created for json data.
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "ginfy.db";
private static final String DATABASE_TABLE_PROJ = "prayers";
private static final int DATABASE_VERSION = 2;
public static final String CATEGORY_COLUMN_ID = "id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "ProjectDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public GinfyDbAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
}
public GinfyDbAdapter GinfyDbAdapter(Context context){
mDbHelper = new DatabaseHelper(context);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key autoincrement, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer primary key autoincrement );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER PRIMARY KEY )" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_NAME);
onCreate(db);
}
}
}
this is mainactivity which is showing listview
public class MainActivity extends Activity implements FetchDataListener,OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final String TAG_CATEGORY = "post";
private static final String CATEGORY_COLUMN_ID = "id";
private static final String CATEGORY_COLUMN_TITLE = "title";
private static final String CATEGORY_COLUMN_CONTENT = "content";
private static final String CATEGORY_COLUMN_COUNT = "count";
private static final int Application = 0;
private ProgressDialog dialog;
ListView lv;
ListView lv1;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int pct;
private String stringVal;
private TextView value;
private int prayers;
private int prayerid;
EditText myFilter;
ApplicationAdapter adapter;
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
//JSONParser jParser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(id,title,content,count);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(CATEGORY_COLUMN_ID, id);
map.put(CATEGORY_COLUMN_TITLE, title);
map.put(CATEGORY_COLUMN_CONTENT, content);
map.put(CATEGORY_COLUMN_COUNT, count);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddPrayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data){
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
/*dataAdapter adapter = new SimpleCursorAdapter(this,
R.layout.activity_row,
new String[] { CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, new int[] {
R.id.text2, R.id.text1, R.id.count });*/
//lv.setListAdapter(adapter);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg){
if ( dialog != null )
dialog.dismiss();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
Before using db it shows in listview also,rite now i want to make db also,for that i wrote some code in mainactivity.
Fetchdatatask.java
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private OnClickListener onClickListener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
app.setTitle(json.getString("title"));
app.setCount(Integer.parseInt(json.getString("count")));
app.setId(Integer.parseInt(json.getString("id")));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
This fetchdatatask fetch from json and showing in listview,i want that without internet time it has to show in listview also for that i am creating db.
can you check my code is correct,actually it showing error in mainactivity line JSONArray aJson = jsonObject.getJSONFromUrl(url);
Create a class which act's as the intermediate between your Db class and the main activity to insert the data into the db and vice versa
public class Category {
String id;
String title;
String content;
String count;
public Category(String id, String title, String content, String count) {
super();
this.id = id;
this.title = title;
this.content = content;
this.count = count;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
In your main activity where you do the json parsing create an object of DB class and call one the save record method at there like i did below
DatabaseHelper mDbHelper;
public class ABC extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
mDbHelper= new DatabaseHelper (this);
new GetSyncDataAsyncTask().execute();
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog Dialog = new ProgressDialog(ABC.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Dialog.dismiss();
Intent intent = new Intent(ABC.this, XYZ.class);
startActivity(intent);
}
#Override
protected Boolean doInBackground(Void... params) {
getData();
return null;
}
}
public void getProdData() {
// getting JSON string from URL
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
At last in your db class insert the values like below
public void saveCategoryRecord(Category category) {
String query = "insert into"+ TABLE_NAME+ values( ?, ?, ?, ?, ?, ? )";
SQLiteStatement stmt = mDb.compileStatement(query);
stmt.bindString(1, category.getId());
stmt.bindString(2, category.getTitle());
stmt.bindString(3, category.getContent());
stmt.bindString(4, category.getCount());
stmt.execute();
}
I have tried to use the same things as you have used. This is the way i think now you got the concept to do that