I have a MainActivity whose onCreate is
//called when activity first created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchText = (EditText) findViewById(R.id.searchText);
utils = new Utils(MainActivity.this);
db=(new SQLLiteDbHelper(MainActivity.this,utils.getInt(Key.Db_version))).getReadableDatabase();
request = new WebRequest(this);
status = new AsynGetEmployeeStatus();
}
and sqlitehelper onCreate and constructor is
//constructor
public SQLLiteDbHelper(Context context,int dbVersion) {
super(context,DATABASE_NAME, null, dbVersion);
this.context = context;
Log.d("tag","db version is "+DATABASE_VERSION);
crypt = new Cryptography();
utils = new Utils(context);
}
//called when activity first created
#Override
public void onCreate(final SQLiteDatabase db) {
String s;
try {
//new LoadData().execute(db);
new AsynNetworkOperation(context, ServiceUri.AccessMethod.GET, "loading").execute(ServiceUri.SERVICE_URI+"s?d=abc"); //this line throw exception
} catch (Throwable t) {
Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
Log.d("tag",t.toString());
}
}
my AsynNetworkOperation class is
public class AsynNetworkOperation extends AsyncTask<String,Void,Void>{
private Context context = null;
private ProgressDialog dialog = null;
private String title = "";
private WebRequest request = null;
private String accessMethod = "";
private HttpResponse response = null;
AsynResponse delegate = null;
public AsynNetworkOperation(Context context, String method, String dialogTitle)
{
this.context = context;
accessMethod = method;
this.title = dialogTitle;
delegate = (AsynResponse) context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage(title);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected Void doInBackground(String... data) {
// TODO Auto-generated method stub
request = new WebRequest(context);
if(accessMethod.equals(ServiceUri.AccessMethod.GET)){
response = request.makeHttpGetCall(data[0]);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
delegate.responseResult(response);
dispose();
}
private void dispose()
{
context = null;
dialog = null;
title = "";
request = null;
accessMethod = "";
delegate = null;
}
}
AsynResponse is
public interface AsynResponse {
/**
* This will called when AysncTask finished its execution or when onPostExecute called
*
* #param response
*/
public void responseResult(HttpResponse response);
}
My problem is , whenever sqlitehelper try to execute new AsynNetworkOperation in its onCreate , it throw exception
java.lang.ClassCastException: android.app.MainActivity
can anyone help me finding the problem why it is throwing exception.
Thanks
Well this looks like it's probably the problem:
delegate = (AsynResponse) context;
You're casting the context variable to AsynResponse, and that context variable comes from here:
new SQLLiteDbHelper(MainActivity.this, ...)
So it isn't an AsynResponse. It's not even clear what AsynResponse is, but MainActivity presumably isn't compatible with it.
You should work out what you really want that value to be, potentially passing it separately to the Context.
Related
I want to display this textview "txtCalculate" which comes from the class CustomerMapActivity which is displayed in the activity_map_customer layout in another layout which is activity_bon_de_commande, of the class BonDeCommande.
the problem is I don't know how to do it
I'm new to java programming
thank you
public void readValues(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query lastQuery = ref.child("ride_info").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
double value0_float = ds.child("pickup").child("lat").getValue(Double.class);
double value1_float = ds.child("pickup").child("lng").getValue(Double.class);
double value2_float = ds.child("destination").child("lat").getValue(Double.class);
double value3_float = ds.child("destination").child("lng").getValue(Double.class);
String pickupLat = String.valueOf(value0_float);
String pickupLng = String.valueOf(value1_float);
String destiLat = String.valueOf(value2_float);
String destiLng = String.valueOf(value3_float);
String requestUrl=null;
try {
requestUrl = "https://maps.googleapis.com/maps/api/directions/json?"+
"mode=driving&"
+"transit_routing_preference=less_driving&"
+"origin="+pickupLat+","+pickupLng+"&"
+"destination="+destiLat+","+destiLng+"&"
+"key="+getResources().getString(R.string.google_maps_key);
Log.e("LINK",requestUrl);
mService.getPath(requestUrl).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject object = routes.getJSONObject(0);
JSONArray legs = object.getJSONArray("legs");
JSONObject legsObject = legs.getJSONObject(0);
//Get distance
JSONObject distance = legsObject.getJSONObject("distance");
String distance_text = distance.getString("text");
//use regex to extract double from string
//This regex will remove all text not digit
Double distance_value= Double.parseDouble(distance_text.replaceAll("[^0-9\\\\.]+",""));
//Get Time
JSONObject time = legsObject.getJSONObject("duration");
String time_text = time.getString("text");
Integer time_value = Integer.parseInt(time_text.replaceAll("\\D+",""));
String final_calculate = String.format("%.2f €",
TypeObject.getPrice(distance_value,time_value));
HERE -----> txtCalculate.setText(final_calculate);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
mCurrentRide.cancelRide();
endRide();
}
});
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
mCurrentRide.cancelRide();
endRide();
}
});
}
screenshot of my screen
You need to Create an Interface with an update method, declare in your Activity and after, pass as parameter to your handler object that gets the data.
Don't forget If you're getting the data in a different Thread, you need to update your views always in an UI Thread or in the Main Thread.
Here Follow some example code:
Your Activity or Fragment
public class MainActivity extends AppCompatActivity
implements UpdateViewCallback { // implement the interface here
private TextView textView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = findViewById(R.id.textView);
// Pass the interface in your Object that makes the async work
final AsyncWork asyncWork = new AsyncWork(this);
// Running
Thread thread = new Thread(asyncWork);
thread.start();
}
/**
* UpdateViewCallback
* #param result
*/
#Override
public void updateView(final String result) {
// Always update View on MainThread or an UI Thread, or else issues will start to happening
this.runOnUiThread(new Runnable() {
public void run() {
// Check if View is null since you're updating in a thread async
if (textView != null) {
textView.setText(result);
}
}
});
}
}
Your Interface:
public interface UpdateViewCallback {
void updateView(String result);
}
Your Object to handle the Async Work:
public class AsyncWork implements Runnable {
private UpdateViewCallback updateViewCallback;
public AsyncWork(UpdateViewCallback updateViewCallback) {
this.updateViewCallback = updateViewCallback;
}
/**
* Async Work here
*/
#Override
public void run() {
// Do some Work and after update using the interface you passed in the constructor
updateViewCallback.updateView("This is a test");
}
}
This question already has answers here:
android auto-refresh listview items
(2 answers)
Closed 4 years ago.
I have an android listview, but I have to relance the application every time that I want to refresh the list. I have two questions, please:
1) How to refresh it automatically?
2) How to do to receive a notification when an item is added to the database?
So it just tests if an item is added, I receive a notification, when I Click on it I will be able to see the list of items.
This is my code:
public class MainActivity extends Activity {
ListView SubjectFullFormListView;
ProgressBar progressBar;
String HttpURL = "http://254.221.325.11/test/Subject.php";
ListAdapter adapter ;
List<Subject> SubjectFullFormList;
EditText editText ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
SubjectFullFormListView = (ListView) findViewById(R.id.SubjectFullFormListView);
editText = (EditText)findViewById(R.id.edittext1);
progressBar = (ProgressBar) findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(this).execute();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subject subject;
SubjectFullFormList = new ArrayList<Subject>();
for (int i = 0; i < jsonArray.length(); i++) {
subject = new Subject();
jsonObject = jsonArray.getJSONObject(i);
subject.Subject_Name = jsonObject.getString("SubjectName");
subject.Subject_Full_Form = jsonObject.getString("SubjectFullForm");
SubjectFullFormList.add(subject);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
SubjectFullFormListView.setVisibility(View.VISIBLE);
adapter = new ListAdapter(SubjectFullFormList, context);
SubjectFullFormListView.setAdapter(adapter);
}
}
}
I find a solution but I don't know how and where to insert it:
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
Thank you.
-> Write a runnable thread which calls the API of the list regularly after some time and on its response change the list in the adapter and call notifydatasetchanged().
-> By using FCM you can get the solution to question 2. When an item is added in DB generate a notification from server side and send it to clients sides and by using pending intent you can show the list when user tap on the notification.
(OR)
-> You can use the real-time DB Like Firebase DB or Realm etc. for this approach. This DB notify you when an item added to the list and you don't need threads to refresh list.
When my device Network Connect, execute AsyncTask.
this AsyncTask is get Public Ip.
asyncTask in MainActivity (inner)
I want asyncTask result (result value is public Ip) value from another class.
How to get public ip from another class?
My source
public class MainActivity extends Activity {
static getAsyncPubIp async = new getAsyncPubIp();
public static final class getAsyncPubIp extends AsyncTask<Void, Void, String> {
String result;
TextView pubView;
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
try {
URL pub = new URL("get public ip domain");
BufferedReader in = new BufferedReader(new InputStreamReader(
pub.openStream()));
String strPub = in.readLine();
result = strPub;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pubView = (TextView) activity.findViewById(R.id.ip);
pubView.setText(result);
async = null;
pubView = null;
}
}
usually, call this asynctask on another class
MainActivity.getAsyncPubIp asyncPub = new MainActivity.getAsyncPubIp();
asyncPub.execute();
but I want only asyncTask result value from another class
How to get this ?
Create a static variable in second activity's java class named SecondClass.java:
public static String public_ip;
Then in your MainActivity:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Add this
SecondClass.public_ip = result;
pubView = (TextView) activity.findViewById(R.id.ip);
pubView.setText(result);
async = null;
pubView = null;
}
I'm Using inner AsyncTask to Calculate the Average from remote DB,
I get the result but
The problem is : The value of Average available only in "onPostExecute" , I want this value to be accessible in "On Create ()" so I can send it to another AsyncTask in the same Activity
public class Place_details extends Activity {
RatingBar PlaceRatingBar;
UserSessionManager session;
String ID;
Double [] Place_rates;
int Total_place_rates;
float Average_place_rates;
// JSON
JSONParser jsonparser;
JSONObject JSONObject;
ProgressDialog ProgressDialog;
JSONArray jsonArray1;
int value;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_details);
PlaceRatingBar = (RatingBar) findViewById (R.id.Place_rating);
jsonparser = new JSONParser();
//Session
session = new UserSessionManager(Place_details.this);
new getPlaceRating().execute() ;
// Here I get 0.0 and not the correct Average
Toast.makeText(Place_details.this, ""+Average_place_rates, Toast.LENGTH_SHORT).show();
} // End Of OnCreate
public class getPlaceRating extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
ProgressDialog = new ProgressDialog(Place_details.this);
ProgressDialog.setTitle("Wait....");
ProgressDialog.setIndeterminate(false);
ProgressDialog.setCancelable(true);
ProgressDialog.show();
}
#Override
protected String doInBackground(String...parma) {
// TODO Auto-generated method stub
List<NameValuePair> list = new ArrayList<NameValuePair>();
// passing place_id value
list.add(new BasicNameValuePair("id",String_Place_id));
try {
JSONObject = jsonparser.makeHttpRequest("http://192.168.1.2/Yourguideapplication/Place_rating2.php", "POST", list);
Log.e("pass 1", "connection success ");
}
catch (Exception e) {
Log.e("Fail 1", "Fail connection");
}
try {
value = JSONObject.getInt("value");
if (value==1){
//Place Rating
jsonArray1 = JSONObject.getJSONArray("Place_rating");
Place_rates = new Double[jsonArray1.length()];
Total_place_rates =0;
for (int i = 0 ; i < jsonArray1.length() ; i++)
{
JSONObject object = jsonArray1.getJSONObject(i);
Place_rates[i] = object.getDouble("Rating_box");
Total_place_rates+= Place_rates[i];
}
} else {
value = 0;
}
} catch (Exception e){
Log.d("ERORR",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (value == 1){
//Place Rating
Average_place_rates = (float) (Total_place_rates/jsonArray1.length());
PlaceRatingBar.setRating((float) Average_place_rates);
} else {
Toast.makeText(Place_details.this, "Error", Toast.LENGTH_LONG).show();
}
ProgressDialog.dismiss();
}
}
}
Thank you
You can create something like
private interface CallbackListener<T> {
void onComputingFinished(T arg);
}
Make your activity implement this interface.
public class Place_details extends Activity implements CallbackListener<String> {
#Override
public void onComputingFinished(String arg) {
//do your stuff here
}
And register it as listener in your AsynTask class (create field and constructor in you AsyncTask class):
public class GetPlaceRating extends AsyncTask<String,String,String>{
private CallbackListener<String> mListener;
public GetPlaceRating(CallbackListener<String> listener) {
mListener = listener;
}
And when starting task
new GetPlaceRating(this).execute() ;
And in onPostExecute call
if (mListener != null) mListener.onComputingFinished(*your arg*);
I used String to replace generic T in this example, hope you understand you can use whatever you want.
EDITED:
If arguments are of the same type you can change signature of interface to:
private interface CallbackListener<T> {
void onComputingFinished(T ...args);
}
And access them as an array: args[0], args[1].
Or just specify what concrete arguments you want to pass, for example String, int and SomeClass:
private interface CallbackListener {
void onComputingFinished(String str, int value, SomeClass obj);
}
I'm trying to parse an XML from a url page. To do so I have used the SAX implementation explained in this IBM example with the Adapter and other changes I got from this article. I've also tried to implement an AsyncTask to do the parsing and show a ProgressDialog but I think this is where my application starts to break down.
I don't really know exactly how to implement the AsyncTask into my code, and I believe my poor implementation is causing my app to force close.
MainActivity:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ListView lv1;
ProgressDialog ShowProgress;
public static ArrayList<MangaItem> MangaItemList = new ArrayList<MangaItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv1 = (ListView) findViewById(R.id.listView1);
ShowProgress = ProgressDialog.show(MainActivity.this, "",
"Loading. Please wait...", true);
//new loadingTask().execute("http://www.mangapanda.com/alphabetical");
new loadFeedTask().execute();
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri
.parse(MangaItemList.get(position).getMangaLink()));
startActivity(intent);
}
});
}
class loadFeedTask extends AsyncTask<String, Void, ArrayList<MangaItem>> {
private String feedUrl;
protected void onPostExecute(String s) {
lv1.setAdapter(new EfficientAdapter(MainActivity.this, MangaItemList));
//new MangaParserTask().execute();
ShowProgress.dismiss();
}
protected ArrayList<MangaItem> doInBackground(String... params) {
ArrayList<MangaItem> ParsedMangaItemList = new ArrayList<MangaItem>();
feedUrl = "http://www.mangapanda.com/alphabetical";
FeedParser parser = new SaxFeedParser(feedUrl);
ParsedMangaItemList = parser.parse();
for (MangaItem mitem : ParsedMangaItemList) {
MangaItemList.add(mitem);
}
return MangaItemList;
}
}
}
How can I properly use AsyncTask so that my parser will return an ArrayList that I can then put into an ArrayAdapter
Improper use of type parameters in subclass (AsyncTask<Params, Progress, Result>). Re-write the AsyncTask sub-class.
class loadFeedTask extends AsyncTask<String, Void, ArrayList<MangaItem>> {
protected void onPostExecute(ArrayList<MangaItem> list) {
lv1.setAdapter(new EfficientAdapter(MainActivity.this, list));
ShowProgress.dismiss();
}
protected ArrayList<MangaItem> doInBackground(String... params) {
ArrayList<MangaItem> list=null;
String feedUrl = "http://www.mangapanda.com/alphabetical";
FeedParser parser = new SaxFeedParser(feedUrl);
list = parser.parse();
MangaItemList=list;
return list;
}
}
use this code
try {
items = new ArrayList<String>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new InputStreamReader(
getUrlData(" url")));
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
Log.i(TAG, "doc started");
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("entry")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
get url data method
public InputStream getUrlData(String url) throws URISyntaxException,
ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
return res.getEntity().getContent();
}