I have an application where I fetch data from http server & set data to activity.
for fetching data from server it takes time. so i want to give an progress dialog there.
I did that but problem is that progressdialog is coming but its not rotating(only constant).
Plz anybody tell me how it came like this!
Below is my code,
private void setupViews()
{
imgRestro = (ImageView) findViewById(R.id.imageResturant);
tvRestroName = (TextView) findViewById(R.id.tvRestroName);
tvRestroAddr = (TextView) findViewById(R.id.tvRestroAddr);
tvRestroArea = (TextView) findViewById(R.id.tvRestroArea);
tvRestroCity = (TextView) findViewById(R.id.tvRestroCity);
tvRestroPhone = (TextView) findViewById(R.id.tvRestroPhone);
tvRestroRating = (TextView) findViewById(R.id.tvRestroRating);
tvRestroCuisines = (TextView) findViewById(R.id.tvRestroCuisines);
tvRestroAttr = (TextView) findViewById(R.id.tvRestroAttributes);
}
//to execute url
private String executeHttpGet(String URL) throws Exception {
URL url = null;
StringBuffer strBuf = null;
BufferedReader read = null;
HttpURLConnection httprequest = null;
try {
url = new URL(URL);
httprequest = (HttpURLConnection) url.openConnection();
httprequest.setRequestMethod("GET");
httprequest.setDoInput(true);
httprequest.setDoOutput(true);
httprequest.setConnectTimeout(5000); //time for before connect
httprequest.setRequestProperty("Content-Type",
"text/plain; charset=utf-8");
//httprequest.setReadTimeout(15000); //time for after connect
read = new BufferedReader(new InputStreamReader(
httprequest.getInputStream()));
strBuf = new StringBuffer();
String line = "";
while ((line = read.readLine()) != null) {
strBuf.append(line).append("\n");
}
} catch (IOException ex) {
} finally {
try {
httprequest.disconnect();
read.close();
} catch (Exception ex) {
}
}
return strBuf.toString();
}
//to assign all the info from json to activity textview or imageview
private void examineJSONFile() {
try {
String str = "";
page = executeHttpGet(url);
Log.i("hello", str.toString());
JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
tvRestroName.setText("Restaurant "+innerobj.getString("name"));
String photoURL = innerobj.getString("photo");
URI uri = new URI(photoURL);
Bitmap bmp = loadBitmap(photoURL);
System.out.println("str ;" + photoURL + " uri " + uri);
imgRestro.setImageBitmap(Bitmap.createScaledBitmap(bmp, 300, 300,true));
tvRestroAddr.setText("Address: " + innerobj.getString("address"));
tvRestroArea.setText("Area: " + innerobj.getString("area"));
tvRestroCity.setText("City: " + innerobj.getString("city"));
JSONArray location = innerobj.getJSONArray("location");
String lat = location.get(0).toString();
String lng = location.get(1).toString();
latitude = Double.valueOf(lat.trim()).doubleValue();
longitude = Double.valueOf(lng.trim()).doubleValue();
System.out.println("Lat :" + latitude + " Long :" + longitude);
JSONArray phone = innerobj.getJSONArray("phone");
tvRestroPhone.setText("Phone: " + phone.get(0).toString() + " ,"
+ phone.get(1).toString());
tvRestroRating.setText("Rating: " + innerobj.getString("rating"));
JSONArray cuisines = innerobj.getJSONArray("cuisines");
tvRestroCuisines.setText("Cuisines: " + cuisines.get(0).toString()
+ " ," + cuisines.get(1).toString());
JSONArray attributes = innerobj.getJSONArray("attributes");
tvRestroAttr.setText("Attributes: " + attributes.get(0).toString()
+ " ," + attributes.get(1).toString() + " ,"
+ attributes.get(2).toString());
Log.i("hello", str.toString());
} catch (Exception je) {
tvRestroAddr.setText("Error w/file: " + je.getMessage());
}
}
// to get image from url in form of bitmap
private static Bitmap loadBitmap(String url) {
URL myFileUrl = null;
InputStream is = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
Log.i("im connected", "Download");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return BitmapFactory.decodeStream(is);
}
//for progressdialog
private class DownloadTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(InfoActivity.this);
protected void onPreExecute() {
System.out.println("In onPreExecute ");
dialog.setTitle("Loading..");
dialog.setMessage("Downloading source..");
dialog.setProgress(100);
dialog.setMax(5000);
dialog.show();
}
protected Void doInBackground(Void... unused) {
//examineJSONFile();
System.out.println("In doInBackground ");
return null;
}
protected void onPostExecute(Void unused) {
System.out.println("In onPostExecute ");
dialog.dismiss();
examineJSONFile();
}
Plz have a look and give the answer.
Thank you
You should override onProgressUpdate() method in AsyncTask and change your dialog's value there. You can send your progress value to the dialog via publishProgress() method from doInBackground(). Hope this helps.
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Related
I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson
I am new in Android development and I need some help with HttpURLConnection.
What I want to do is to send http get request (by clicking button) and then check the response (to check response I added TextView to my main Activity).
My code:
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendGetRequest(View View) {
new GetClass(this).execute();
}
private class GetClass extends AsyncTask<String, Void, Void> {
private final Context context;
public GetClass(Context c){
this.context = c;
}
protected void onPreExecute(){
progress= new ProgressDialog(this.context);
progress.setMessage("Loading");
progress.show();
}
#Override
protected Void doInBackground(String... params) {
String dataUrl = "http://myurl.com";
String dataUrlParameters = "email="+"pp#gmail.com"+"&name="+"priyabrat";
URL url;
HttpURLConnection connection = null;
try {
final TextView outputView = (TextView) findViewById(R.id.showOutput);
url = new URL(dataUrl);
connection = (HttpURLConnection) url.openConnection();
String urlParameters = "fizz=buzz";
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
int responseCode = connection.getResponseCode();
final StringBuilder output = new StringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
The problem is, when I run my app and click the button "Send GET Request", application is stopping with message "Application Was stopped"
Have a look at some Networking Librarys for Android, they will handle the async stuff for you:
Volley (https://developer.android.com/training/volley/index.html)
Retrofit makes(HTTP API into a Java interface.)(http://square.github.io/retrofit/)
OkHTTP(Retrofit works with it)https://github.com/square/okhttp/wiki/Recipes
If you would do it for your own, have a look at the doku from Async Task (
https://developer.android.com/reference/android/os/AsyncTask.html) and use the Function:
onPostExecute(String output)
invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
And instead of:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
make this:
return output;
I am trying to read phone contacts and send that list to my server, but getting FileNotFound error in some phones but programme is working properly in some phones. following is my class -
public class UpdateNetwork extends Activity {
private String server, server_response;
private String updatenetwork = "/update-network.php";
private String data_to_send;
public JSONArray jacontacts;
public JSONObject jcontacts;
public ArrayList<String> contacts;
private ProgressDialog pd;
private Long user_id;
private MainActivity main;
JSONObject jo = null;
Button update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatenetwork);
server = getString(R.string.server_add_new);
contacts = new ArrayList<String>();
main = new MainActivity();
update = (Button) findViewById(R.id.update);
update.setVisibility(View.INVISIBLE);
user_id = main.getDefaultsint("user_id", UpdateNetwork.this);
Updatenetwork un = new Updatenetwork(true);
un.execute();
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
URL url = null;
try {
url = new URL(server + updatenetwork);
data_to_send = "contacts=" + jcontacts + "&";
data_to_send += "user_id=" + user_id;
Updatenetwork un = new Updatenetwork(url, data_to_send);
un.execute();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class Updatenetwork extends AsyncTask<String, Integer, JSONObject> {
private URL url;
Boolean un_send = false;
String data_to_send;
public Updatenetwork(Boolean b) {
this.un_send = b;
}
public Updatenetwork(URL url, String data_to_send2) {
this.url = url;
this.data_to_send = data_to_send2;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (un_send) {
update.setVisibility(View.VISIBLE);
} else {
finish();
}
pd.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(UpdateNetwork.this, "Please wait...", "Sending...");
}
#Override
protected JSONObject doInBackground(String... params) {
Log.e("value of un_send", "********"+un_send+jcontacts);
if(un_send){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
/* System.out.println("name : " + name );
*/
// get <span id="IL_AD4" class="IL_AD">the phone number</span>
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(phone);
jacontacts = new JSONArray();
/* System.out.println("phone" + phone);*/
}
for(int i=0; i<contacts.size(); i++){
jacontacts.put(contacts.get(i));
}
jcontacts = new JSONObject();
try{
jcontacts.put("contacts", jacontacts);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Log.e("value inside", "json obj"+jcontacts);*/
pCur.close();
jo = jcontacts;
}
}
}
} else {
BufferedReader reader=null;
try
{
Log.e("inside try block ", "get text 11111111" + data_to_send);
URLConnection conn = url.openConnection();
Log.e("inside try block ", "get text 2222222" + data_to_send);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside ", "while loop");
}
server_response = sb.toString();
Log.e("server_response ", "server_response" +server_response);
}
catch(FileNotFoundException(String detailMessage))
{
Log.e("MyTag ", "Failure to get json data in --1--", ex);
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {
Log.e("MyTag", "Failure to get json data in ", ex);
}
}
try {
jo = new JSONObject(server_response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jo;
}
}
}
following is what i got in errorlog
12-18 16:44:21.922: E/MyTag(32005): Failure to get json data in --1--
12-18 16:44:21.922: E/MyTag(32005): java.io.FileNotFoundException: http:// server address/update-network.php
12-18 16:44:21.922: E/MyTag(32005): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:194)
I have some data on the internet for each specific longitude and latitude. If a user inputs a particular latitude and longitude, the data is downloaded from the web and then used in further calculation. I want to save that data so that the next time the user inputs the same latitude and longitude, It bypasses the web connectivity and proceeds with the existing data.
My Input Class:
public class OpTilt extends Activity implements OnClickListener {
EditText latitude, longitude;
Button go;
String data1, data2, link, link1;
double dat1, dat2;
TextView gps;
SharedPreferences dataurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.optilt);
initialize();
go.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
go = (Button) findViewById(R.id.loaddata);
latitude = (EditText) findViewById(R.id.lat);
longitude = (EditText) findViewById(R.id.lon);
dataurl = getSharedPreferences("url", 0);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data1 = longitude.getText().toString();
data2 = latitude.getText().toString();
dat1 = Double.parseDouble(data1);
dat2 = Double.parseDouble(data2);
link = ("http://www.otilt.com/api.php?lat=" + dat2 + "&lon=" + dat1);
SharedPreferences.Editor editor = dataurl.edit();
editor.putString("key", link);
editor.commit();
Intent i = new Intent(OpTilt.this, DataRetrieve.class);
startActivity(i);
}
}
My Parsing Class:
public class DataRetrieve extends Activity {
HttpClient client;
String URL, re, element;
JSONObject json, getjson;
int i, j, statusCode;
HttpGet httpget;
HttpResponse response;
HttpEntity entity;
InputStream is;
BufferedReader reader;
StringBuilder sb, sb1;
WakeLock w;
SharedPreferences getinput, passjson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
w = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "tag");
super.onCreate(savedInstanceState);
w.acquire();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dataretrieve);
// Bundle gotBasket = getIntent().getExtras();
// URL = gotBasket.getString("key");
getinput = getSharedPreferences("url", 0);
URL = getinput.getString("key", null);
Read r = new Read();
r.execute();
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DataRetrieve.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
re = null;
is = null;
json = null;
try {
client = new DefaultHttpClient();
httpget = new HttpGet(URL);
response = client.execute(httpget);
entity = response.getEntity();
is = entity.getContent();
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
statusCode = -1;
Log.e("log_tag", "Erro http " + e.toString());
}
if (statusCode == 200) {
try {
reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
re = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Erro conversão " + e.toString());
}
}
return re;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pd.dismiss();
try {
json = new JSONObject(result);
getjson = json.getJSONObject("Solar");
String H[] = new String[getjson.length()];
for (i = 0, j = 1; i < getjson.length(); i++, j++) {
H[i] = getjson.getString("" + j);
}
Bundle bundle = new Bundle();
bundle.putStringArray("key1", H);
Intent f = new Intent(DataRetrieve.this, Calculator.class);
f.putExtras(bundle);
startActivity(f);
}
catch (JSONException e) {
Log.e("log_tag", "Erro dados " + e.toString());
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
w.release();
finish();
}
}
So, how can I achieve my goal?
When I call asynctask function data is load and display in listview but whenever i go into this activity everytime that function execute and load data again. But I just want that function call only once and display in listview. So what is the solution for that.
This is My full class code:
public class Feed extends Fragment implements
PullToRefreshAttacher.OnRefreshListener {
Button btnSlider;
ListView lv;
String userid, success, message, eventType, feed_title, feed_desc,
timeDate, like, commemt, Feeduserid, photo, posted, hasLike,
latsId, noMore, feed_id, category_id, feedImg, result;
InputStream is;
ProgressDialog pDialog;
InterNetConnectionDetector isNet = new InterNetConnectionDetector(
getActivity());
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
FeedAdapter fdp;
HashMap<String, String> map;
private uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher mPullToRefreshAttacher;
int limit = 5;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.feed, container, false);
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
SharedPreferences pref = getActivity().getSharedPreferences("Login",
Activity.MODE_PRIVATE);
userid = pref.getString("user_id", "user_id");
btnSlider = (Button) v.findViewById(R.id.btnSlide);
lv = (ListView) v.findViewById(R.id.feed_ListView);
btnSlider.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
Sliding.viewActionsContentView.showActions();
} catch (Exception e) {
// TODO: handle exception
}
}
});
try {
if (fdp == null) {
new FeedData().execute();
} else {
lv.setAdapter(fdp);
}
} catch (Exception e) {
// TODO: handle exception
}
mPullToRefreshAttacher = new uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher(
getActivity(), lv);
// Set Listener to know when a refresh should be started
mPullToRefreshAttacher
.setRefreshListener((uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher.OnRefreshListener) this);
((LoadMore) lv)
.setOnLoadMoreListener(new com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
return v;
}
/*
* #Override protected void onCreate(Bundle savedInstanceState) { // TODO
* Auto-generated method stub super.onCreate(savedInstanceState);
* setContentView(R.layout.feed);
*
* if (Build.VERSION.SDK_INT >= 8) { getActionBar().hide(); }
*
* if (android.os.Build.VERSION.SDK_INT > 8) {
*
* StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
* .permitAll().build(); StrictMode.setThreadPolicy(stp);
*
* }
*
* try { new FeedData().execute();
*
* } catch (Exception e) { // TODO: handle exception }
*
* SharedPreferences pref = getSharedPreferences("Login",
* Activity.MODE_PRIVATE); userid = pref.getString("user_id", "user_id");
*
* btnSlider = (Button) findViewById(R.id.btnSlide); lv = (ListView)
* findViewById(R.id.feed_ListView); btnSlider.setOnClickListener(new
* OnClickListener() {
*
* #Override public void onClick(View arg0) { // TODO Auto-generated method
* stub
*
* int width = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
* 40, getResources() .getDisplayMetrics());
* SlideoutActivity.prepare(getActivity(), R.id.inner_content, width);
* startActivity(new Intent(getActivity(), MenuActivity.class));
* getoverridePendingTransition(0, 0);
*
* } });
*
* mPullToRefreshAttacher = new PullToRefreshAttacher(getActivity(), lv);
*
* // Set Listener to know when a refresh should be started
* mPullToRefreshAttacher .setRefreshListener((OnRefreshListener)
* getActivity());
*
* ((LoadMore) lv) .setOnLoadMoreListener(new
* com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() { public
* void onLoadMore() { // Do the work to load more items at the end of list
* // here new LoadDataTask().execute(); } }); }
*/
public class FeedData extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "", "Loading..");
pDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
Log.v("Length", contactList.size() + "");
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
}
}
#Override
public void onRefreshStarted(View view) {
/**
* Simulate Refresh with 4 seconds sleep
*/
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
}.execute();
}
private class LoadDataTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
limit += 5;
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
// mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
fdp.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMore) lv).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMore) lv).onLoadMoreComplete();
}
}
}
Better option is like, just declare your ADAPTER as public static in your ROOT class or in your activity. This will make single copy. And you are done with.
Suppose you have following structure.
ABC (ROOT/SPLASH) Activity -> class Feed extends Fragment
So basically you are calling Feed from ABC. Inside ABC, declare like
public class ABC...{
public static FeedAdapter fdp;
//.. all other stuffs
}
public class Feed...{
//.. to use that object delcared in ABC
ABC.fdp = new FeedAdapter(...);
}