I am downloading data from a website and would like to put it in an ArrayList. I am downloading 2 forms, images and URLS.
ArrayList<String> artistNames = new ArrayList<String>();
ArrayList<String> artistImageURLS = new ArrayList<String>();
int chosen = 0;
public class nameGetterClass extends AsyncTask<Void, Void, String>{
Handler handle;
Document doc;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... strings) {
try {
String url = "http://www.billboard.com/charts/artist-100";
doc = Jsoup.connect(url).get();
Elements names = doc.select("div.chart-row__title > h2.chart-row__song");
for (Element p : names)
artistNames.add(p.text());
// Log.i("names,", p.text());
}
catch(IOException ex){
}
return null;
}
#Override `**<--- ERROR HERE: method does not override superclass**`
protected void onPostExecute(Void result) {
}
}
I get an error as described in the second last line.
This actually doesnt even add anything to the arraylist, what should I do now?
protected String doInBackground(Void... strings) {
try {
String url = "http://www.billboard.com/charts/artist-100";
doc = Jsoup.connect(url).get();
Elements names = doc.select("div.chart-row__title > h2.chart-row__song");
for (Elements p : names)
artistNames.add(p.text());
// Log.i("names,", p.text());
}
catch(IOException ex){
}
return null;
}
please update the line inside the foreach with Elements you put Element. If you have still any problem please try to paste the console output which will you got when run in emulator that one makes people understand what the real problem is.
Try to use with volley library . Its easy and updated
https://developer.android.com/training/volley/request.html
ArrayList<String> artistImageURLS = new ArrayList<String>();
String url = "http://my-json-feed";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
artistImageURLS.add(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
and here the Singleton :
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
Related
I am trying to implement a GET request using Volley. I have a button 'Apply' in PlacementActivity which directs the user to PlacementHomeActivity which has fragments. I have implemented the GET request in Apply.OnClickListener and the data received from the request must be shown in PlacementHomeActivity. But I get a null object error in this line:
SingletonRequestQueue.getInstance(PlacementActivity.context).addToRequestQueue(ArrayRequest);
(This code worked fine when Activity was used instead of Fragments)
This is the code of the Apply.OnClickListener class:
Apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
applyList = new ArrayList<Company>();
JsonArrayRequest ArrayRequest = new JsonArrayRequest(Request.Method.GET, applyCompaniesUrl,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject companies = response.getJSONObject(i);
String id = companies.getString("id");
JSONObject company = companies.getJSONObject("company");
Company company = new Company(id, company);
applyList.add(company);
}
} catch (JSONException e) {
e.printStackTrace();
}
Intent applyListIntent = new Intent(PlacementActivity.this,
PlacementHomeActivity.class);
startActivity(applyListIntent);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PlacementActivity.this, error.toString(), Toast.LENGTH_LONG).show();
StringWriter writer = new StringWriter();
error.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Cookie", "remember_user_token=" + userToken);
return params;
}
};
SingletonRequestQueue.getInstance(PlacementActivity.context).addToRequestQueue(ArrayRequest);
}
});
This is the SingletonRequestQueue class:
public class SingletonRequestQueue {
public static SingletonRequestQueue mInstance;
private RequestQueue mRequestQueue;
private static Context appContext;
public Context context;
private SingletonRequestQueue(Context context){
appContext = context;
mRequestQueue = getRequestQueue();
}
public static synchronized SingletonRequestQueue getInstance(Context context){
if(mInstance==null) {
mInstance = new SingletonRequestQueue(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
if(mRequestQueue==null){
mRequestQueue = new Volley().newRequestQueue(appContext.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> request){
getRequestQueue().add(request);
}
}
How do I fix this error?
It seems like a context problem, try replacing PlacementActivity.context for getApplicationContext()
SingletonRequestQueue.getInstance(Context.getApplicationContext()).addToRequestQueue(ArrayRequest);
Am implementing a service to get updates from server as below:
public class Myupdates extends Service {
private static final String TAG = "AutoUpdates";
private static final int started = 0;
static SQLiteDatabase db;
private boolean isRunning = false;
private CountDownTimer timer;
#Override
public void onCreate() {
this.db = openOrCreateDatabase("db", Context.MODE_PRIVATE, null);
//Log.i(TAG, "Service onCreate");
isRunning = true;
}
int mCount = 1;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
#Override
public void run() {
if (isRunning) {
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
updates();
}
}, 0, 30000);
}
//Stop service once it finishes its task
//stopSelf();
}
}).start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
//Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
//Log.i(TAG, "Service onDestroy");
}
/*
HANDLE ADVERTS
*/
protected void updates() {
/*
JSON
*/
final JSONObject json = new JSONObject();
final JSONObject manJson = new JSONObject();
try {
manJson.put("userid", "4444");
manJson.put("version", "6.0");
final String j = json.put("UPDATE", manJson).toString();
final String base_url = "https://myweburl.com";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, base_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.i(TAG, "received "+response);
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String update = object.getString("UPDATE");
} catch (JSONException e) {
return;
}
return;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//perform operation here after getting error
return;
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//pack message into json
try {
params.put("data", j.toString());
} catch (Exception e) {
//Log.i(TAG,"Map error: Unable to compile post");
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
// ends here
return;
} catch (Exception e) {
//Log.i(TAG,"ERROR: Unable to get setup settings");
} // end exception write
return;
}
}
However, after a long running of the service the app is crashing with the below error:
03-08 00:19:41.570 11239-11253/com.mobiledatabook.com.dialcode
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.mobiledatabook.com.dialcode, PID: 11239
java.lang.OutOfMemoryError: pthread_create (stack size 16384 bytes)
failed: Try again
at java.lang.VMThread.create(Native Method)
at java.lang.Thread.start(Thread.java:1029)
at com.android.volley.RequestQueue.start(RequestQueue.java:152)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:66)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at
com.mobiledatabook.com.dialcode.Myupdates.iDialAutoUpdates(Myupdates.java:128)
at
com.mobiledatabook.com.dialcode.Myupdates$1$1.run(Myupdates.java:74)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Error: java.lang.OutOfMemoryError.
Could someone help me to improve this code so as to avoid crashing the app after long running of the service?
This is occurring because you are creating the RequestQueue instance multiple times by passing the activity context. You should create the instance once using an Application class and then use it again and again whenever needed. Create an application class like this,
public class AppController extends Application {
private static AppController sInstance;
private RequestQueue mRequestQueue;
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static synchronized AppController getInstance() {
return sInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
}
Then use it like this
RequestQueue queue=AppController.getInstance().getRequestQueue();
NOTE : By passing the context to request queue again and again , you are filling up your ram, which leads to an OutOfMemoryException when no more space can be allocated
As mentioned in android's official docs here ,
A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
I am trying to post boolean value using volley library.When a button is clicked,a boolean value is set to true.The boolean value is then posted to my php script to increment counter in my mysql database. i am getting an error in trying to add a request to queue. What am i doing wrong? This is my code
holder.custom_button.setOnClickListener(new View.OnClickListener() {
int count;
#Override
public void onClick(View v) {
count = 0;
superHeroes.get(position).setCount(superHeroes.get(position).getCount() + 1);
holder.txtCount.setText(superHeroes.get(position).getCount() + "");
final String url = "http://10.0.2.2/likes.php";
isLiked = true;
JSONObject obj = new JSONObject();
try {
obj.put("isLiked", true);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
// i am getting error here
customVolleyRequest.getInstance(this).addToRequestQueue(jsObjRequest);
}
});
SINGLETON
package net.simplifiedcoding.myfeed;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;
/**
* Created by Belal on 12/5/2015.
*/
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
ERROR
'getInstance(android.content.Context)' in 'net.simplifiedcoding.myfeed.CustomVolleyRequest' cannot be applied to '(anonymous android.view.View.OnClickListener)'
You are not making POST request. You should do like this:
JsonObjectRequest req = new JsonObjectRequest( Request.Method.POST, url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Handle response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
AppController.getInstance().addToRequestQueue(req); // AppController is Volley Singleton.
You have used CardAdapter, I don't what that is. You should always add the request object to Volley Singleton. Reference.
When the new message is received, message should be passed to the internet for my further business logic.
To receive the new messages I used onReceive of broadcastreceiver and to process the internet business logics in background I used AsyncTask.
I am getting the null pointer exception in onPostExecute method of AyncTask, I read many stackoverflow and other website solutions and created the interface and initialized it in the AsyncTask extended class constructor. But getting only nullpointer.
My Full code:
MainActivity:
public class SmsActivity extends Activity implements ParseURL.OnAsyncRequestComplete {
private static SmsActivity inst;
public static final String SMS_BUNDLE = "pdus";
public static SmsActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
}
#Override
public void processResp(String output){
String outpu1 = output+" in main";
}
}
BroadCastReceiver:
public class SmsBroadcastReceiver extends BroadcastReceiver{
public static final String SMS_BUNDLE = "pdus";
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
boolean rechargeResult = false;
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
if (smsBody != null) {
String[] splitValues = smsBody.split(" ");
if (splitValues != null && splitValues.length > 0) {
String siteURL = "SITE_URL";
try {
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
Toast.makeText(context, siteURL, Toast.LENGTH_LONG).show();
new ParseURL(procesInterf).execute(new String[]{siteURL});
} catch (Exception e) {
Toast.makeText(context, "123 "+e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "split values is null", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "smsbody is null", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
ParseURL:
public class ParseURL extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
OnAsyncRequestComplete caller;
//Context context;
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
// context = a;
}
public interface OnAsyncRequestComplete {
public void processResp(String response);
}
#Override
protected void onPreExecute()
{
progressDialog.setMessage("WAIT...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String responseStatus = "";
try {
if(strings!=null) {
if (null != strings[0]) {
Document doc = Jsoup.connect(strings[0]).timeout(0).get();
if (doc != null) {
String result = doc.select("body").text();
if (null != result) {
if (result.toLowerCase().contains("FAILED".toLowerCase())) {
responseStatus = result;
} else if (result.toLowerCase().contains("SUCCESS".toLowerCase())) {
responseStatus = "SUCCESS";
} else {
responseStatus = "FAILED";
}
} else {
responseStatus = "google";
}
} else {
responseStatus = "facebook";
}
} else {
responseStatus = "youtube";
}
}else{
responseStatus = "ebay";
}
} catch (Throwable t) {
t.printStackTrace();
}
return responseStatus;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
}
I tried many solutions which is shared in the stackoverflow and other sites. But I could not solve it. Please do not mark this as duplicate.
Thanks in advance.
Ohh maaan...
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
Are You see mistake?
You pass null to the ParseUrl constructor, so on PosteExecute() tries to call a method of a null callback.
I suspect that you would like to do that
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.this;
But it will work, if your SmsBroadcastReceiver class is a inner class of SmsActivity.
You never initialize caller. Basically you set it to null, then you pass it to your AsyncTask, then you try to use it.
You already use the singleton pattern in your Activity, so you were probably after
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.instance();
I want to send Cus_id from postParamName to web server.
According to cus_id I want to fetch data from server and get it into listview.
I have no error in my code...but the code still not able to fetch data from server..
Plz look at my code...i have been working on this code since last two days. but I am not able to find the mistake
Point1.java
public class Points1 extends ListActivity implements FetchDataListener {
SessionManager session;
TextView tvCusPoints1, tvCusPoints2, tvcusName;
TextView bus_name;
TextView cus_points;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.points);
initView();
}
private void initView() {
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// ID
String cus_id = user.get(SessionManager.KEY_ID);
ArrayList<NameValuePair> postParamName = new ArrayList<NameValuePair>();
postParamName.add(new BasicNameValuePair("cus_id", cus_id));
String url = "http://10.0.2.2/android_api_main/business_points.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
}
}
Application.java
public class Application
{
private String bus_name;
private String cus_points;
public String getbus_name() {
return bus_name;
}
public void setbus_name(String bus_name) {
this.bus_name = bus_name;
}
public String getcus_points() {
return cus_points;
}
public void setcus_points(String cus_points) {
this.cus_points = cus_points;
}
}
ApplicationAdapter.java
public class ApplicationAdapter extends ArrayAdapter<Application> {
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.point_list_item, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.point_list_item, null);
}
Application app = items.get(position);
if (app != null) {
TextView titleText = (TextView) v.findViewById(R.id.item_bname1);
TextView dlText = (TextView) v.findViewById(R.id.item_bpoint1);
if (titleText != null)
titleText.setText(app.getbus_name());
if (dlText != null)
dlText.setText(app.getcus_points());
}
return v;
}
}
FetchDataTask.java
public class FetchDataTask extends AsyncTask<String, Void, String> {
private final FetchDataListener listener;
private String msg;
String cus_id, responseString, success, bus_name, cus_points;
SessionManager session;
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
if (params == null)
return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
// get response content and convert it to json string
} catch (IOException e) {
msg = "No Network Connection";
}
return responseString;
}
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
List<Application> apps = new ArrayList<Application>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
bus_name = json_data.getString("bus_name");
cus_points = json_data.getString("cus_points");
success = json_data.getString("success");
Application app = new Application();
app.setbus_name(json.getString("bus_name"));
app.setcus_points(json.getString("cus_points"));
// add the app to apps
apps.add(app);
}
if (listener != null)
listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if (listener != null)
listener.onFetchFailure(msg);
return;
}
}
}
FetchDataListener.java
public interface FetchDataListener {
public void onFetchComplete(List<Application> data);
public void onFetchFailure(String msg);
}
Your FetchDataTask constructor accepts FetchDataTaskListener as parameter
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
But you have initialized it using activity's context
FetchDataTask task = new FetchDataTask(this);
Could you please check this.
You should set listener correctly, something like this
this.mListener = (FetchDataListener) activity