I want to make a simple widget on my Android Homescreen where I am able to fill in my postalcode or city, and by submitting that data, I would like to be able to update the Widget with data from an API call to Openweathermap.org.
I've made every step to make it work, but for some reason the Widget textView won't update with the data collected.
This is my main activity.
public class WeerManWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
CharSequence widgetText = WeerManWidgetConfigureActivity.loadTitlePref(context, appWidgetId);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weer_man_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
Intent configIntent = new Intent(context, WeerManWidgetConfigureActivity.class);
configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent configPendingIntent = PendingIntent.getActivity(context, appWidgetId, configIntent, 0);
views.setOnClickPendingIntent(R.id.btnSettings, configPendingIntent);
configIntent.setAction(ACTION_WIDGET_CONFIGURE + Integer.toString(appWidgetId));
new GetWeatherTask(views).execute(widgetText.toString());
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
// When the user deletes the widget, delete the preference associated with it.
for (int appWidgetId : appWidgetIds) {
WeerManWidgetConfigureActivity.deleteTitlePref(context, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
And this is the class that I use for the API call.
public class GetWeatherTask extends AsyncTask<String, String, String> {
private RemoteViews views;
GetWeatherTask(RemoteViews views) {
this.views = views;
}
#Override
public String doInBackground(String... params) {
String postalCode = params[0];
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
JSONArray myArray = null;
InputStream inStream = null;
try {
url = new URL("http://api.openweathermap.org/data/2.5/weather?q="+postalCode+",nl&appid=XXXXX&units=metric");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null) {
response += temp;
}
object = (JSONObject) new JSONTokener(response).nextValue();
JSONObject obj = object.getJSONObject("main");
String weatherTemp = obj.getString("temp");
double weatherFloat = Double.parseDouble(weatherTemp);
//weatherFloat = (weatherFloat - 273.15);
String newTemp = String.valueOf(weatherFloat);
return newTemp;
} catch (Exception e) {
return e.toString();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException ignored) {
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
#Override
public void onPostExecute(String result) {
Log.v("WeerManWidget", result);
views.setTextViewText(R.id.appwidget_text, result);
}
}
Seen in the onPostExecute in the AsyncTask, I log the results. This has the correct data. So everthing comes along nicely, but when I want to update the view with the setTextViewText, nothing happens. I am new to Android development, and am out of ideas.
Anyone care to enlighten me?
After you called the API and used:
views.setTextViewText(R.id.appwidget_text, result);
You need to use the AppWidgetManager to update the UI.
Here is an example:
AppWidgetManager manager=AppWidgetManager.getInstance(context);
manager.updateAppWidget(widgetID,views);
private void updateViewHere(String parseResult){
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
int[] ids = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, WidgetProvider.class));
views.setTextViewText(R.id.text, parseResult);
AppWidgetManager manager=AppWidgetManager.getInstance(context);
manager.updateAppWidget(ids,views);
}
Using this approach we can update widget views.
Related
I am new to android studio and just want an app to do one thing: check if the bytewerk is open (domain is stats.bytewerk.org/status.txt just one word either open or closed) and display it on a widget. But I tried all kind of httpconections like volley or okhttp, but never got a result. I already added the uses permission in the manifest.
1:
public class StatusWidget<appWidgetId> extends AppWidgetProvider {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) throws IOException {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.status_widget);
new GetNotePadFileFromServer().execute();
//views.setViewVisibility(R.id.bytewerk_online, 0);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
try {
updateAppWidget(context, appWidgetManager, appWidgetId);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}public class GetNotePadFileFromServer extends AsyncTask<Void, Void, Void> {
String TextHolder;
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://stats.bytewerk.org/status.txt");
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
TextHolder = "";
String TextHolder2 = "";
while ((TextHolder2 = bufferReader.readLine()) != null) {
TextHolder += TextHolder2;
}
bufferReader.close();
} catch (MalformedURLException malformedURLException) {
// TODO Auto-generated catch block
malformedURLException.printStackTrace();
TextHolder = malformedURLException.toString();
} catch (IOException iOException) {
// TODO Auto-generated catch block
iOException.printStackTrace();
TextHolder = iOException.toString();
}
return null;
}
#Override
protected void onPostExecute(Void finalTextHolder) {
textView.setText(TextHolder);
super.onPostExecute(finalTextHolder);
}
2:
final TextView textView = (TextView) findViewById(R.id.text);
// ...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
And the other examples on the offical website
of course i already implemented
dependencies {
...
implementation 'com.android.volley:volley:1.1.1'
}
Add internet permission to your Manifest.xml and volley works, This line:
<uses-permission android:name="android.permission.INTERNET" />
before application tag.
Hope this helps.
this was my solution:
static void updateAppWidget(Context context, final AppWidgetManager appWidgetManager,
final int appWidgetId) {
final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.status_widget);
// ...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
String url ="http://stats.bytewerk.org/status.txt";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
public void onResponse(String response) {
// Display the first 500 characters of the response string.
if (response.equals("open")) {
views.setViewVisibility(R.id.status_online, 1);
} else {
views.setViewVisibility(R.id.status_offline, 1);
}
//views.setTextViewText(R.id.text, "Yeah!" + response);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
views.setViewVisibility(R.id.status_nointernet, 1);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
});
queue.add(stringRequest);
this is my listview where data is coming from the remote server in the JSON format so everything is working fine but now I have to pass a certain value to the server and then make a filter based on that value and then load only the desired result into the listview
public class Reciepe extends AppCompatActivity {
String Barname;
TextView food,price;
private ListView reciepeListView;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reciepe);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Color.parseColor("#FFBC03"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
new JSONTask().execute("http://thehostels.in/Foody/reciepe_json.php");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(Reciepe.this)
.defaultDisplayImageOptions(options)
.build();
com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
reciepeListView = (ListView)findViewById(R.id.list_recipe);
Intent intent=getIntent();
if(intent!=null){
Barname=intent.getStringExtra("Type");
Log.e("Type",Barname);
}
if (Barname != null) {
switch (Barname) {
case "Punjabi":
getSupportActionBar().setTitle("Punjabi");
break;
case "Chinese":
getSupportActionBar().setTitle("Chinese");
break;
case "South Indian":
getSupportActionBar().setTitle("South Indian");
break;
case "Gujarati":
getSupportActionBar().setTitle("Gujarati");
break;
case "Chicken":
getSupportActionBar().setTitle("Chicken");
break;
}
}
}
public class JSONTask extends AsyncTask<String, String, List<Listview_reciepe_conveyer>> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Reciepe.this, "loading,please wait...", null, true, true);
}
#Override
protected List<Listview_reciepe_conveyer> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("list");
List<Listview_reciepe_conveyer> fixture_conveyerList = new ArrayList<Listview_reciepe_conveyer>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Listview_reciepe_conveyer fixtureList = new Listview_reciepe_conveyer();
fixtureList.setImage(finalObject.getString("image"));
fixtureList.setFood(finalObject.getString("food"));
fixtureList.setPrice(finalObject.getString("price"));
fixture_conveyerList.add(fixtureList);
}
return fixture_conveyerList;
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<Listview_reciepe_conveyer> result) {
super.onPostExecute(result);
if (result !=null) {
loading.dismiss();
ListAdapter adapter = new ListAdapter(Reciepe.this, R.layout.custom_recipe_list, result);
reciepeListView.setAdapter(adapter);
}
else
{
Toast.makeText(Reciepe.this, "No Internet Connection!", Toast.LENGTH_LONG).show();
loading.dismiss();
}
}
}
public class ListAdapter extends ArrayAdapter {
private List<Listview_reciepe_conveyer> reciepe_conveyerList;
private int resource;
private LayoutInflater inflater;
public ListAdapter(Context context, int resource, List<Listview_reciepe_conveyer> objects) {
super(context, resource, objects);
reciepe_conveyerList = objects;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView food_photo;
final TextView food,price;
food_photo = (ImageView)convertView.findViewById(R.id.food_photo);
food = (TextView)convertView.findViewById(R.id.food_name);
price = (TextView)convertView.findViewById(R.id.food_price);
ImageLoader.getInstance().displayImage(reciepe_conveyerList.get(position).getImage(), food_photo);
food.setText(reciepe_conveyerList.get(position).getFood());
String newprice= ("Rs."+reciepe_conveyerList.get(position).getPrice());
price.setText(newprice);
reciepeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(Reciepe.this,Description.class);
i.putExtra("Dish",reciepe_conveyerList.get(position).getFood());
i.putExtra("Price",reciepe_conveyerList.get(position).getPrice());
startActivity(i);
}
}
);
return convertView;
}
}
}
this is what my code looks like where i am loading a list from an api,
so i am using AsyncTask to load the listview but i do not know how to make the post request , i have updated the api it os taking the post values but what changes do i need to make on android level.., i have to pass the 'barname' as the post parameter...
On:
protected List<Listview_reciepe_conveyer> doInBackground(String... params) {
Try:
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("firstParam", "paremeterValue"));
//your param nr.1.
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'firstParam=parameterValue'.
//You need to edit this field in respect to what you are doing.
params.add(new BasicNameValuePair("secondParam", "your2parameter"));
//your param nr.2
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'secondParam=your2parameter'.
//You need to edit this field in respect to what you are doing.
params.add(new BasicNameValuePair("thirdParam", "anotherParameter"));
//your param nr.3
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'thirdParam=anotherParameter'.
//You need to edit this field in respect to what you are doing.
// Write(add) parameters to your request
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
Before your..:
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
...
EDITED
private String getQuery(List<BasicNameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (String pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
This function turn's the List params, in a String with the format, 'name=value' which is needed to send via request.
For more info see Query String.
Please do NOT copy and paste the solution, you also need to understand what you are doing and replace variables/methods accordingly, for this code to work.
Best
How make notification?
How to check the date of the news and show notification when there is news?
Can service get SharedPref from Fragment and check and then make notification or no?
TabFragment1.class code:
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String imageUrl = object.getString("urlToImage");
String articleUrl = object.getString("url");
String newsdata = object.getString("publishedAt");
sPref = getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, newsdata);
ed.commit();
Toast.makeText(getActivity(), "Text saved", Toast.LENGTH_SHORT).show();
News news = new News(title, desc, imageUrl, articleUrl);
myAdapter.addNews(news);
myAdapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Notification Service code:
public class Notification extends Service {
String datanews;
String titlenotif;
String destnotif;
MyAsynk asynk;
final String SAVED_TEXT = "saved_text";
String checker;
SharedPreferences sPref;
#Override
public void onCreate() {
super.onCreate();
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 0, 1800000); //тикаем каждые 30 мinute без задержки 1800000
}
class UpdateTimeTask extends TimerTask {
public void run() {
sPref = getSharedPreferences("MyPref",MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
checker = sPref.getString(savedText, "0");
if(datanews != checker){
asynk = new MyAsynk();
asynk.execute();
createNotification(getApplicationContext());//пушим уведомление
} else {
asynk = new MyAsynk();
asynk.execute();
}
}
}
class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
#Override
protected StringBuilder doInBackground(Void... voids) {
StringBuilder stringBuilder = new StringBuilder();
String key = "0aa2713d5a1a4aad9a914c9294f6a22b";
try {
URL url = new URL("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=" + key);
URLConnection uc = url.openConnection();
uc.connect();
BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
int ch;
while ((ch = in.read()) != -1) {
stringBuilder.append((char) ch);
}
} catch (Exception e) {e.printStackTrace();}
return stringBuilder;
}
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String newsdata = object.getString("publishedAt");
datanews = newsdata;
titlenotif = title;
destnotif = desc;
}
}
catch (Exception e){e.printStackTrace();}
}
}
private void createNotification(Context context) {
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncBuilder = new NotificationCompat.Builder(context);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
ncBuilder.setVibrate(new long[]{500});
ncBuilder.setLights(Color.WHITE, 3000, 3000);
ncBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
ncBuilder.setContentIntent(pIntent);
ncBuilder.setContentTitle(titlenotif + "");
ncBuilder.setContentText(destnotif + "");
ncBuilder.setTicker("You have news!");
ncBuilder.setSmallIcon(R.drawable.news_icon);
ncBuilder.setAutoCancel(true);
manager.notify((int)System.currentTimeMillis(),ncBuilder.build());
}
public IBinder onBind(Intent arg0) {
return null;
}
}
Yes Service can read SharedPreference and can make notification.
If I understood correctly, you need to create the notification in the onPostExecute function of your MyAsynk class.
So you may try adding an public attribute in your AsyncTask like this.
class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
public boolean showNotification;
// .. Other functions
}
Now in your UpdateTimerTask
if(datanews != checker){
asynk = new MyAsynk();
asynk.showNotification = true;
asynk.execute();
} else {
asynk = new MyAsynk();
asynk.showNotification = false;
asynk.execute();
}
Now in the onPostExecute of your MyAsynk class, you need to check the boolean and create the notification accordingly.
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String newsdata = object.getString("publishedAt");
datanews = newsdata;
titlenotif = title;
destnotif = desc;
}
// Create notification here on demand
if(showNotification) createNotification(getApplicationContext);
}
catch (Exception e){e.printStackTrace();}
}
Update
From comment
Maybe somehow it is necessary to check the date of the publication of
news, verify it with the current date and display a notice .. So you
need to show the notice only when there is news
If you're planning to track the new news from client side only, you might have to do a lot of coding including keeping a local storage and checking each time if a new news arrived or not. You need to have a server-side implementation here I guess. Which will send you a push notification when a new news is received. The server should handle the syncing and other mechanisms.
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();
}
Pretty new in Android.
The problem here is simple.
My app needs to be waken up in some interval of time.
The problem is that I can`t call it properly.
There in the comment // HERE IS THE PROBLEM the code is breaking giving me error that cant find context and to declare it.
public class BackgroundService extends Service {
Integer background_connect = null;
String SERVER_IP;
String APP_ID;
private Context context;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
DB_Queries db = new DB_Queries(getApplicationContext());
Cursor c = db.getSettings();
StringBuilder app_id = new StringBuilder();
StringBuilder server_ip = new StringBuilder();
if (c.moveToFirst()) {
do {
server_ip.append(c.getString(c.getColumnIndex("server_ip")));
app_id.append(c.getString(c.getColumnIndex("app_id")));
} while (c.moveToNext());
}
db.close();
SERVER_IP = server_ip.toString();
APP_ID = app_id.toString();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
requestServerDelay delay = new requestServerDelay();
delay.execute("http://" + SERVER_IP + "/index.php/app/requestAppRecall");
return super.onStartCommand(intent, flags, startId);
}
private class requestServerDelay extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
post.addHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("app_id", APP_ID));
try {
post.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = client.execute(post);
InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder str = new StringBuilder();
String chunk = null;
while ((chunk = br.readLine()) != null) {
str.append(chunk);
}
background_connect = Integer.parseInt(str.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//HERE IS THE PROBLEM
Intent intent = new Intent(getApplication().getApplicationContext(), getApplication().getApplicationContext().getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().getApplicationContext().startActivity(intent);
}
}, background_connect * 60 * 1000);
}
}
}
If the requestServerDelay task is in the service, you can use getApplicationContext().startActivity(...) to start an activity.
No need for getApplication() before.
Alternatively You can keep a Context member in the Service class (mContext) and use it.