Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Hi i'm completely new to Android. Very used to .Net and SQL Server. Hence, having issue adopting to SQLite. I'm currently able to display the result in a listView from a URL via HttpGet. Kindly be gentle with me. Helps are greatly appreciated, as I'm stuck in SQLite for the past week.
Just want check if it's possible to set it such that
HttpGet will retrieve and insert into SQLite table.
listView retrieve All columns data from SQLite table.
The HttpGet AsyncTask will run only if 48hrs has pass. So for example if the the download happens on Monday, the database should not be updated if the person use the app on Tuesday. However, the data will be updated on Wed when the user on it.
It will delete all column in the table before inserting into SQlite table.
EncounterActivity.Java
public class EncounterActivity extends Activity {
ListView list;
TextView eid;
TextView eclerkship;
TextView ename;
TextView etype;
TextView erequiredattempts;
EncounterDbAdapter encounterDB;
Context myContext;
Button Btngetdata;
ArrayList<HashMap<String, String>> encouterlist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "SorryHadToRemoveThisDueToSomeReason";
//JSON Node Names
private static final String TAG_ENCOUNTERS = "encounters";
private static final String TAG_E_ID = "e_id";
private static final String TAG_E_CLERKSHIP = "clerkship";
private static final String TAG_E_NAME = "encounter_name";
private static final String TAG_E_TYPE = "type";
private static final String TAG_E_REQUIRED_ATTEMPTS = "required_attempts";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encounter);
encouterlist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
eid = (TextView)findViewById(R.id.eid);
eclerkship = (TextView)findViewById(R.id.eclerkship);
ename = (TextView)findViewById(R.id.ename);
etype = (TextView)findViewById(R.id.etype);
erequiredattempts = (TextView)findViewById(R.id.erequiredattempts);
pDialog = new ProgressDialog(EncounterActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_ENCOUNTERS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String eid = c.getString(TAG_E_ID);
String eclerkship = c.getString(TAG_E_CLERKSHIP);
String ename = c.getString(TAG_E_NAME);
String etype = c.getString(TAG_E_TYPE);
String erequiredattempts = c.getString(TAG_E_REQUIRED_ATTEMPTS);
// Opening of database
encounterDB = new EncounterDbAdapter(myContext);
encounterDB.open();
encounterDB.insertEncounterEntry(eid, eclerkship, ename, etype, erequiredattempts);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_E_ID, eid);
map.put(TAG_E_CLERKSHIP, eclerkship);
map.put(TAG_E_NAME, ename);
map.put(TAG_E_TYPE, etype);
map.put(TAG_E_REQUIRED_ATTEMPTS, erequiredattempts);
encouterlist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(EncounterActivity.this, encouterlist,
R.layout.list_v,
new String[] { TAG_E_ID, TAG_E_CLERKSHIP, TAG_E_NAME, TAG_E_TYPE, TAG_E_REQUIRED_ATTEMPTS }, new int[] {
R.id.eid, R.id.eclerkship, R.id.ename, R.id.etype, R.id.erequiredattempts});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(EncounterActivity.this, "You Clicked at "+encouterlist.get(+position).get("type"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
EncounterDbAdapter.java
public class EncounterDbAdapter {
private static final String DATABASE_NAME = "mediLearner.db";
private static final String DATABASE_TABLE = "EncounterDb";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase _db;
private final Context context;
public static final String E_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String CLERKSHIP = "entry_clerkship";
public static final int COLUMN_CLERKSHIP_ID = 1;
public static final String ENCOUNTER_NAME = "entry_encounter";
public static final int COLUMN_ENCOUNTER_NAME = 2;
public static final String TYPE = "entry_type";
public static final int COLUMN_TYPE = 3;
public static final String REQUIRED_ATTEMPTS = "entry_requiredAttempts";
public static final int COLUMN_REQUIRED_ATTEMPTS = 4;
protected static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + E_ID
+ " PRIMARY KEY, " + CLERKSHIP + " Text, "
+ ENCOUNTER_NAME + " text, " + TYPE + " Text, "
+ REQUIRED_ATTEMPTS + " Text);";
private String encounterDBADAPTER_LOG_CAT = "MY_LOG";
private myDBOpenHelper dbHelper;
public EncounterDbAdapter(Context _context) {
this.context = _context;
dbHelper = new myDBOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public void close() {
_db.close();
Log.w(encounterDBADAPTER_LOG_CAT, "DB closed");
}
public void open() throws SQLiteException {
try{
_db=dbHelper.getWritableDatabase();
Log.w(encounterDBADAPTER_LOG_CAT, "DB opened as writable database");
}catch(SQLiteException ex){
_db=dbHelper.getReadableDatabase();
Log.w(encounterDBADAPTER_LOG_CAT, "DB opened as readable database");
}
}
//insertion
public long insertEncounterEntry(String ID , String clerkship, String encounter, String type, String requiredAttempts ) {
//insert new task
ContentValues newEntryValues=new ContentValues();
newEntryValues.put(E_ID, ID);
newEntryValues.put(CLERKSHIP,clerkship);
newEntryValues.put(ENCOUNTER_NAME,encounter);
newEntryValues.put(TYPE, type);
newEntryValues.put(REQUIRED_ATTEMPTS, requiredAttempts);
//Insert the row
Log.w(encounterDBADAPTER_LOG_CAT, "Inserted E_ID="+ID+" CLERKSHIP="+clerkship + "Inserted ENCOUNTER_NAME="+encounter + "Inserted TYPE="+type + "Inserted REQUIRED_ATTEMPTS="+requiredAttempts +"into table"+DATABASE_TABLE);
return _db.insert(DATABASE_TABLE, null, newEntryValues);
}
public boolean removeEntry(long _rowIndex) {
if(_db.delete(DATABASE_TABLE, E_ID+"="+_rowIndex, null)<=0)
{
Log.w(encounterDBADAPTER_LOG_CAT,"Removing Entrying where id="+_rowIndex+"Failed");
return false;
}
Log.w(encounterDBADAPTER_LOG_CAT,"Removing Entrying where id="+_rowIndex+"Success");
return true;
}
//updating
public boolean updateEntry(int ID , String clerkship, String encounter_name, String type, String requiredAttempts ) {
return false;
}
//retrival
public Cursor retrieveAllEntriesCursor() {
Cursor c=null;
try{
c=_db.query(DATABASE_TABLE,new String[]{E_ID, CLERKSHIP, ENCOUNTER_NAME, TYPE, REQUIRED_ATTEMPTS}, null,null,null,null,null);
}catch(SQLException sle){
Log.w(encounterDBADAPTER_LOG_CAT,"Retrieve fail!!");
}
return c;
}
public class myDBOpenHelper extends SQLiteOpenHelper {
public myDBOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
Log.w(encounterDBADAPTER_LOG_CAT, "Helper : DB " + DATABASE_TABLE
+ " Created!!");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
} // End of myDBOpenHelper
}// End of myDBAdapter
I would not use a Timer for the updates, but instead use a Service that starts on an interval set up by the AlarmManager. Like this:
public void setScheduling() {
Date now = new Date();
// Set the time to download to 18:00
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartDownloadReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
mgr.cancel(pi);
// 1 * 24 * 60 * 60 * 1000 = repeat this every day
mgr.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 1 * 24 * 60 * 60 * 1000, pi);
}
Handle the pending intent in a BroadcastReceiver:
public class StartDownloadReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean autoDownload = sharedPreferences.getBoolean("auto_download", false);
if (autoDownload) {
context.startService(new Intent(context, DownloaderService.class));
}
}
}
In your download service you would then use an AsyncTask to do the downloading, parsing and updating of the database.
I recently finished an app with somewhat the exact same requirements;
every day at 18:00 download an RSS feed
If the download and parsing was successful wipe the database tables and update the data
Send a broadcast to let any Activity that might be open to refresh its ListView
That's basically it, though the implementation is not exactly like that.
Have a look at it here: https://github.com/slidese/SGU
Also: I'm using OrmLite when working with SQLite. I find it to be far easier and quicker to work with than dealing with the SQL directly.
Related
I have an Activity that uses a ListView to display an array of data fetched from a JSON response. Clicking on one of the items will present the user with a business card activity, displaying the data associated with the item clicked. When the application first loads, it works fine. I can close the business card and reopen it multiple times. However, if i pause on the ListView activity, the page will no longer load the data. I have placed Log.d commands before and after the connection to try debugging the issue. The activity is receiving the information necessary to perform the connection. However, the closest I have gotten to a solution is knowing that when it doesn't work, I cannot Log.d the response code immediately after opening the connection.
To be clear, I am including the entirety of the code I am using, just in case the issue lies somewhere else. First is the code for the ListView Activity, then is the Business Card Activity code.
This is the Directory Activity.
public class DirectoryActivity extends AppCompatActivity {
ListView lvContacts;
Button goMenu;
Button goFilter;
TextView tempText;
static ArrayList<String> arrlst = new ArrayList<>();
static ArrayAdapter<String> adapter;
private FetchList process;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directory);
lvContacts = findViewById(R.id.lvContacts);
goMenu = findViewById(R.id.btn_goMenu);
goFilter = findViewById(R.id.btn_goSearch);
tempText = findViewById(R.id.temptext);
// Set adapter for listview: used in FetchList
adapter = new ArrayAdapter<>(this, R.layout.layout_org_list, R.id.listViewItem, arrlst );
lvContacts.setAdapter(adapter);
// Get list from DB
process = new FetchList();
process.setListener(new FetchList.FetchListTaskListener() {
#Override
public void onFetchListTaskFinished(String[] result) {
// update UI in Activity here
arrlst.clear();
for (String OrgName:result) {
addItemsToList(OrgName);
}
adapter.notifyDataSetChanged();
}
});
process.execute();
// Set onclick listener for listview
lvContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String selectedOrg = lvContacts.getItemAtPosition(position).toString(); // Get org name from list view
goBusinessCard(selectedOrg); // Go to business card
}
});
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
public static void addItemsToList(String item) {
arrlst.add(item);
}
// Set Methods for Buttons
public void goMenu(View v) {
startActivity(new Intent(this, HomeActivity.class));
}
public void goFilter(View v) {
startActivity(new Intent(this, FilterActivity.class));
Log.d("FILTER DEBUG", "checking if extras are filled " + this.getIntent().getExtras());
}
// Method for opening BusinessCardActivity and passes orgID
public void goBusinessCard(String selectedOrg) {
Bundle extras = new Bundle();
extras.clear();
extras.putString("selectedOrg", selectedOrg);
Intent BusinessCard = new Intent(this, BusinessCardActivity.class);
BusinessCard.putExtras(extras);
startActivity(BusinessCard);
}
// ASYNC TASK
static class FetchList extends AsyncTask<Void, Void, String[]> {
private FetchListTaskListener listener;
#Override
protected String[] doInBackground(Void... voids) {
try {
URL url = new URL(URL_READ_ORG ); // Set url to API Call location
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // Open connection to html
InputStream inputStream = httpURLConnection.getInputStream(); // create input stream from html location
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); // create reader for inputStream
StringBuilder data = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null ) {
data.append(line); // creates string from all lines in response
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
JSONObject JO = new JSONObject(data.toString()); // creates object from json response in data string
JSONArray JA = JO.getJSONArray("orgs");
// Create array list to store items from json response
List<String> al_orgList = new ArrayList<>();
// Iterate through JSON array to get json object org_name
for (int i = 0; i < JA.length(); i++) {
JSONObject Orgs = JA.getJSONObject(i);
String org_name = Orgs.getString("org_name");
al_orgList.add(org_name);
}
// convert array list to array
return al_orgList.toArray(new String[al_orgList.size()]);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}
// UI Process - allows manipulation of UI
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
if (listener != null) {
listener.onFetchListTaskFinished(result);
}
}
private void setListener(FetchListTaskListener listener) {
this.listener = listener;
}
public interface FetchListTaskListener {
void onFetchListTaskFinished(String[] result);
}
}
This is the Business Card Activity that runs the data fetch for individual items
public class BusinessCardActivity extends AppCompatActivity {
TextView tv_org, tv_name, tv_email, tv_phone, tv_website, tv_servicetype,
tv_servicesprovided, tv_address;
String Favorite, Latitude, Longitude, selectedOrg, FavoriteChanged, dbPhone, phoneNum, dbWeb, orgWeb;
CheckBox cbFavorite;
List<String> arrlstID = new ArrayList<>();
String[] arrID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_card);
// Assign fields to variables
tv_org = findViewById(R.id.tv_org);
tv_name = findViewById(R.id.tv_name);
tv_email = findViewById(R.id.tv_email);
tv_phone = findViewById(R.id.tv_phone);
tv_website = findViewById(R.id.tv_website);
tv_servicetype = findViewById(R.id.tv_servicetype);
tv_servicesprovided = findViewById(R.id.tv_servicesprovided);
tv_address = findViewById(R.id.tv_address);
cbFavorite = findViewById(R.id.cbFavorite);
// Set variable for selectedOrg from DirectoryActivity
selectedOrg = Objects.requireNonNull(this.getIntent().getExtras()).getString("selectedOrg");
// Get Org data from DB using async
process = new FetchOrg();
process.setListener(new FetchOrg.FetchOrgTaskListener() {
#Override
public void onFetchOrgTaskFinished(String[] result) {
setTextView(result);
// onClick for Email
tv_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showEmailDialog();
}
});
// onClick for Call
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Get phone number from DB
// Replace any non-digit in phone number to make call
phoneNum = dbPhone.replaceAll("\\D", "");
// make call
goCall(phoneNum);
}
});
// onClick for Web
tv_website.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Fix URL logic
orgWeb = "http://" + dbWeb;
goWeb(orgWeb);
}
});
// onClick for Address
tv_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goMap();
}
});
// TODO add favorite functionality
// When checkbox status changes, change value of Favorite
cbFavorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
}
});
process.execute(selectedOrg);
/*
// if favorite = 1 then check box
if (Favorite.equals("1")) {
cbFavorite.setChecked(true);
} else {
cbFavorite.setChecked(false);
}
*/
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
// Method to assign text view items from async task
public void setTextView(String[] org_data) {
String name = org_data[1] + " " + org_data[2];
String address = org_data[8] + " " + org_data[9] + " " + org_data[10] + " " + org_data[11];
tv_org.setText(org_data[0]);
tv_name.setText(name);
tv_email.setText(org_data[3]);
tv_phone.setText(org_data[4]);
tv_website.setText(org_data[5]);
tv_servicetype.setText(org_data[6]);
tv_servicesprovided.setText(org_data[7]);
tv_address.setText(address);
}
public void showEmailDialog() {
// Get dialog_box_goals.xml view
LayoutInflater layoutInflater = LayoutInflater.from(BusinessCardActivity.this);
View promptView = layoutInflater.inflate(R.layout.dialog_box_send_email, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BusinessCardActivity.this);
alertDialogBuilder.setView(promptView);
final EditText etEmailMessage = (EditText) promptView.findViewById(R.id.etMailMessage);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// my code
/* WONT USE THIS UNTIL EMAILS ARE FINAL
USING MY EMAIL FOR TESTING PURPOSES
// Get email
niagaraDB.open();
c2 = niagaraDB.getEmailByID(passedID);
if (c2.moveToFirst())
{
public String emailTo = c2.getString(0);
}
niagaraDB.close();
*/
// This is for final code
// String to = "mailto:" + emailTo;
String to = "snownwakendirt#yahoo.com";
String subject = "Mail From Connect & Protect Niagara App";
String message = etEmailMessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(BusinessCardActivity.this,
"Message must contain something",
Toast.LENGTH_LONG).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
// email.putExtra(Intent.EXTRA_CC, new String[]{ to});
// email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
// need this to prompt email client only
email.setType("message/rfc822");
try {
startActivity(Intent.createChooser(email, "Choose an Email client :"));
finish();
Log.i("Email Sent...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(BusinessCardActivity.this,
"There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void goCall(final String phoneNum) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNum, null)));
}
public void goWeb(String orgWeb) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(orgWeb)));
}
public void goCloseBusinessCard(View v) {
finish();
startActivity(new Intent(this, DirectoryActivity.class));
}
public void goMap() {
/*
int locationAddressLatInt = Integer.parseInt(locationAddressLat);
int locationAddressLongInt = Integer.parseInt(locationAddressLong);
*/
// pass id to map view. only one item in array for ease of use in MapActivity
arrlstID.add(selectedOrg);
arrID = new String[arrlstID.size()];
arrlstID.toArray(arrID);
Bundle extras = new Bundle();
extras.putStringArray("arrID", arrID);
Intent Map = new Intent(BusinessCardActivity.this, MapActivity.class);
Map.putExtras(extras);
startActivity(Map);
}
// ASYNC TASK
static class FetchOrg extends AsyncTask<String, Void, String[]> {
private FetchOrgTaskListener listener;
#Override
protected String[] doInBackground(String... params) {
try {
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
String line = "";
URL url = new URL(orgbyname);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
line = br.readLine();
br.close();
is.close();
conn.disconnect();
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject JO = new JSONObject(line); // creates object from json response in data string
JSONObject Orgs = JO.getJSONObject("orgs"); // creates array for parsing of json data
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = Orgs.getString("org_name");
String FirstName = Orgs.getString("contact_first_name");
String LastName = Orgs.getString("contact_last_name");
String Email = Orgs.getString("contact_email");
String Phone = Orgs.getString("contact_phone");
String Website = Orgs.getString("org_website");
String ServiceType = Orgs.getString("org_type");
String ServicesProvided = Orgs.getString("org_services");
String Address = Orgs.getString("org_street_address");
String City = Orgs.getString("org_city");
String State = Orgs.getString("org_state");
String Zip = Orgs.getString("org_zip");
String Lat = Orgs.getString("latitude");
String Long = Orgs.getString("longitude");
// Add items to string array
String[] org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
return org_data;
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
if (listener != null) {
listener.onFetchOrgTaskFinished(result);
}
}
private void setListener(FetchOrgTaskListener listener) {
this.listener = listener;
}
public interface FetchOrgTaskListener {
void onFetchOrgTaskFinished(String[] result);
}
}
Activity lifecycle would go back from paused to resume state.
You need to provide the expected behaviour inside onResume something like below
public void onResume(){
super.onResume();
new XXXAsyncTask( new XXXAsyncListener(){
public void postTaskMethod(){
//do stuff here
}
}).execute();
}
I made a few changes in your onCreate()method of your BusinessCardActivity. I check for hasExtra instead--a little more flexibility. I got rid of the Listener and packed all onClick listener below. I felt it was a bit too complicated using the Listener approach (So you can remove this process.setListener(null); from the onDestroy()method). I also added a few Log.e(); so you can see what is going on in the logcat.
(BTW "TAG" would be:
private static final Strting TAG = BusinessCardActivity.class.getSimpleName();)
With "BusinessCardActivity.class.getSimpleName();" written out just in case you refactor sometime.
This is part of your BusinessCardActivity onCreate() method:
// Set variable for selectedOrg from DirectoryActivity
Intent intent = this.getIntent();
if(intent.hasExtra(selectedOrg)){
String selectedOrg = intent.getStringExtra("selectedOrg")
Log.e(TAG, "selectedOrg : " + selectedOrg);
FetchOrg process = new FetchOrg();
process.execute(selectedOrg);
}
else{
Log.e(TAG, "No Extras!")
//You might what to call finish() here
return;
}
//Move all your onClick Listeners below...
I don't think this is the best case to use a Listener so lets use the AsyncTask like this (I also removed the static):
class FetchOrg extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
try {
Log.e(TAG, "doInBackground ... Started");
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
String line = "";
URL url = new URL(orgbyname);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
line = br.readLine();
br.close();
is.close();
conn.disconnect();
Log.e(TAG, "Data Returned : " + line);
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject JO = new JSONObject(line); // creates object from json response in data string
JSONObject Orgs = JO.getJSONObject("orgs"); // creates array for parsing of json data
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = Orgs.getString("org_name");
String FirstName = Orgs.getString("contact_first_name");
String LastName = Orgs.getString("contact_last_name");
String Email = Orgs.getString("contact_email");
String Phone = Orgs.getString("contact_phone");
String Website = Orgs.getString("org_website");
String ServiceType = Orgs.getString("org_type");
String ServicesProvided = Orgs.getString("org_services");
String Address = Orgs.getString("org_street_address");
String City = Orgs.getString("org_city");
String State = Orgs.getString("org_state");
String Zip = Orgs.getString("org_zip");
String Lat = Orgs.getString("latitude");
String Long = Orgs.getString("longitude");
// Add items to string array
String[] org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
return org_data;
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
setTextView(result);
}
}
Also I would change your method goBusinessCard() a bit (and no need to be public):
private void goBusinessCard(String selectedOrg) {
//Java variables should written in lower case and Classes Capitalized
Intent businessCard = new Intent(this, BusinessCardActivity.class);
businessCard.putExtra("selectedOrg", selectedOrg);
startActivity(businessCard);
}
Please let me know if you have any issues! I typed this out in a standard Text Editor..so there might be a few typos.
Posting a new answer so I can add all the code for the BusinessCardActivity class.
I added some additional logging and changed getString() to optString() in order to be able to offer an alternative value. For example if the value or "key" is invalid or missing you would get an error.
public class BusinessCardActivity extends AppCompatActivity {
TextView tv_org, tv_name, tv_email, tv_phone, tv_website, tv_servicetype,
tv_servicesprovided, tv_address;
String Favorite, Latitude, Longitude, FavoriteChanged, dbPhone, phoneNum, dbWeb, orgWeb;
CheckBox cbFavorite;
List<String> arrlstID = new ArrayList<>();
String[] arrID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_card);
// Assign fields to variables
tv_org = findViewById(R.id.tv_org);
tv_name = findViewById(R.id.tv_name);
tv_email = findViewById(R.id.tv_email);
tv_phone = findViewById(R.id.tv_phone);
tv_website = findViewById(R.id.tv_website);
tv_servicetype = findViewById(R.id.tv_servicetype);
tv_servicesprovided = findViewById(R.id.tv_servicesprovided);
tv_address = findViewById(R.id.tv_address);
cbFavorite = findViewById(R.id.cbFavorite);
Intent intent = this.getIntent();
if(!intent.hasExtra("selectedOrg")){
Log.e(TAG, "No Extras!")
//You might what to call finish() here
return;
}
String selectedOrg = intent.getStringExtra("selectedOrg")
Log.e(TAG, "selectedOrg : " + selectedOrg);
FetchOrg process = new FetchOrg();
process.execute(selectedOrg);
// onClick for Email
tv_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showEmailDialog();
}
});
// onClick for Call
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Get phone number from DB
// Replace any non-digit in phone number to make call
phoneNum = dbPhone.replaceAll("\\D", "");
// make call
goCall(phoneNum);
}
});
// onClick for Web
tv_website.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Fix URL logic
orgWeb = "http://" + dbWeb;
goWeb(orgWeb);
}
});
// onClick for Address
tv_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goMap();
}
});
// TODO add favorite functionality
// When checkbox status changes, change value of Favorite
cbFavorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
/*
// if favorite = 1 then check box
if (Favorite.equals("1")) {
cbFavorite.setChecked(true);
} else {
cbFavorite.setChecked(false);
}
*/
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
// Method to assign text view items from async task
public void setTextView(String[] org_data) {
String name = org_data[1] + " " + org_data[2];
String address = org_data[8] + " " + org_data[9] + " " + org_data[10] + " " + org_data[11];
tv_org.setText(org_data[0]);
tv_name.setText(name);
tv_email.setText(org_data[3]);
tv_phone.setText(org_data[4]);
tv_website.setText(org_data[5]);
tv_servicetype.setText(org_data[6]);
tv_servicesprovided.setText(org_data[7]);
tv_address.setText(address);
}
public void showEmailDialog() {
// Get dialog_box_goals.xml view
LayoutInflater layoutInflater = LayoutInflater.from(BusinessCardActivity.this);
View promptView = layoutInflater.inflate(R.layout.dialog_box_send_email, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BusinessCardActivity.this);
alertDialogBuilder.setView(promptView);
final EditText etEmailMessage = (EditText) promptView.findViewById(R.id.etMailMessage);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// my code
/* WONT USE THIS UNTIL EMAILS ARE FINAL
USING MY EMAIL FOR TESTING PURPOSES
// Get email
niagaraDB.open();
c2 = niagaraDB.getEmailByID(passedID);
if (c2.moveToFirst())
{
public String emailTo = c2.getString(0);
}
niagaraDB.close();
*/
// This is for final code
// String to = "mailto:" + emailTo;
String to = "snownwakendirt#yahoo.com";
String subject = "Mail From Connect & Protect Niagara App";
String message = etEmailMessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(BusinessCardActivity.this,
"Message must contain something",
Toast.LENGTH_LONG).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
// email.putExtra(Intent.EXTRA_CC, new String[]{ to});
// email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
// need this to prompt email client only
email.setType("message/rfc822");
try {
startActivity(Intent.createChooser(email, "Choose an Email client :"));
finish();
Log.i("Email Sent...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(BusinessCardActivity.this,
"There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void goCall(final String phoneNum) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNum, null)));
}
public void goWeb(String orgWeb) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(orgWeb)));
}
public void goCloseBusinessCard(View v) {
finish();
startActivity(new Intent(this, DirectoryActivity.class));
}
public void goMap() {
/*
int locationAddressLatInt = Integer.parseInt(locationAddressLat);
int locationAddressLongInt = Integer.parseInt(locationAddressLong);
*/
// pass id to map view. only one item in array for ease of use in MapActivity
arrlstID.add(selectedOrg);
arrID = new String[arrlstID.size()];
arrlstID.toArray(arrID);
Bundle extras = new Bundle();
extras.putStringArray("arrID", arrID);
Intent Map = new Intent(BusinessCardActivity.this, MapActivity.class);
Map.putExtras(extras);
startActivity(Map);
}
// ASYNC TASK
class FetchOrg extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection con = null;
String[] org_data = null;
try {
Log.e(TAG, "FetchOrg doInBackground started");
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
URL url = new URL(orgbyname);
con = (HttpURLConnection) url.openConnection();
Log.e(TAG, "FetchOrg doInBackground Connected!");
//Check the response code of the server -
Integer replyCode = con.getResponseCode();
logMess += " Reply Code: " + replyCode.toString();
responseStream = new BufferedInputStream(con.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
logMess += " elapsed Time : " + elapsedTime + " ms";
Log.e(TAG, "FetchOrg logMess: --- " + logMess);
String line = "";
StringBuilder stringBuilder = new StringBuilder();
//Make sure you get everything!
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
//this will close underlying streams
responseStreamReader.close();
String data = stringBuilder.toString();
Log.e(TAG, "FetchOrg Data: --- " + data);
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject obj = new JSONObject(data); // creates object from json response in data string
JSONObject orgs = obj.getJSONObject("orgs"); // creates array for parsing of json data
String nA = "not available";
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = orgs.optString("org_name", nA);
String FirstName = orgs.optString("contact_first_name", nA);
String LastName = orgs.optString("contact_last_name", nA);
String Email = orgs.optString("contact_email", nA);
String Phone = orgs.optString("contact_phone", nA);
String Website = orgs.optString("org_website", nA);
String ServiceType = orgs.optString("org_type", nA);
String ServicesProvided = orgs.optString("org_services", nA);
String Address = orgs.optString("org_street_address", nA);
String City = orgs.optString("org_city", nA);
String State = orgs.optString("org_state", nA);
String Zip = orgs.optString("org_zip", nA);
String Lat = orgs.optString("latitude", nA);
String Long = orgs.optString("longitude", nA);
// Add items to string array
org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
} catch (Exception ex) {
Log.e(TAG, "FetchOrg doInBackground: " + ex.getMessage());
}
finally{
//just in case you get an error above
if(con != null){
con.disconnect();
}
}
return org_data;
}
#Override
protected void onPostExecute(String[] result) {
if(result != null){
setTextView(result);
}
else{
Log.e(TAG, "FetchOrg onPostExecute: result is null");
}
}
}
Be aware that I did not clean up things like maintaining minimal scope: For example :public void showEmailDialog() and public void goMap() which do not need to be public methods! Any method that does not need to be accessed outside the class (and that is rare!) should not be made public.
You have also defined many class variables at the beginning of the class like "Favorite, Latitude, Longitude, FavoriteChanged" do they need to have class wide scope?? And they are variables! So in java naming convention, variables and methods are written in lower case, while classes are capitalized--this helps reading code easier (for the SO community!)
When working with Indent extras often mistakes are made when entering the "key" like "selectedOrg". Therefore it is some times an advantage to create a global class to help keep things straight. Example public class GlobalExtras and just keep public static final String SELECTED_ORG = "selectedOrg"; Then just use intent.getString(SELECTED_ORG);
Another thing: I am not a big fan of String[] as you have used to store your "org" strings. They can be tricky with size and indexes. You might want to consider using another object.
I do not have access to your API and your data, so I was only able to make requests on my server trying to duplicate your user scenario, but I was unable to reproduce your issue. I hope this helps, let me know what the logcat spits out!
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);
I'm writing an Android application which will occasionally need to download a json string of around 1MB and containing around 1000 elements, and parse each of these into an SQLite database, which I use to populate a ListActivity.
Even though the downloading and parsing isn't something that needs to be done on every interaction with the app (only on first run or when the user chooses to refresh the data), I'm still concerned that the parsing part is taking too long, at around two to three minutes - it seems like an eternity in phone app terms!
I am using this code... :-
public class CustomerAsyncTask extends AsyncTask<String, Integer, String> {
private Context context;
private String url_string;
private String usedMethod;
private String identifier;
List<NameValuePair> parameter;
private boolean runInBackground;
AsynTaskListener listener;
private Bitmap bm = null;
public ProgressDialog pDialog;
public String entityUtil;
int index = 0;
public static int retry = 0;
private String jsonString = "";
private String DialogString = "";
// use for AsyncTask web services-----------------
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground, String DialogString,
List<NameValuePair> parameter, AsynTaskListener callack) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.DialogString = DialogString;
}
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground,
List<NameValuePair> parameter, AsynTaskListener callack, Bitmap bm) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.bm = bm;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (runInBackground)
initProgressDialog(DialogString);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000; // mili second
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
HttpResponse response = null;
if (usedMethod.equals(GlobalConst.POST)) {
HttpPost httppost = new HttpPost(this.url_string);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
// Customer Login MObile
if (identifier.equals("Customer_Login")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_mob",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
// Customer Verify Code
} else if (identifier.equals("Customer_mob_verify")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_verify",
params[0]));
parameter.add(new BasicNameValuePair("cus_mobile",
params[1]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
} else if (identifier.equals("Dashboard")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_id",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
}
response = (HttpResponse) httpClient.execute(httppost);
} else if (usedMethod.equals(GlobalConst.GET)) {
HttpGet httpput = new HttpGet(this.url_string);
httpput.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = (HttpResponse) httpClient.execute(httpput);
}
// Buffer Reader------------------------
InputStream inputStream = null;
String result = null;
try {
HttpEntity entity1 = response.getEntity();
inputStream = entity1.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
jsonString = result;
} catch (ClientProtocolException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (IOException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (Exception e1) {
e1.printStackTrace();
return AsyncResultConst.EXCEPTION;
} finally {
httpClient.getConnectionManager().shutdown();
}
return AsyncResultConst.SUCCESS;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (runInBackground)
pDialog.dismiss();
if (result.equals(AsyncResultConst.SUCCESS)) {
listener.onRecieveResult(identifier, jsonString);
} else if (result.equals(AsyncResultConst.PARSINGERROR)) {
// showAlertMessage(context, "Error", "Parsing Error", null);
listener.onRecieveException(identifier, result);
} else {
if (retry < 0) {
retry++;
new CustomerAsyncTask(context, url_string, usedMethod,
identifier, runInBackground, DialogString, parameter,
listener).execute("");
} else {
// showAlertMessage(context, "Error", "Connection Error", null);
listener.onRecieveException(identifier, result);
}
}
super.onPostExecute(result);
}
private void initProgressDialog(String loadingText) {
pDialog = new ProgressDialog(this.context);
pDialog.setMessage(loadingText);
pDialog.setCancelable(false);
pDialog.show();
}
}
Don't use Async-task in such case, use native java thread here.
new Thread(new Runnable() {
public void run() {
// Do your work .....
}
}).start();
When need to update UI. Yes! Android won't allow you to do that. so... solution is: USE Handler for that :)
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// Do Update your UI
}
});
Use AsyncTask for:
Simple network operations which do not require downloading a lot of
data Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
You could use Google's GSON as well.
Try to use Jackson Library to manage your JSON. It is really efficient. You can find it here : http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs
I am using it for a 400KB file is less than 1 second.
If you want a tuto this one looks good http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
This is how is read JSON into my listview in my app. The result is processed to my app in an average of 3 seconds on Wi-Fi and 5 seconds on 3G:
public class CoreTeamFragment extends ListFragment {
ArrayList> membersList;
private String url_all_leaders = //URL goes here
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_TEAM = "CoreTeam";
private static final String pid = "pid";
private static final String COL_NAME = "CoreTeam_Name";
private static final String COL_DESC = "CoreTeam_Desc";
private static final String COL_PIC = "CoreTeam_Picture";
JSONArray CoreTeam = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public CoreTeamFragment() {
}
public void onStart() {
super.onStart();
membersList = new ArrayList<HashMap<String, String>>();
new LoadAllMembers().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.leader_id))
.getText().toString();
Intent intent = new Intent(view.getContext(),
CoreTeamDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_coreteam,
container, false);
return rootView;
}
class LoadAllMembers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_leaders,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
CoreTeam = json.getJSONArray(TABLE_TEAM);
// looping through All Contacts
for (int i = 0; i < CoreTeam.length(); i++) {
JSONObject ct = CoreTeam.getJSONObject(i);
// Storing each json item in variable
String id = ct.getString(pid);
String name = ct.getString(COL_NAME);
String desc = ct.getString(COL_DESC);
String pic = ct.getString(COL_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_PIC, pic);
// adding HashList to ArrayList
membersList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(),
membersList,
R.layout.coreteam_item,
new String[] { pid, COL_NAME, COL_DESC, COL_PIC },
new int[] { R.id.leader_id, R.id.leaderName,
R.id.photo });
setListAdapter(adapter);
}
});
}
}
}
Use Volley or Retrofit lib.
Those lib are increasing the speed.
Volley:
JsonObjectRequest channels = new JsonObjectRequest(Method.POST,
Constants.getaccountstatement + Constants.key, statement_object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
I am parsing JSON data to database,that data shows in my lisview.But in the first time it get data from my JSON and stores in db,its not upgrading if i add anything in my website,the json also will increase but its not reflect in db,the database part also not upgrading.Just its simply the display the first fetched data only.
Ginfydbadapter.java
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "test";
private static final String DATABASE_TABLE_PROJ = "projects";
private static final int DATABASE_VERSION = 3;
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 = "GinfyDbAdapter";
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
private final Context mCtx;
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 , "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String DATABASE_CREATE_PROJ = "CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " integer primary key, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
db.execSQL(DATABASE_CREATE_PROJ);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_TABLE_PROJ);
onCreate(db);
}
}
public void saveCategoryRecord(Category category) {
ContentValues values = new ContentValues();
values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
values.put(CATEGORY_COLUMN_CONTENT, category.getContent());
values.put(CATEGORY_COLUMN_COUNT, category.getCount());
// Inserting Row
mDb.insert(DATABASE_TABLE_PROJ, null, values);
mDb.close(); // Closing database connection
}
public Cursor fetchAllProjects() {
// TODO Auto-generated method stub
return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
}
public GinfyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public GinfyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
}
this is my MainActivity.java
here only i mention my url of json also
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
fillData(projectsCursor);
Log.i("filling", "...");
}
else
{
new GetDataAsyncTask().execute();
}
//lv1 =(ListView)findViewById(R.id.list);
//lv =(ListView)findViewById(R.id.list);
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);
} */
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
fillData(projectsCursor);
}
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
}
public void getData() {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("https://ancient-caverns-4909.herokuapp.com/api/v1/posts.json");
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i("................",_response);
httpclient.getConnectionManager().shutdown();
JSONObject jsonObject = new JSONObject(_response);
JSONArray contacts = jsonObject.getJSONArray("post");//(url);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
String content = c.getString("content");
String count = c.getString("count");
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData(Cursor projectsCursor) {
//mDbHelper.open();
if(projectsCursor!=null)
{
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
}else
{
Log.i("...........","null");
}
}
My Database is not upgrading due to JSON change,it will take only one time of json data only.
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