extract data from PHP json to use in android - java

I'm using this code to fetch some data from PHP file and extract some data into my android application.
This code extract name, price and availability for each product and put each one in an String.
Now I need to have array of the product in java which that is included name,price and availability for each product and name them product1 product2 product3 so I'll be able to write rest of my code based on that.
How can I do that ?
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view.findViewById(R.id.name)).getText().toString();
String selval1 = ((TextView) view.findViewById(R.id.price)).getText().toString();
String selval2 = ((TextView) view.findViewById(R.id.found)).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval", selval);
intnt.putExtra("selval1", selval1);
intnt.putExtra("selval2", selval2);
startActivity(intnt);
}
});
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[]{url});
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}

its very simple, by using this code outside of the for loop
JSONObject pro1 = jsonMainNode.getJSONObject(0);

Related

JSONParser: IOException: Unable to resolve host "my host address": No address associated with hostname

I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.

Google Places Details search System.err

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);
}

How to access json array that is passed from restful web service in android?

I have successfully created a rest web service and it returns jsonarray which has two fields
id and city from data base.
My resr web service is
#GET
#Path("city")
#Produces("application/json")
public String getJson() {
PropertyPojo propojo=null;
ArrayList cityList = new ArrayList();
JSONArray list = new JSONArray();
Map m1 = new LinkedHashMap();
List l1 = new LinkedList();
String jsonString = null;
try{
cityList=PDao.CityList();
Iterator it=cityList.iterator();
while(it.hasNext())
{
propojo=(PropertyPojo)it.next();
m1.put(propojo.getKeyid(),propojo.getKeyvalue());
}
}catch(Exception e){
}
l1.add(m1);
jsonString = JSONValue.toJSONString(l1);
return jsonString;
}
I just need to put these values into a spinner...
My android code is
public class MainActivity extends Activity {
Spinner spinner;
private static final String SERVICE_URL = "http://192.168.1.6:8080/eSava_RestWeb/webresources/service";
private static final String TAG = "AndroidRESTClientActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.city);
}
public void retrieveSampleData(View vw) {
String sampleURL = SERVICE_URL + "/city";
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK,
this, "GETting data...");
wst.execute(new String[] { sampleURL });
}
#SuppressLint("NewApi")
public void handleResponse(String response) {
try {
// JSONObject jso = new JSONObject(response);
JSONArray json = new JSONArray(response);
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray) json;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
list.add(jsonArray.get(i).toString());
}
}
Spinner s = (Spinner) findViewById(R.id.city);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, list);
s.setAdapter(adapter);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext,
String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity()
.getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
JSONArray jsArray;
// jsArray = new JSONArray(response);
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
}
Its better to create Model class and then you can parse the response with gson.
For example,
Imagine that you have your response with two strings Name and Mail. Create a model with two strings.
public class Sample{
public Sample()
{
}
#SerializedName("Name")//if needed
String name;
#SerializedName("Email")//if needed
String email;
public void set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void set(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
Then parse your response with gson.
Sample sample = gson.fromJson(jsonRes.toString(), Sample.class);
Then you can access the members of the object sample. Change the Sample class as you needed(with the array of strings and int. You can use ArrayList instead of Array)
String[] city= {};
String[] id= {};
JSONArray jsonDetailsObj = json.getJSONArray("cityList");
JSONObject jsonLoop = null;
int noOfPoints = jsonDetailsObj.length();
city= new String[noOfPoints];
id= new String[noOfPoints];
for (int i=0 ; i < noOfPoints ; i++)
{
jsonLoop=jsonDetailsObj.getJSONObject(i);
city [i] = jsonLoop.getString("CityName");
id[i] = jsonLoop.getString("ID");
}

json array shows in logacat with no errors but does not show in android view

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

Want to insert json data into the Sqlite Database

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

Categories