retain sqlite data records during screen orientation change - android

in my app im using gridview
when in portrait mode it shows one column.
in landscape mode new layout defined to show 2 column.
this is how the app works..
when app is launched, progress dialog is called to load website name from sqlite database and async is used to load website from sqlite db. the progress dialog is dismissed after the gridview is inflated.
now after loading the website name into gridview the screen orientation changes, it restarts the progress dialog.
i know that on screen orientation change the ondestroy() and then oncreate() are called.
this is my app's src code.
public class RSSReaderActivity extends Activity {
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> rssFeedList;
RSSParser rssParser = new RSSParser();
RSSFeed rssFeed;
Button add_rss;
// array to trace sqlite ids
String[] sqliteIds;
public static String TAG_ID = "id";
public static String TAG_TITLE = "title";
public static String TAG_LINK = "link";
GridView gridview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.site_list);
add_rss = (Button) findViewById(R.id.add_rss);
gridview = (GridView) findViewById(R.id.gridview);
rssFeedList = new ArrayList<HashMap<String, String>>();
new loadStoreSites().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
...
...
);
add_rss.setOnClickListener(new View.OnClickListener() {
...
...
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class loadStoreSites extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
...
...
}
#Override
protected String doInBackground(String... args) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
RSSDatabaseHandler rssDb = new RSSDatabaseHandler(getApplicationContext());
// listing all websites from SQLite
List<WebSite> siteList = rssDb.getAllSites();
sqliteIds = new String[siteList.size()];
// loop through each website
for (int i = 0; i < siteList.size(); i++) {
WebSite s = siteList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, s.getId().toString());
map.put(TAG_TITLE, s.getTitle());
map.put(TAG_LINK, s.getLink());
// adding HashList to ArrayList
rssFeedList.add(map);
// add sqlite id to array
// used when deleting a website from sqlite
sqliteIds[i] = s.getId().toString();
}
gridview.setAdapter(new SimpleAdapter(RSSReaderActivity.this,rssFeedList, R.layout.site_list_row,new String[] { TAG_ID, TAG_TITLE, TAG_LINK },new int[] { R.id.sqlite_id, R.id.title, R.id.link }));
registerForContextMenu(gridview);
}
});
return null;
}
protected void onPostExecute(String args) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
}
}
SO how do we use onsavedinstance() over here.. please can anyone guide me.

add this in menifest file
android:configChanges="keyboardHidden|orientation|screenSize"

Related

How to download entire S3 bucket automatically

I am able to successfully download all files from aws s3 bucket, so when I click on the particular list item the list item gets download. But, I want all s3 bucket item automatically download when activity is launched.
/**
* DownloadSelectionActivity displays a list of files in the bucket. Users can
* select a file to download.
*/
public class DownloadSelectionActivity extends ListActivity {
// The S3 client used for getting the list of objects in the bucket
private AmazonS3Client s3;
// An adapter to show the objects
private SimpleAdapter simpleAdapter;
private ArrayList<HashMap<String, Object>> transferRecordMaps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_selection);
initData();
initUI();
}
#Override
protected void onResume() {
super.onResume();
// Refresh the file list.
new GetFileListTask().execute();
}
private void initData() {
// Gets the default S3 client.
s3 = Util.getS3Client(DownloadSelectionActivity.this);
transferRecordMaps = new ArrayList<HashMap<String, Object>>();
}
private void initUI() {
simpleAdapter = new SimpleAdapter(this, transferRecordMaps,
R.layout.bucket_item, new String[] {
"key"
},
new int[] {
R.id.key
});
simpleAdapter.setViewBinder(new ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
switch (view.getId()) {
case R.id.key:
TextView fileName = (TextView) view;
fileName.setText((String) data);
return true;
}
return false;
}
});
// When an item is selected, finish the activity and pass back the S3
// key associated with the object selected
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, int pos, long id) {
Intent intent = new Intent();
intent.putExtra("key", (String) transferRecordMaps.get(pos).get("key"));
setResult(RESULT_OK, intent);
finish();
}
});
}
/**
* This async task queries S3 for all files in the given bucket so that they
* can be displayed on the screen
*/
private class GetFileListTask extends AsyncTask<Void, Void, Void> {
// The list of objects we find in the S3 bucket
private List<S3ObjectSummary> s3ObjList;
// A dialog to let the user know we are retrieving the files
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(DownloadSelectionActivity.this,
getString(R.string.refreshing),
getString(R.string.please_wait));
}
#Override
protected Void doInBackground(Void... inputs) {
// Queries files in the bucket from S3.
s3ObjList = s3.listObjects(Constants.BUCKET_NAME).getObjectSummaries();
transferRecordMaps.clear();
for (S3ObjectSummary summary : s3ObjList) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("key", summary.getKey());
transferRecordMaps.add(map);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
simpleAdapter.notifyDataSetChanged();
}
}
}
You already have the list of objects in the bucket, you could just iterate through the list and download each one when the list operation has completed. It might be easier to handle the transfers (allowing pause/resume, checking status, ect...) using the Transfer Utility, which is a high level utility on top of the standard S3 Client.
A guide for the Transfer Utility can be found here (http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/s3transferutility.html)

Start app and load data with viewpager AsyncTask

I'm using AsyncTask with Viewpager and so far everything is working properly. When I run my application everything works fine and displays the data by sliding from one column to another. But when you start the app the data in that first column does not appear. I have tried in the onCreate insert the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = "1";
layout = R.id.lista;
empty = R.id.empty;
DownloadJSON newTask = new DownloadJSON(url,layout,empty);
newTask.execute();
...
It does not work. The app is closed. How do I can load this data when the app starts?
My code:
public class MainActivity extends Activity {
ViewPager vp;
private vpAdapter myAdapter;
ListViewAdapter adapter;
ListView listview;
String url;
int layout;
int empty;
ArrayList<HashMap<String, String>> arraylist;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
vp = (ViewPager) findViewById(R.id.pager);
myAdapter = new vpAdapter();
vp.setAdapter(myAdapter);
vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
//CASE 0 = FIRST PAGE
switch (i) {
case 0:
url = "1";
layout = R.id.lista;
empty = R.id.empty;
DownloadJSON newTask = new DownloadJSON(url,layout,empty);
newTask.execute();
break;
default:
break;
case 1:
url = "2";
layout = R.id.lista2;
empty = R.id.empty2;
DownloadJSON newTask2 = new DownloadJSON(url,layout,empty);
newTask2.execute();
break;
case 2:
url = "3";
layout = R.id.lista3;
empty = R.id.empty3;
DownloadJSON newTask3 = new DownloadJSON(url,layout,empty);
newTask3.execute();
break;
case 3:
url = "4";
layout = R.id.lista4;
empty = R.id.empty4;
DownloadJSON newTask4 = new DownloadJSON(url,layout,empty);
newTask4.execute();
break;
case 4:
url = "5";
layout = R.id.lista5;
empty = R.id.empty5;
DownloadJSON newTask5 = new DownloadJSON(url,layout,empty);
newTask5.execute();
break;
case 5:
url = "6";
layout = R.id.lista6;
empty = R.id.empty6;
DownloadJSON newTask6 = new DownloadJSON(url,layout,empty);
newTask6.execute();
break;
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String givemeurl;
int givemelayout;
int givemeempty;
public DownloadJSON(String url, int layout, int empty) {
this.givemeurl = url;
this.givemelayout = layout;
this.givemeempty = empty;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
ListView listview = (ListView) findViewById(layout);
if(listview.getCount()==0){
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Cargando...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}else{
cancel(true);
Log.e("CANCELADO","CANCELADO");
}
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("URL");
if(jsonobject != null){
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("productos");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("imagen", jsonobject.getString("imagen"));
map.put("nombre", jsonobject.getString("nombre"));
map.put("total", jsonobject.getString("total"));
map.put("empresa", jsonobject.getString("empresa"));
map.put("unidades", jsonobject.getString("unidades"));
map.put("precionuevo", jsonobject.getString("precionuevo")+" €");
map.put("precioantiguo", jsonobject.getString("precioantiguo")+" €");
map.put("descripcion", jsonobject.getString("descripcion"));
map.put("direccion", jsonobject.getString("direccion"));
map.put("telefono", jsonobject.getString("telefono"));
map.put("latitud", jsonobject.getString("latitud"));
map.put("longitud", jsonobject.getString("longitud"));
map.put("codeqr", jsonobject.getString("codeqr"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
//e.printStackTrace();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
}else{
//Log.e("Response","No data");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(givemelayout);
listview.setEmptyView(findViewById(givemeempty));
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
//Log.e("",""+listview.getCount());
}
}
For a better performance, You should download all of the data, before showing the view pager. Currently you're downloading the same data again and again, whenever the user swipes the view pager. And not seeing any data on the first page initially is an expected result, because you download data only in onPageChangeListener. My suggestion is:
Create a dummy activity and make it launcher. It will be for downloading data. You can also do some configurations initially.
In onCreate method of that activity, download all of the necessary data your app needs using an AsyncTask.
In onPostExecute method of that AsyncTask start your main intent.
And finish the dummy activity to remove it from the stack so that when the user clicks back, your dummy activity won't be seen.
You can either pass the data you got to your main intent with:
Setting them as extras to your intent, using putExtra
Or you can store them in Application class, this is the only class that won't be destroyed by Android OS, so it's safe to store data there.

How to reload SimpleAdapter on onActivityResult

I'm trying to achieve the following:
Screen 1 shows list data from server
User presses "+" button on top right to add a new item
Screen 2 shows with text field
User enters data and clicks save
Now I want to go back to Screen 1 and refresh the list from server so that the newly added item shows up
I'm having problems achieving point 5 above. This is what I have so far:
I have an AyncTask like following:
public class MyActivity extends SherlockListActivity {
ArrayList<HashMap<String, String>> taskList;
//this grabs data from server and loads it in ArrayList
protected void loadList() {
taskList = new ArrayList<HashMap<String, String>>();
final RestAdapter restAdapter = new RestAdapter.Builder().setServer("http://10.0.2.2:8080").build();
final TaskService apiManager = restAdapter.create(TaskService.class);
final Task task = apiManager.getTask("someuser", task_id);
for (Item item : task.getItems()) {
String t_id = t.getId()+"";
String name = t.getName();
HashMap<String, String> map = new HashMap<String, String>();
map.put("act_id", act_id);
map.put("t_id", t_id);
map.put("t_name", name);
taskList.add(map);
}
}
public void onCreate (Bundle b) {
new LoadItems().execute();
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Create")) {
Intent create = new Intent(getApplicationContext(), CreateTask.class);
startActivityForResult(create, 1);
return true;
}
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
//item got added now load again from server
if (resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
new UpdateItems.execute();
adapter.notifyDataSetChanged();
}
}
}
class UpdateItems extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
loadList();
return null;
}
}
class LoadItems extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
loadList();
}
protected void onPostExecute(String file_url) {
adapter = new SimpleAdapter(
MyActivity.class, taskList,
R.layout.list_item_rec, new String[] { "act_id", "t_id", "t_name"}, new int[] {
R.id.act_id, R.id.t_id,R.id.t_name });
setListAdapter(adapter);
}
}
Question
How can I reload the data from the server in onActivityResult. Based on above, what I'm doing is creating another AynchTask only for loading the data again and then calling notifyDataSetChanged(). This doesn't seem to be working.
Is my process wrong? Is there a better way to do this? I am stumped....
You have to reload the data in UpdateItems onPostExecute() method..because you are loading data in AsynchTask it loads data in another thread and updating the ListView but the list is not loaded at that time..so change your AsynchTask like this..
class UpdateItems extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
loadList();
return null;
}
#Override
protected void onPostExecute(String result) {
adapter.notifyDataSetChanged();
}
}
and remove this line adapter.notifyDataSetChanged() in onActivityResult()

Passing data between activities from listview to another activity

I am trying to pass the data from this main activity to another activity
I am successful in sending data between activities .... Like the data from Edit-text to next activity through putExtra and GetExtra methods and passing as intents
But i am facing challenge in this particular task where it involves
sending data from listview to an ordinary activity
data is populated in the list view from JSON so when on click of a
row how can i send the data from that row to a new activity
Any Ideas,
ativity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7002/";
List<Item> yourData = new ArrayList<Item>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiating ProgressDialog with onCreate method
progressDialog=new ProgressDialog(MainActivity.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(MainActivity.this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(MainActivity.this,CopperChimneyDesc.class);
startActivity(myIntent);
}else if(position == 1)
{
//Intent myIntent = new Intent(MainActivity.this,AroyDesc.class);
//startActivity(myIntent);
}
}
});
}
}
}
item.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
Thanks,
Ok so you would do
String item = yourData.get(position).getName();
Then you can add the string to intent using:
intent.putExtra("restaurent", item);
On the other end if its textview you would do
textView.setText(getIntent().getExtras().getString("restaurent"));
intent.putExtra("City Name", String.valueOf(lvCity.getSelectedItem()));
try this one to cast.
you can parcle data and send it to other activity with putxtera method.please see How to store values in onSaveInstanceState() and retrive?
Since you have the index of the item in the listview the user has clicked you can get the item value from the adapter:
String value = (String)customAdapter.getItem(position);
Intent myIntent = new Intent(MainActivity.this,CopperChimneyDesc.class);
intent.putExtra("restaurant_name", value);
startActivity(myIntent);
You can save the data in sharedPreferences and can access it from other activity. Just an idea :)

What is wrong with progress dialog in AsyncTask

Am using Async Task in my application to get response from web service using restful web service. My code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_page);
_mContext = this;
new JSONParserTask().execute();
}
asynctask class
private class JSONParserTask extends AsyncTask<Void, Void, ListAdapter >{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// dialog = new ProgressDialog(_mContext);
// dialog.setMessage("Loading...");
// dialog.show();
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0) {
ListAdapter adapter = null;
itemsList = new ArrayList<HashMap<String, String>>();
jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(Constants.JsonURL);
if(json == null){
Log.v(TAG, "----------- null");
return null;
}
try {
// Getting Array of Items
items = json.getJSONArray(TAG_ITEMS);
// looping through All items
for(int i = 0; i < items.length(); i++) {
JSONObject itemsObj = items.getJSONObject(i);
JSONObject products = null;
products = itemsObj.getJSONObject(TAG_PRODUCT);
Log.d(TAG,"product array "+products.toString());
JSONArray images = products.getJSONArray(TAG_IMAGES);
JSONObject imagesObj = images.getJSONObject(0);
Log.d(TAG, "......."+ imagesObj.getString(TAG_LINK));
String imageUrl = imagesObj.getString(TAG_LINK);
// Storing each json item in variable
String kind = itemsObj.getString(TAG_KIND);
String id = itemsObj.getString(TAG_KID);
String selfLink = itemsObj.getString(TAG_SELFLINK);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_KIND, kind);
map.put(TAG_KID, id);
map.put(TAG_SELFLINK, selfLink);
// adding HashList to ArrayList
itemsList.add(map);
}
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
} catch(JSONException e){
e.printStackTrace();
}
return adapter;
}
#Override
protected void onPostExecute(ListAdapter adapter) {
lv.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// some action
}
});
//dialog.dismiss();
}
}
with this code every thing working fine without using progress dialog. If u found, the code related to progress dialog is commented in above class.
If i uncomment progress dialog code, am not getting any response from server. I have tried with debugging also but never get any idea to remove this error.
Can some one tell what wrong am doing here.
ok the reason for that is you are updating you are adapter in your doInBackground() method
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
This code is related to the MAIN THREAD and shouldn't be called here in the background thread, remove it from here, and add it to the onPostExecute() , just pass an array list from the Background thread and do other UI related stuff in the onPostExecute()
Try this
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(mProgressDialog!=null){
mProgressDialog.dismiss();
}
}
Try this one, rather
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0){
//do your stuff here
}
#Override
protected void onPostExecute(Void result) {
if(mProgressDialog!=null && mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
Try this
#Override
protected void onPreExecute() {
pd=new ProgressDialog(m_context);
pd.setTitle("Authenticating");
pd.show();
}
#Override
protected Void doInBackground(Void... args) {
//your stuff
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
}

Categories

Resources