JSON Data stored to SQLite - android

I am following this to store JSON parsed data into SQLite Database, but whenever i use my app offline not getting stored data into ListView.
Is there anything left to implement in my existing code ?
MainActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper=new CategoryHelper(MainActivity.this);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
databaseHelper.saveCategoryRecord(id,name);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME }, new int[] { R.id.name });
setListAdapter(adapter);
}
}

I don't know what that ServiceHandler thing is, but I'm guessing the call to makeServiceCall() returns null when you're offline. This means you aren't populating the contactList, which means it's empty when you're creating the ListAdapter.
I'm guessing what you want to do, is add an else clause to if (jsonStr != null) that populates contactList with records from your DB. How to do this depends on the implementation details of CategoryHelper.

Using shared preference would be a better approach for that. Follow these steps:
search and download GSON library. This will simplify our task for saving and retrieving JSON to/from shared preferences and let your app use the GSON library
example:
SharedPreferences prefs = getSharedPreferences("mySharedPreferenceKey");
Editor editor = prefs.edit();
Gson gson = new Gson();
//convert your object to string and save it to shared preference
ArrayList<Integer> myIntArrs = new ArrayList<Integer>();
editor.putString("myJSONKey", new Gson().toJson(myIntArrs)).commit();
//get your json string from shared preferences
public final Type ARRAYLIST_INTEGER = new TypeToken<ArrayList<Integer>>(){}.getType();
ArrayList<Integer> intArrs = gson.fromJson(prefs.getString("myJSONKey", "{}"), ARRAYLIST_INTEGER);
//do something with your intArrs
Hope this helps!

Related

How to pass extra data of a list view to another activity in Android?

I am trying to create a list view with only "name" in the parent list (MainActivity) and pass the remaining "email" and "mobile" to another activity (SingleContactActivity) along with the "name". How can I achieve that? Now my MainActivity listview is showing all details, name, email, mobile, I know I have to delete something from here. My second activity result is OK. But MainActivity must display the list with "name" only. For this I need to make changes to the MainActivity code. The issue is that I am new to JAVA and Android programming. I want your help showing exactly which line to delete from MainActivity so it show only "name" in the list, and pass the other two parameters "email" and "mobile to the second activity along with the "name".
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// 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) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}
you can save data in bundle and carry it on next activity. or u can also use shared preference to save data temporarily and next activity you get the data from shared preference and then clear it. https://www.tutorialspoint.com/android/android_shared_preferences.htm
Try to go in second activity using intent.and pass your variables to display in second activity like this:
use this in onPostExecute function or any other event what u want
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("name", namestringvariable);
intent.putExtra("email", emailstringvariable);
startActivity(intent);
finish();
and in second activity
Bundle bundle = getIntent().getExtras();
String name= bundle.getString("name");
String email= bundle.getString("email");

android Restful GET operation

I need to get an image using webservice which is rest.And most of the tutorials are about click the button in order to trigger the process.I need to implement this such a way that when activity opens images has to be loaded immediately without trigger or clicking the button or something.I just need a source or idea.
Any help will be appreciated.
Implement an Asynctask and call it onCreate.
Here is an example on how to do it;
public class MainActivity extends ListActivity {
.
.
.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
.
.
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
As you can see, you only need to call the asynctask (new GetContacts().execute();) onCreate and it will behave as you design it.
References: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Write your code in onCreate() or onResume() method of activity.
For downloading images you can use Picasso and Glide.
For communication between app and webservice you can use Retrofit.
Also for more information you can read this tutorial Retrofit - Getting Started and Create an Android Client
Write your code for loading image in onCreate() method of Activity. So user don't need to trigger or clicking the button or something.

Android JSONObject cannot be converted to JSONArray

I'm new in android. I'm trying to get json but I got this error.
I trying following this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
I already search the solution, but I still don't get it how to use the JSONArray.
Here is my Json example
[{"id":"152","category_id":"14","item_name":"Restaurant1","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"161","category_id":"14","item_name":"Restaurant10","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"153","category_id":"14","item_name":"Restaurant2","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"154","category_id":"14","item_name":"Restaurant3","cuisine_id":"7","cuisine_name":"American"},{"id":"155","category_id":"14","item_name":"Restaurant4","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"156","category_id":"14","item_name":"Restaurant5","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"157","category_id":"14","item_name":"Restaurant6","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"158","category_id":"14","item_name":"Restaurant7","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"159","category_id":"14","item_name":"Restaurant8","cuisine_id":"6","cuisine_name":"Indonesian"},{"id":"160","category_id":"14","item_name":"Restaurant9","cuisine_id":"3","cuisine_name":"Chinese"}]
And Here the class
/**
* Async task class to get json by making HTTP call
* */
private class GetRestaurant extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attractions.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
// looping through All Contacts
for (int i = 0; i < restaurant.length(); i++) {
JSONObject c = restaurant.getJSONObject(i);
String id = c.getString(TAG_CUISINE_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CUISINE_NAME, id);
// adding contact to contact list
restaurantList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Attractions.this, restaurantList,
R.layout.attractionslayout, new String[] { TAG_ITEM_NAME, TAG_CUISINE_NAME }, new int[] { R.id.item_name,
R.id.cuisine_name});
// Assign adapter to ListView
listview.setAdapter(adapter);
}
}
Thanks Before.
Try this..
Your response starts with JSONArray
[ ==> JSONArray
{ ==> JSONObject
Change this..
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
to
restaurant = new JSONArray(jsonStr);
Your string is not json object , it is json array because the string are start via third bracket
so, try this
restaurant = new JSONArray(jsonStr);
you do not need to convert it as a josn object,
JSONObject jsonObj = new JSONObject(jsonStr);

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

JSON to listView in android

I'm trying to put JSON to ListView. I am getting data from http://api.androidhive.info/contacts/ (only using the name field) I am able to get them to array, but im unable to put them into the list,
[NOTE]
however the ListView makes exactly 13 lines for 13 entries (number of names) but the lines are blank.
private class GetJidla extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TableMenuActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
jidla = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < jidla.length(); i++) {
JSONObject c = jidla.getJSONObject(i);
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
// adding contact to contact list
jidlaList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
TableMenuActivity.this, jidlaList,
android.R.layout.simple_list_item_1, new String[] {TAG_NAME}, new int[] {android.R.id.list,
});
menu = (ListView)findViewById(android.R.id.list);
menu.setAdapter(adapter);
}
and the list is here
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip" >
</ListView>
i need it to be on one screen, in one activity here is the image, the brown lsit is where i need it
I have an exemple to do that:
public class MainActivity extends Activity {
//json string
private String jsonString = "{\"employee\":[{\"emp_name\":\"employee1\",\"emp_no\":\"101700\"},{\"emp_name\":\"employee2\",\"emp_no\":\"101701\"},{\"emp_name\":\"employee3\",\"emp_no\":\"101702\"},"+
"{\"emp_name\":\"employee4\",\"emp_no\":\"101703\"},{\"emp_name\":\"employee5\",\"emp_no\":\"101704\"},{\"emp_name\":\"employee6\",\"emp_no\":\"101705\"},"+
"{\"emp_name\":\"employee7\",\"emp_no\":\"101706\"},{\"emp_name\":\"employee8\",\"emp_no\":\"101707\"},{\"emp_name\":\"employee9\",\"emp_no\":\"101708\"},"+
"{\"emp_name\":\"employee10\",\"emp_no\":\"101709\"},{\"emp_name\":\"employee11\",\"emp_no\":\"101710\"},{\"emp_name\":\"employee12\",\"emp_no\":\"101711\"},"+
"{\"emp_name\":\"employee13\",\"emp_no\":\"101712\"},{\"emp_name\":\"employee14\",\"emp_no\":\"101713\"},{\"emp_name\":\"employee15\",\"emp_no\":\"101712\"}]}";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initList();
ListView listView = (ListView) findViewById(R.id.listView1);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, android.R.layout.simple_list_item_1, new String[] {"employees"}, new int[] {android.R.id.text1});
listView.setAdapter(simpleAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
List<Map<String,String>> employeeList = new ArrayList<Map<String,String>>();
private void initList(){
try{
JSONObject jsonResponse = new JSONObject(jsonString);
JSONArray jsonMainNode = jsonResponse.optJSONArray("employee");
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("emp_name");
String number = jsonChildNode.optString("emp_no");
String outPut = name + "-" +number;
employeeList.add(createEmployee("employees", outPut));
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
private HashMap<String, String>createEmployee(String name,String number){
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
I use this code and it works fine!
Code from JSON Exemple
Here is the very simple example for json to list view
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
download the project and use your own service in MainActivity.java
replace the service URl with your url and format your array accordingly thatz it
happy coding.

Categories

Resources