I am new in android,I have one application,in my application i am getting user's profile data,here in my profile data i am getting user's state and city which user had previously set,like right now user set following state and city,and i am able to display that state and city in my spinner
{
"user_city": "Kolkata",
"user_state": "West Bengal",
}
Now issue is if user want to change state like from WestBengal to Karnataka,then i need to display all state and make user to change,so for that i have other separate webservice for load all state and i want to display that all state in same that spinner,but right now issue is i need to click two times then only it is showing all states
this is the response
[{"user_status":"1","state_id":"1","state":"Karnataka"},{"user_status":"1","state_id":"2","state":"Tamilnadu"},{"user_status":"1","state_id":"3","state":"Maharastra"},{"user_status":"1","state_id":"4","state":"Andhra Pradesh"},{"user_status":"1","state_id":"5","state":"West Bengal"},{"user_status":"1","state_id":"6","state":"Delhi"},{"user_status":"1","state_id":"8","state":"Andaman & Nicobar Islands"},{"user_status":"1","state_id":"9","state":"Arunachal Pradesh"},{"user_status":"1","state_id":"10","state":"Bihar"},{"user_status":"1","state_id":"11","state":"Chattisgarh"},{"user_status":"1","state_id":"12","state":"Dadra & Nagar Haveli"},{"user_status":"1","state_id":"13","state":"Daman & Diu"},{"user_status":"1","state_id":"14","state":"Goa"},{"user_status":"1","state_id":"15","state":"Gujarat"},{"user_status":"1","state_id":"16","state":"Haryana"},{"user_status":"1","state_id":"17","state":"Himachal Pradesh"},{"user_status":"1","state_id":"18","state":"Jharkhand"},{"user_status":"1","state_id":"19","state":"Kerala"},{"user_status":"1","state_id":"20","state":"Lakshadweep"},{"user_status":"1","state_id":"21","state":"Madhya pradesh"},{"user_status":"1","state_id":"22","state":"Pondichery"},{"user_status":"1","state_id":"23","state":"Punjab"},{"user_status":"1","state_id":"24","state":"Rajasthan"},{"user_status":"1","state_id":"25","state":"Sikkim"},{"user_status":"1","state_id":"26","state":"Telangana"},{"user_status":"1","state_id":"27","state":"Tripura"},{"user_status":"1","state_id":"28","state":"Uttaranchal"},{"user_status":"1","state_id":"29","state":"Uttar Pradesh"},{"user_status":"1","state_id":"31","state":"Nagaland"},{"user_status":"1","state_id":"32","state":"Mizoram"},{"user_status":"1","state_id":"33","state":"Meghalaya"},{"user_status":"1","state_id":"34","state":"Manipur"},{"user_status":"1","state_id":"35","state":"Assam"},{"user_status":"1","state_id":"36","state":"Chandigarh"},{"user_status":"1","state_id":"37","state":"Orissa"},{"user_status":"1","state_id":"38","state":"Others"}]
Loading profile
class LoadAllProdetails extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
private JSONObject jsonObjsss;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(GET_PRO_DETAILS, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObjsss = new JSONObject(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
profilessstates=new ArrayList<HashMap<String,String>>();
profilecitis=new ArrayList<HashMap<String,String>>();
if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("0"))
{
final String msgs=jsonObjsss.getString("message");
System.out.println("Messagessss"+msgs);
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getActivity(), msgs, Toast.LENGTH_LONG).show();
}
});
}
else if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("1")) {
HashMap<String, String> mapzz = new HashMap<String, String>();
usersstatus = jsonObjsss.getString(GET_PRO_USERSTATUS);
usersfname = jsonObjsss.getString(GET_PRO_FIRSTNAME);
usersmails = jsonObjsss.getString(GET_PRO_EMAILS);
usersmob = jsonObjsss.getString(GET_PRO_MOBILE);
usersdobs = jsonObjsss.getString(GET_PRO_DATES);
usersaddresss = jsonObjsss.getString(GET_PRO_ADDRESS);
userszipss = jsonObjsss.getString(GET_PRO_ZIP);
userstates=jsonObjsss.getString(GET_PRO_STATE);
usercitys=jsonObjsss.getString(GET_PRO_CITY);
mapzz.put(GET_PRO_STATE, jsonObjsss.getString(GET_PRO_STATE));
mapzz.put(GET_PRO_CITY, jsonObjsss.getString(GET_PRO_CITY));
profilessstates.add(mapzz);
profilecitis.add(mapzz);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return profilessstates;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
updtfname.setText(usersfname);
updtmail.setText(usersmails);
updtmob.setText(usersmob);
updtaddress.setText(usersaddresss);
updtpin.setText(userszipss);
datestext.setText(usersdobs);
arrprostates = new String[profilessstates.size()];
for (int index = 0; index < profilessstates.size(); index++) {
HashMap<String, String> map = profilessstates.get(index);
arrprostates[index] = map.get(GET_PRO_STATE);
}
adapterprostates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprostates);
statespinner.setAdapter(adapterprostates);
arrprocities = new String[profilecitis.size()];
for (int index = 0; index < profilecitis.size(); index++) {
HashMap<String, String> map = profilecitis.get(index);
arrprocities[index] = map.get(GET_PRO_CITY);
}
adapterprocities = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprocities);
cityspinner.setAdapter(adapterprocities);
To load all states
class LoadStatess extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(USER_STATUSS, c.getString(USER_STATUSS));
map.put(PRESET_TITLES, c.getString(PRESET_TITLES));
statedata.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
// pDialog.dismiss();
arrallstates = new String[statedata.size()];
for (int index = 0; index < statedata.size(); index++) {
HashMap<String, String> map = statedata.get(index);
arrallstates[index] = map.get(PRESET_TITLES);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adapterallstates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
statespinner.setPrompt("Select State");
statespinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spitems = statespinner.getSelectedItem().toString();
System.out.println("PresetEVent selected" + spitems);
new Logincity().execute();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
first screen by default get
then i click to load state it shows
then again i click the only it shows
Put these lines in OnCreate method of your activity.
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, new ArrayList<String>());
statespinner.setAdapter(adapterallstates);
And delete these lines from onPostExecute:
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
And add these lines in for loop of onPostExecute.
adapterallstates.add(map.get(PRESET_TITLES));
adapterprostates.notifyDataSetChanged();
Do this it will work for you.
other one is to,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoadListView();
}
private void LoadListView() {
try {
statespinner.setAdapter(adapterprostates);
} catch (Exception e) {
e.printStacktrace();
}
}
I have an API with a pagination scheme, like that:
-meta: {
-pagination: {
total: 100
count: 20
per_page: 20
current_page: 1
total_pages: 5
-links: {
next: "http://dev.app/api/posts?page=2"
}
}
}
I'm trying to find a way to implement that on my android app using volley and infinite scroll, the app has to read the json pagination from the API and scroll down to 20 items and than autoload to the next page, the problem is that when I get to "page=2" and I hit LoadMore button again it still getting the page 2 and not page 3, I mean, the current page is always 1, I don't know why this is happening, what I tried to do is:
public class MainActivity extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
JSONObject pagination = null;
JSONObject link = null;
private String url_posts = "http://dev.app/api/posts";
//Flag for current page
private String nPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please Check Your Internet Connection");
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
new LoadRestaurants().execute();
Button btnLoadMore = new Button(MainActivity.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
url_posts = nPage;
new LoadRestaurants().execute();
}
});
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(url_posts, "GET", params);
try {
restaurants = json.getJSONArray("data");
JSONObject meta = json.getJSONObject("meta");
pagination = meta.getJSONObject("pagination");
link = pagination.getJSONObject("links");
nPage = link.getString("next");
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put("id", c.getString("id"));
map.put("look1", c.getString("look1"));
map.put("look2", c.getString("look2"));
map.put("comment", c.getString("comment"));
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, restaurant_list,
R.layout.feed_item, new String[]{
"id", "look1", "look2", "comment"}, new int[]{
R.id.profilePic, R.id.name, R.id.txtUrl});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
}
});
}
}
}
I am using asynctask in main activity and populating the list items from server data. Now I placed a download symbol beside each list item and now I want to implement onclick listener for it. I did not use any custom adapter to put download icon beside the list items, I used imageview in my xml. Now I made another class 'download' which downloads a specific file from server. When I put onclick for image (download icon) in main activity, it is showing me a null pointer exception.
My main activity:
public class MainActivity extends Activity {
TextView uid;
Button Btngetdata;
//URL to get JSON Array
private static String url = "myurl";
//JSON Node Names
private static final String TAG_POSTS = "allposts";
private static final String TAG_SINGLEPOST = "post";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.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
user = json.getJSONArray(TAG_POSTS);
String[] allposts = new String[user.length()];
for(int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
allposts[i]=c.getString(TAG_SINGLEPOST);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.singlepost,
R.id.singlepostid,
allposts
);
ListView list = (ListView) findViewById(R.id.allposts);
list.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
My download class:
public class download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// startBtn = (Button)findViewById(R.id.downloadid);
ImageView img = (ImageView) findViewById(R.id.downloadid);
img.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
public void startDownload() {
String url = "urlforfile";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/fileonserver.pdf");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
Now I want to implement onclick listener for each download icon in the listview. Can anyone help?
You want a callback that's (more or less) the same every time, for a child of the listview item view? There are a couple of approaches you could take. You're implementing getView() already in your adapter, right? Let's set the callback there.
public View getView (int position, View convertView, ViewGroup parent){
...
converView.findViewbyId(R.id.ID_OF_YOUR_DOWNLOAD_ICON).setOnClickListener(new OnClickListener() {
//new DownloadFileAsync().execute(url);?
});
return convertView;
}
I don't know where your NPE is, if you post your stack trace we can help with that as well.
I'm doing an app that has mutiple tab and for each tab has its own activity. after putting the code to load the list on one activity; still listview is not visible at all.
here is my code, somebody please help:
public class BillsActivity extends ListActivity {
private ProgressDialog pDialog;
String mUrl = BayadCenterConstants.BAYAD_URL_BILLERS;
JSONParsers jsonParser = new JSONParsers();
ArrayList<HashMap<String, String>> billerList;
JSONArray billers = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_child_bills);
/*
* Check network connection here
*/
billerList = new ArrayList<HashMap<String, String>>();
new LoadBillers().execute();
}
class LoadBillers extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BillsActivity.this);
pDialog.setMessage("Downlaoding list ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String json = jsonParser.getBillers(mUrl, params);
Log.d("Billers JSON: ", "> " + json);
try {
billers = new JSONArray(json);
if (billers != null) {
for (int i = 0; i < billers.length(); i++) {
JSONObject c = billers.getJSONObject(i);
String id = c.getString("bid");
String name = c.getString("name");
String status = c.getString("status");
String date_added = c.getString("date_added");
HashMap<String, String> map = new HashMap<String, String>();
map.put("bid", id);
map.put("name", name);
map.put("status", status);
map.put("date_added", date_added);
billerList.add(map);
}
}else{
Log.d("Billers: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
BillsActivity.this, billerList,
R.layout.tab_child_bills_list_row, new String[] { "bid", "name", "status",
"date_added" }, new int[] { R.id.txtBillerID, R.id.txtBillerName,
R.id.txtBillerStatus, R.id.txtBillerDateAdded });
setListAdapter(adapter);
}
});
}
}
this activity is just part of an activity that holds then in tab+swipe manner.
did i miss something with my code?
I am a beginner. I need an item by clicking on the list to send data "link" to activities "DownloadFile.java". The activity "DownloadFile.java" I need to replace the data with "String fileURL =" data for the "link" with the previous activities. Thank you very much.
acivity1
public class Mangalist extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholdermanga);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLmanga.getXML();
Document doc = XMLmanga.XMLfromString(xml);
int numResults = XMLmanga.numResults(doc);
if((numResults <= 0)){
Toast.makeText(Mangalist.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLmanga.getValue(e, "id"));
map.put("name", "Kapitola:" + XMLmanga.getValue(e, "name"));
map.put("volume", "Volume: " + XMLmanga.getValue(e, "volume"));
map.put("link", XMLmanga.getValue(e, "link"));
mylist.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.mangalist,
new String[] { "name", "volume" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Mangalist.this, "Kapitola '" + o.get("id") + "'", Toast.LENGTH_LONG).show();
Intent i = new Intent(Mangalist.this,DownloadFile.class);
startActivity(i);
}
});
}
DownloadFile activity
public class DownloadFile extends Activity {
public static final String LOG_TAG = "Android Downloader";
//initialize our progress dialog/bar
private ProgressDialog mProgressDialog;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
//initialize root directory
File rootDir = Environment.getExternalStorageDirectory();
//defining file name and url
public String fileName = "xx.jpg";
public String fileURL = "https://xx.JPG";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setting some display
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("Android Download File With Progress Bar");
//making sure the download directory exists
checkAndCreateDirectory("/my_downloads");
//executing the asynctask
new DownloadFileAsync().execute(fileURL);
}
//this is our download file asynctask
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
//connecting to url
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
//lenghtOfFile is used for calculating download progress
int lenghtOfFile = c.getContentLength();
//this is where the file will be seen after the download
FileOutputStream f = new FileOutputStream(new File(rootDir + "/my_downloads/", fileName));
//file input is from the url
InputStream in = c.getInputStream();
//here's the download code
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d(LOG_TAG,progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
//function to verify if directory exists
public void checkAndCreateDirectory(String dirName){
File new_dir = new File( rootDir + dirName );
if( !new_dir.exists() ){
new_dir.mkdirs();
}
}
//our progress bar settings
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
The correct approach is to pass the data in the Intent that you use to launch the DownloadFile activity. In OnItemClickListener
Intent i = new Intent(Mangalist.this,DownloadFile.class);
i.putExtra("link", link /* link from your list item*/ );
startActivity(i); //or startActivityForResult() if you want to come back to this activity
and in your DownloadFile activity onCreate()
Intent intent = getintent()
String link = intent.getStringExtra("link");
You may try to use SharedPreferences to pass parameters between activities.
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("fileURL", "actualURL");
editor.commit();
The other activity can read it as follows:
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(yourActivity.this);
String fileName = app_preferences.getString("fileURL", "");
StartActivityForResult.
Once the new activity has finished it will send the results back to you.