Set Text edittext activity from another class android - android

I'm a newbie android programmer that want to set text from another class
Here is the code:
MainActivity.java
EventHandler eventHandler = new EventHandler();
reader.Events.addEventsListener(eventHandler);
This one another Class but still inside the MainActivity
class EventHandler implements RfidEventsListener {
// Read Event Notification
public void eventReadNotify(RfidReadEvents e){
TagData[] myTags = myReader.Actions.getReadTags(100);
if (myTags != null)
{
for (int index = 0; index < myTags.length; index++)
{
System.out.println("Tag ID " + myTags[index].getTagID());
//I want to settext here
}
}
}
// Status Event Notification
public void eventStatusNotify(RfidStatusEvents e) {
System.out.println("Status Notification: " +
e.StatusEventData.getStatusEventType());
}
}
Thanks.. Regards

You can only manipulate UI elements, when your code is executed on the UI thread.
class EventHandler implements RfidEventsListener {
// Read Event Notification
public void eventReadNotify(RfidReadEvents e){
TagData[] myTags = myReader.Actions.getReadTags(100);
if (myTags != null)
{
for (int index = 0; index < myTags.length; index++)
{
System.out.println("Tag ID " + myTags[index].getTagID());
//I want to settext here
final String myText = myTags[index].getTagID();
runOnUiThread(new Runnable() {
#Override
public void run() {
myEditText.setText(myText);
}
});
}
}
}
// Status Event Notification
public void eventStatusNotify(RfidStatusEvents e) {
System.out.println("Status Notification: " +
e.StatusEventData.getStatusEventType());
}
}

This can be easily achieved by: (tested example)
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
* This class was created by Anthony M Cannon on 16/05/2018.
*/
public class MainActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
EventHandler handler = new EventHandler();
handler.test();
}
class EventHandler {
void test() {
textView.setText("Hello, from EventHandler.");
}
}
}

Related

EditText clears before I use contents

I am trying to implement a WebSocket client in Android Studio.
My code works fine but I'd like to clear the text boxes after the data has been set. When I tried to clear my EditText boxes after the 'SEND' button is clicked I found that they were being cleared before they were being used.
If I use the following code the contents of the text boxes gets sent,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.send);
output = (TextView) findViewById(R.id.output);
client = new OkHttpClient();
add = (EditText) findViewById(R.id.add_str);
cmd = (EditText) findViewById(R.id.cmd_str);
key = (EditText) findViewById(R.id.key_str);
data = (EditText) findViewById(R.id.data_str);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start();
}
});
}
But if I use the following...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.send);
output = (TextView) findViewById(R.id.output);
client = new OkHttpClient();
add = (EditText) findViewById(R.id.add_str);
cmd = (EditText) findViewById(R.id.cmd_str);
key = (EditText) findViewById(R.id.key_str);
data = (EditText) findViewById(R.id.data_str);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start();
add.getText().clear();
cmd.getText().clear();
key.getText().clear();
data.getText().clear();
}
});
}
I just get an empty string sent. How do I stop this? I have tried setting a sent flag that is only set after the text has been sent...
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start();
if (sent){
add.getText().clear();
cmd.getText().clear();
key.getText().clear();
data.getText().clear();
sent = false;
}
}
});
...but the text never gets cleared.
Edit #1: Full MainActivity listing
package qdivision.org.websocketexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public class MainActivity extends AppCompatActivity {
private Button start;
private TextView output;
private OkHttpClient client;
public EditText add;
public EditText cmd;
public EditText key;
public EditText data;
public boolean sent = false;
private final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
#Override
public void onOpen(WebSocket webSocket, Response response) {
String addStr = add.getText().toString();
String cmdStr = cmd.getText().toString();
String keyStr = key.getText().toString();
String dataStr = data.getText().toString();
String dataFrame = "<" + addStr + "," + cmdStr + "," + keyStr + "," + dataStr + ">";
webSocket.send(dataFrame);
webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
sent = true;
}
#Override
public void onMessage(WebSocket webSocket, String text) {
output("Receiving : " + text);
}
#Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("Receiving bytes : " + bytes.hex());
}
#Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
//output("Closing : " + code + " / " + reason);
}
#Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("Error : " + t.getMessage());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.send);
output = (TextView) findViewById(R.id.output);
client = new OkHttpClient();
add = (EditText) findViewById(R.id.add_str);
cmd = (EditText) findViewById(R.id.cmd_str);
key = (EditText) findViewById(R.id.key_str);
data = (EditText) findViewById(R.id.data_str);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start();
/*add.getText().clear();
cmd.getText().clear();
key.getText().clear();
data.getText().clear();*/
}
});
}
private void start() {
Request request = new Request.Builder().url("ws://192.168.1.84:81/").build(); //"ws://echo.websocket.org"
EchoWebSocketListener listener = new EchoWebSocketListener();
WebSocket ws = client.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();
}
private void output(final String txt) {
runOnUiThread(new Runnable() {
#Override
public void run() {
output.setText(output.getText().toString() + "\n\n" + txt);
}
});
}
}
First of all, about the sent flag. If you are using another thread for settings its value, does not mean, this thread has to wait for it to read the value. In the if statement, if it is not true, it will skip the body. So, as soon as start() is called, assuming that start() is running on another thread, this thread will read the next statement and skip the loop.
Try using something like an OnCompleteListener() provided with the API that you are using.
The same logic goes with the editText.getText().clear(). If you are trying to read the text in start() after any HTTP call, the program will not wait for it and execute the remaining statements.
Hope that helps
Since onOpen happens asynchronously, the values that you're trying to pass are already cleared by that time. The simplest way would be to assign the values from your EditTexts to variables and then read them in onOpen. You could also add a constructor to your Websocket implementation that accepts String as a parameter.
Maybe you can try:
data.setText("");
editText.getText().clear();
will clear the text box.

Variable is accessed within inner class, needs to be declared final

I'm trying to make a button compare its value to some other variable. In the onClick method i get an error saying Variable is accessed within inner class, needs to be declared final. The problem is that the variable is supposed to be changed, so i cannot make it final. How can i fix this? Here is my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class GameActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
int partA = 9;
int partB = 9;
int correctAnswer = partA * partB;
int wrongAnswer1 = correctAnswer++;
int wrongAnswer2 = correctAnswer--;
TextView textObjectA = (TextView)findViewById(R.id.textPartA);
TextView textObjectB = (TextView)findViewById(R.id.textPartB);
Button buttonObjectChoice1 = (Button)findViewById(R.id.buttonChoice1);
Button buttonObjectChoice2 = (Button)findViewById(R.id.buttonChoice2);
Button buttonObjectChoice3 = (Button)findViewById(R.id.buttonChoice3);
buttonObjectChoice1.setText("" + correctAnswer);
buttonObjectChoice2.setText("" + wrongAnswer1);
buttonObjectChoice3.setText("" + wrongAnswer2);
buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
if(correctAnswer==answerGiven) {
}
}
});
buttonObjectChoice1.setOnClickListener(this);
buttonObjectChoice1.setOnClickListener(this);
}
public void onClick(View view) {}
}
Two approaches:
Make buttonObjectChoice1 final:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
final Button buttonObjectChoice1 =(Button)findViewById(R.id.buttonChoice1);
...
buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
...
}
});
}
Convert view at runtime:
buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Button btn = (Button)v;
int answerGiven = Integer.parseInt("" + btn.getText());
...
}
});
Advantage of approach 2 is, it will reduce workload of compiler to generate accessor methods to access buttonObjectChoice1 object.
Try to declare the variables as private field of your class and update it accordingly in the method.

I am refreshing listview in every 30 seconds . click of list item error of notifydatasetchanged

Here is my code:
package com.saba.admin.w2track;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import Adapters.VehicleListAdapter;
import Model.UserData;
import Model.VehicleData;
public class DashboardActivity extends AppCompatActivity {
static ArrayList<VehicleData> vehicleArrayList=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayList1=new ArrayList<>();
boolean clearflag=false;
static ArrayList<VehicleData> vehicleArrayListMoving=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListStopped=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListActive=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListInActive=new ArrayList<>();
String acctype;
//static VehicleListAdapter listAdapter;
UserData userData;
TextView txtStopped,txtMoving,txtTotal,txtInactive,txtAlerts;
RelativeLayout moving,alerts,inactive,stopped,total;
boolean doubleBackToExitPressedOnce = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard3);
setView();
getBundleData();
// String acc[]={acctype};
updateVehicles();
}
public void updateVehicles() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
DashboardActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
vehicle v = new vehicle();
v.execute(acctype);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000);
}
public void setView(){
txtStopped=(TextView)findViewById(R.id.txtstopped);
txtMoving=(TextView)findViewById(R.id.txtmoving);
txtAlerts=(TextView)findViewById(R.id.txtalerts);
txtInactive=(TextView)findViewById(R.id.txtinactive);
txtTotal=(TextView)findViewById(R.id.txttotal);
moving=(RelativeLayout)findViewById(R.id.LayoutMoving);
stopped=(RelativeLayout)findViewById(R.id.LayoutStopped);
alerts=(RelativeLayout)findViewById(R.id.LayoutAlerts);
inactive=(RelativeLayout)findViewById(R.id.LayoutInActive);
total=(RelativeLayout)findViewById(R.id.LayoutTotal);
}
public void getBundleData(){
Bundle b = getIntent().getExtras();
if (b != null && b.containsKey("userData"))
{
userData=b.getParcelable("userData");
acctype=b.getString("acctype");
// Log.d("accountid",userData.getAccountId()+" ");
Log.d("userid123..",userData.getUserId()+" ");
Log.d("timediff123..",userData.getTimediff()+" ");
//Log.d("km1..",userData.getMilesPerKms()+" ");
}
}
//vehicle asyncclass in dashboard..which is called in dashboard every 30 sec to get updated data & store in arraylist.
private class vehicle extends AsyncTask<String,String,String> {
private ProgressDialog dialog;
String response="";
private JSONObject res;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
if(!DashboardActivity.this.isFinishing()) {
dialog = new ProgressDialog(DashboardActivity.this);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
// searchBox.setEnabled(false);
dialog.show();
}
if(true) {
vehicleArrayList.clear();
vehicleArrayList1.clear();
vehicleArrayListMoving.clear();
vehicleArrayListStopped.clear();
vehicleArrayListActive.clear();
vehicleArrayListInActive.clear();
Log.d("cleared1111", "cleared ");
clearflag=true;
}
}catch (Exception e){
Log.d("eroror1111", e.toString() + " ");
// Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
try {
JSONObject vehicle_json = new JSONObject();
vehicle_json.put("pAccountId", userData.getUserId());
res = CustomHttpClient.postJsonObject("http://"+params[0]+".w2track.com/api/index.php?cmd=vehicles", vehicle_json,DashboardActivity.this);
String resData=res.getString("ResponseData");
JSONArray array=new JSONArray(resData);
Log.d("1111",array.length()+" ");
for(int i=0;i<array.length();i++){
Log.d("11112","2222");
VehicleData vehicleData=new VehicleData();
JSONObject jsonVehicleObj=new JSONObject(array.get(i).toString());
Log.d("111123", "2222");
if(jsonVehicleObj.getString("vehiclenumber").equals("null") ||jsonVehicleObj.getString("vehiclenumber")==null ){
Log.d("111124","2222");
continue;
// Log.d("11112","2222");
}
vehicleData.setVehicleNumber(jsonVehicleObj.getString("vehiclenumber"));
vehicleData.setPlacename(jsonVehicleObj.getString("location"));
vehicleData.setSpeed(jsonVehicleObj.getString("speed"));
vehicleData.setLandmark(jsonVehicleObj.getString("landmark"));
vehicleData.setIsActive(jsonVehicleObj.getBoolean("isactive"));
vehicleData.setVehicleType(jsonVehicleObj.getString("vehicletype"));
vehicleData.setFuel(jsonVehicleObj.getString("fuel"));
Log.d("fuel11115", vehicleData.getFuel() + " ");
vehicleData.setDept(jsonVehicleObj.getString("department"));
vehicleData.setDivision(jsonVehicleObj.getString("division"));
vehicleData.setIginition(jsonVehicleObj.getString("ignition"));
vehicleData.setLati(jsonVehicleObj.getString("lat"));
vehicleData.setLongi(jsonVehicleObj.getString("lng"));
vehicleData.setOdometer(jsonVehicleObj.getString("odometer"));
vehicleData.setGpsmode(jsonVehicleObj.getString("gpsmode"));
vehicleData.setInnerbattery(jsonVehicleObj.getDouble("inbatt"));
vehicleData.setExtbattery(jsonVehicleObj.getDouble("extbatt"));
vehicleData.setUnitId(jsonVehicleObj.getString("unitid"));
vehicleData.setUnitNo(jsonVehicleObj.getString("unitno"));
vehicleData.setIgnitionTime(jsonVehicleObj.getString("ign_time"));
vehicleData.setDate1(jsonVehicleObj.getString("date"));
vehicleData.setIconImage(jsonVehicleObj.getString("icon"));
vehicleData.setSignal(jsonVehicleObj.getString("signal"));
Log.d("111126", "2222");
if(clearflag) {
vehicleArrayList.add(vehicleData);
vehicleArrayList1.add(vehicleData);
Log.d("111127", "2222");
if (vehicleData.getIginition().equals("Off") && vehicleData.isActive()) {
vehicleArrayListStopped.add(vehicleData);
vehicleArrayListActive.add(vehicleData);
} else if (vehicleData.getIginition().equals("On") && vehicleData.isActive()) {
vehicleArrayListMoving.add(vehicleData);
vehicleArrayListActive.add(vehicleData);
} else if (!vehicleData.isActive()) {
vehicleArrayListInActive.add(vehicleData);
}
}
Log.d("vehicleno1111",vehicleData.getVehicleNumber()+" ");
}
clearflag=false;
// JSONObject jsonObject1=new JSONObject(array.get(0).toString());
// response=jsonObject1.toString();
//Log.d("myresponse",response+" ");
}catch (Exception e){
Log.d("errorrrr1111", e.toString());
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
txtTotal.setText("Total ("+ vehicleArrayList.size()+")");
txtMoving.setText("Moving ("+ vehicleArrayListMoving.size()+")");
txtStopped.setText("Stopped ("+vehicleArrayListStopped.size()+")");
// txtAlerts.setText(jsonObject.getString("TotalActive"));
txtInactive.setText("InActive (" + vehicleArrayListInActive.size() + ")");
if(!DashboardActivity.this.isFinishing()) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
//dashboard activty calls vehicle service every 30 seconds & storing in different arraylist like moving, stopped etc. i am using that arraraylist & settting adapter & calling notifydatasetchanged (every 10 sec) in vehicle activity
VehicleList class
public class VehicleList extends android.support.v4.app.Fragment {
Runnable r;
Timer timer;
TimerTask myTimerTask;
ListView lstVehicle;
EditText searchBox;
static String status;
// Context context;
VehicleListActivityFinal vehicleListActivityFinal;
ImageView img;
static UserData userData;
int accid,timdiff,mile;
String userid,acctype;
VehicleListAdapter listAdapter;
final Handler handler =new Handler() ;
VehicleListActivityFinal vehiclefinal;
}*/
public VehicleList() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("oncreate..", "oncreate..");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_vehicle_list, container, false);
//vehicleArrayList =new ArrayList<VehicleData>();
lstVehicle =(ListView)view.findViewById(R.id.vehicle_listview);
// lstVehicle.requestFocus();
img=(ImageView)view.findViewById(R.id.Imgnodata);
Log.d("createview", "createview");
if (getArguments() != null) {
// Bundle bundle=getArguments();
userid=getArguments().getString("UserID");
acctype=getArguments().getString("acctype");
timdiff=getArguments().getInt("TimeDiff");
status=getArguments().getString("status");
Log.d("arg1111",userid+" ");
Log.d("arg11112",timdiff+" ");
}
else
{
Log.d("insidenull","nullnull");
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
vehicleListActivityFinal=(VehicleListActivityFinal)getActivity();
searchBox=(EditText)vehicleListActivityFinal.findViewById(R.id.searchBox);
Log.d("onactivitycrated..", "activitycreated...");
if(savedInstanceState==null) {
if (CheckInternet.isConnectionAvailable(vehicleListActivityFinal)) {
getVehicleData();
updateVehicleData();
} else {
CheckInternet.showNoInternet(vehicleListActivityFinal);
}
}
Log.d("testtest", vehicleListActivityFinal.test + " ");
lstVehicle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
VehicleData vehicleData = (VehicleData) parent.getAdapter().getItem(position);
Intent intent = new Intent(vehicleListActivityFinal, VehicleDetailActivity.class);
intent.putExtra("vehicleData1", vehicleData);
intent.putExtra("acctype", acctype);
// intent.putExtra()
startActivity(intent);
vehicleListActivityFinal.overridePendingTransition(R.anim.push_in, R.anim.push_out);
}catch (Exception e){
Toast.makeText(vehicleListActivityFinal,e.toString(),Toast.LENGTH_SHORT).show();
}
}
});
searchText();
// updateVehicleData();
// setRetainInstance(true);
}
//method which calls notifydatasetchanged every 10 seconds on vehicle activity
public void updateVehicleData(){
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
vehicleListActivityFinal.runOnUiThread(new Runnable() {
public void run() {
try {
// getVehicleData();
img.setVisibility(View.GONE);
listAdapter.notifyDataSetChanged();
lstVehicle.invalidate();
if (lstVehicle.getAdapter().getCount() == 0) {
img.setVisibility(View.VISIBLE);
Toast.makeText(vehicleListActivityFinal, "empty list..", Toast.LENGTH_SHORT).show();
}
Toast.makeText(vehicleListActivityFinal, "Refreshing Data..", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000);
}
method which sets adapter of vehicle on vehicle activity
public void getVehicleData(){
// lstVehicle.requestFocus();
if(VehicleListActivityFinal.movingStatus.equals("moving")) {
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListMoving,vehicleListActivityFinal);
// Log.d("adapterempty", listAdapter.isEmpty()+" ");
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("total")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayList1,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("inactive")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListInActive,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("stopped")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListStopped,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
// listAdapter.notifyDataSetChanged();
}
else
{
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayList1,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
// listAdapter.notifyDataSetChanged();
}
// lstVehicle.invalidate();
//lstVehicle.requestLayout();
Log.d("postexecute1111", searchBox.isFocused() + " ");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
VehicleListActivityFinal.currentFragment="VehicleList";
}
#Override
public void onDetach() {
super.onDetach();
Log.d("detach1", "detach");
}
#Override
public void onResume() {
super.onResume();
Log.d("onresume", "onresume");
}
public void searchText() {
// lstVehicle.setAdapter(listAdapter);
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Toast.makeText(vehicleListActivityFinal,"beforetextchanged",Toast.LENGTH_SHORT).show();
}
#Override
public void onTextChanged(CharSequence s1, int start, int before, int count) {
listAdapter.getFilter().filter(s1.toString());
// Toast.makeText(getActivity(),"ontextchanged",Toast.LENGTH_SHORT).show();
//lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
//Toast.makeText(getActivity(),"afterrtextchanged",Toast.LENGTH_SHORT).show();
}
});
}
}

Seekbar not progressing inside Cursor Adaptor

I have a seekbar in my cursor adaptor, code below, when I am playing a song I am supposed to increment it, I have a separate utility class, but the problem is the seekbar is not progressing at all, even if I hard code it, but the log cat is showing my calculations fine which I commented in my run handler.
When I am sliding the seekbar "onStartTrackingTouch" and "onStopTrackingTouch" is responding fine with proper integer value. Music is played via a service which is working fine too.
Where am I going wrong ?
package com.kavayah.spotifystreamer;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.Image;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.kavayah.spotifystreamer.data.SpotifyContract;
import com.squareup.okhttp.Call;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class TrackPlayerAdapter extends CursorAdapter {
private final static String LOG_TAG = TrackPlayerAdapter.class.getSimpleName();
private static Context context;
private SpotifyMusicService mSpotifyMusicService;
private Intent playIntent;
private boolean iSMusicServiceBoundToActivity = false;
private static ServiceConnection spotifyMusicConnection;
private Handler mDurationHandler = new Handler();
private SeekBar mSpotifyMusicSeekBar;
private static int mDuration_ms;
private Utility utils;
//declare a interface which will communicate with the fragment
Callback callback;
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
public void playItemSelected();
public void nextItemSelected(Uri trackUri);
}
/*
public TrackPlayerAdapter(Context context, Cursor c, int flags){
super(context, c, flags);
trackPlayerActivityFragment = new TrackPlayerActivityFragment();
}
*/
public TrackPlayerAdapter(Context context, Cursor c, int flags, Callback callback) {
super(context, c, flags);
this.context = context;
this.callback = callback;
utils = new Utility();
//connect to the service
spotifyMusicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
SpotifyMusicService.SpotifyMusicBinder binder = (SpotifyMusicService.SpotifyMusicBinder) service;
//get the service
mSpotifyMusicService = binder.getService();
iSMusicServiceBoundToActivity = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i(LOG_TAG, ">>>>> Music service disconnected.");
iSMusicServiceBoundToActivity = false;
}
};
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
if (playIntent == null) {
playIntent = new Intent(context, SpotifyMusicService.class);
context.bindService(playIntent, spotifyMusicConnection, context.BIND_AUTO_CREATE);
context.startService(playIntent);
}
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
layoutId = R.layout.list_item_player;
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
TrackPlayerViewHolder trackPlayerViewHolder = new TrackPlayerViewHolder(view);
view.setTag(trackPlayerViewHolder);
return view;
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
TrackPlayerViewHolder trackPlayerViewHolder = (TrackPlayerViewHolder) view.getTag();
int viewType = getItemViewType(cursor.getPosition());
String artistIcon = cursor.getString(TrackPlayerActivityFragment.COL_ALBUM_ICON2);
Log.i(LOG_TAG, ">>>>> TrackPlayerActivityFragment.COL_ALBUM_ICON2 " + artistIcon);
if (artistIcon != null && !artistIcon.equals("")) {
Picasso.with(context)
.load(artistIcon)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.tag(context)
.into(trackPlayerViewHolder.iconView);
} else {
trackPlayerViewHolder.iconView.setImageResource(0);
}
String artistName = cursor.getString(TrackPlayerActivityFragment.COL_ARTIST_NAME);
trackPlayerViewHolder.artistNameView.setText(artistName);
String albumName = cursor.getString(TrackPlayerActivityFragment.COL_ALBUM_NAME);
trackPlayerViewHolder.albumNameView.setText(albumName);
String trackName = cursor.getString(TrackPlayerActivityFragment.COL_TRACK_NAME);
trackPlayerViewHolder.trackNameView.setText(trackName);
String duration = String.valueOf(cursor.getInt(TrackPlayerActivityFragment.COL_DURATION_MS));
trackPlayerViewHolder.durationView.setText(duration);
//implement the OnSeekBarChangeListener interface methods
mSpotifyMusicSeekBar = (SeekBar) view.findViewById(R.id.musicSeekBar);
mSpotifyMusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
Log.i("onProgressChanged", "" + progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
Log.i("onStartTrackingTouch",
"" + seekBar.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
Log.i("onStopTrackingTouch",
"" + seekBar.getProgress());
mSpotifyMusicService.seek(seekBar.getProgress());
}
});
final ToggleButton play_button = (ToggleButton) view.findViewById(R.id.media_play);
play_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
Log.i(LOG_TAG, ">>>>> play button click - " + cursor.getInt(TrackPlayerActivityFragment.COL_PRIMARY_TRACK_ID));
//((Callback)trackPlayerActivityFragment).onItemSelected();
callback.playItemSelected();
mSpotifyMusicService.setSongURL(cursor.getString(TrackPlayerActivityFragment.COL_PREVIEW_URL));
mSpotifyMusicService.playSong(cursor.getString(TrackPlayerActivityFragment.COL_TRACK_NAME));
mDuration_ms = cursor.getInt(TrackPlayerActivityFragment.COL_DURATION_MS);
mSpotifyMusicSeekBar.setProgress(0);
mSpotifyMusicSeekBar.setMax(100);
updateSeekbarProgress();
}
}
});
final ImageButton next_button = (ImageButton) view.findViewById(R.id.media_next);
next_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
Integer nextSongId = cursor.getInt(TrackPlayerActivityFragment.COL_PRIMARY_TRACK_ID);
Log.i(LOG_TAG, ">>>>> next button click - " + ++nextSongId);
//check to see if query return null, means it has reached the end of the
// tracks list, stay of the last song even if the user presses next key
Uri nextTrackUri = SpotifyContract.TrackEntry.buildTrackUri(nextSongId);
Cursor cur = context.getContentResolver().query(nextTrackUri, null, null, null, null);
if (cur.getCount() < 1) {
//--nextSongId;
//nextTrackUri = SpotifyContract.TrackEntry.buildTrackUri(nextSongId);
} else {
callback.nextItemSelected(nextTrackUri);
}
if(cur.getCount() > 0){
cur.moveToFirst();
mSpotifyMusicService.setSongURL(cur.getString(TrackPlayerActivityFragment.COL_PREVIEW_URL));
mSpotifyMusicService.playSong(cur.getString(TrackPlayerActivityFragment.COL_TRACK_NAME));
}
//Intent intent = new Intent(context, TrackPlayerActivity.class);
//intent.setData(SpotifyContract.TrackEntry.buildTrackUri(nextSongId));
//context.startActivity(intent);
}
}
});
final ImageButton prev_button = (ImageButton) view.findViewById(R.id.media_prev);
prev_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
Integer prevSongId = cursor.getInt(TrackPlayerActivityFragment.COL_PRIMARY_TRACK_ID);
Log.i(LOG_TAG, ">>>>> prev button click - " + --prevSongId);
//check if the query returns null, means it has reached the beginning
//increment the track id, else it will show null.
Uri prevTrackUri = SpotifyContract.TrackEntry.buildTrackUri(prevSongId);
Cursor cur = context.getContentResolver().query(prevTrackUri, null, null, null, null);
if (cur.getCount() < 1) {
//++prevSongId;
//prevTrackUri = SpotifyContract.TrackEntry.buildTrackUri(prevSongId);
} else {
callback.nextItemSelected(prevTrackUri);
}
if (cur.getCount() > 0) {
cur.moveToFirst();
mSpotifyMusicService.setSongURL(cur.getString(TrackPlayerActivityFragment.COL_PREVIEW_URL));
mSpotifyMusicService.playSong(cur.getString(TrackPlayerActivityFragment.COL_TRACK_NAME));
}
}
}
});
}
public void updateSeekbarProgress(){
mDurationHandler.postDelayed(mUpdateSeekbarTime, 100);
}
private Runnable mUpdateSeekbarTime = new Runnable() {
public void run() {
//long totalDuration = mSpotifyMusicService.getDur();
long currentDuration = mSpotifyMusicService.getPosn();
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, mDuration_ms));
//Log.i(LOG_TAG, " Seekbar position : " + progress);
mSpotifyMusicSeekBar.setProgress(progress);
mDurationHandler.postDelayed(this, 100);
}
};
}
The problem is that you have only one Adapter Object and only one mSpotifyMusicSeekBar variable and bind() is called multiple times, each time for every visible list item.
By the time the Handler is called, the seekBar reference is changed so you never see the progress because some other seekbar is getting updated.
I tried a sample of your code. And here it is - and - seek bar is getting updated as expected:
public class TrackPlayerAdapter extends RecyclerView.Adapter<TrackPlayerAdapter.MyHolder>
{
private final static String TAG = TrackPlayerAdapter.class.getSimpleName();
private Context context;
public TrackPlayerAdapter(Context context)
{
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
LinearLayout container = new LinearLayout(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams
.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
SeekBar seekbar = new SeekBar(context);
seekbar.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams
.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Button button = new Button(viewGroup.getContext());
button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams
.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
button.setText("play");
seekbar.setTag("SEEKBAR");
button.setTag("BUTTON");
container.addView(seekbar);
container.addView(button);
return new MyHolder(container);
}
#Override
public void onBindViewHolder(MyHolder myHolder, int i)
{
myHolder.bind();
}
/**
* Get the row id associated with the specified position in the list.
*
* #param position The position of the item within the adapter's data set whose row id we want.
* #return The id of the item at the specified position.
*/
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemCount()
{
return 3;
}
public static class MyHolder extends RecyclerView.ViewHolder
{
private Handler mDurationHandler = new Handler();
private SeekBar mSpotifyMusicSeekBar;
private Button mToggleButton;
int totalProgress = 0;
public void updateSeekbarProgress()
{
mDurationHandler.postDelayed(mUpdateSeekbarTime, 100);
}
private Runnable mUpdateSeekbarTime = new Runnable()
{
public void run()
{
if(totalProgress <= 10000)
{
totalProgress += 100;
int progress = (int) ((float) totalProgress / 100);
mSpotifyMusicSeekBar.setProgress(progress);
mDurationHandler.postDelayed(this, 1000);
}
}
};
public MyHolder(View itemView)
{
super(itemView);
mSpotifyMusicSeekBar = (SeekBar)itemView.findViewWithTag("SEEKBAR");
mToggleButton = (Button) itemView.findViewWithTag("BUTTON");
}
public void bind()
{
mSpotifyMusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
Log.i(TAG, "onProgressChanged::" + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
// TODO Auto-generated method stub
Log.i(TAG, "onStartTrackingTouch::" + seekBar.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
// TODO Auto-generated method stub
Log.i(TAG, "onStopTrackingTouch" + seekBar.getProgress());
}
});
mToggleButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
mSpotifyMusicSeekBar.setProgress(0);
mSpotifyMusicSeekBar.setMax(100);
updateSeekbarProgress();
}
});
}
}
}

Why do I get a "cannot be resolved to a type" error when trying to refer to a class - android

This is the code I have, I am trying to have multiple images slide across the screen. The specific error shows up for "ThisClass" in the "TimerTask thisTimerTask = new ThisClass();" line. I appreciate any feed back available
package your.package2.namespace2;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.widget.Button;
import android.widget.ImageView;
#SuppressWarnings("unused")
public class ChangeuppicksActivity extends Activity {
Display thisDisplay;
ImageView img, img4, img5, img7;
Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
thisDisplay = getWindowManager().getDefaultDisplay();
TimerTask thisTimerTask = new ThisClass();
timer = new Timer();
timer.scheduleAtFixedRate(thisTimerTask, 1000, 16);
img = (ImageView) findViewById(R.id.pic1);
img4 = (ImageView) findViewById(R.id.pic4);
img5 = (ImageView) findViewById(R.id.pic5);
img7 = (ImageView) findViewById(R.id.pic7);
}
public void doSomething() {
int slideToPOS_X = (img.getLeft() - 7);
if (slideToPOS_X <= -img.getWidth()) {
int slideToPOS_X2 = (img4.getLeft() - 5);
if (slideToPOS_X2 <= -img4.getWidth()) {
slideToPOS_X2 = thisDisplay.getWidth();
}
img.layout(slideToPOS_X, 0, (slideToPOS_X + img.getWidth()), (0 + img.getHeight()));;
img4.layout(slideToPOS_X2, 0, (slideToPOS_X2 + img4.getWidth()), (0 + img4.getHeight()));
}
class ThisClass extends TimerTask {
#Override
public void run() {
ChangeuppicksActivity.this.runOnUiThread(new Runnable() {
public void run() {
doSomething();
}
});
}
}
}
}
Not sure if this is the root cause of your problem, but looks like you have one too many close brackets at the bottom of your class. Try removing one of the '}' at the bottom of the class to see if that makes your compiler any happier.
You are also missing a close bracket in your doSomething() method. I may have broken your logic, but try replacing the bottom with this:
public void doSomething() {
int slideToPOS_X = (img.getLeft() - 7);
if (slideToPOS_X <= -img.getWidth()) {
int slideToPOS_X2 = (img4.getLeft() - 5);
}
if (slideToPOS_X2 <= -img4.getWidth()) {
slideToPOS_X2 = thisDisplay.getWidth();
}
img.layout(slideToPOS_X, 0, (slideToPOS_X + img.getWidth()), (0 + img.getHeight()));;
img4.layout(slideToPOS_X2, 0, (slideToPOS_X2 + img4.getWidth()), (0 + img4.getHeight()));
}
class ThisClass extends TimerTask {
#Override
public void run() {
ChangeuppicksActivity.this.runOnUiThread(new Runnable() {
public void run() {
doSomething();
}
});
}
}
}
One of the close brackets at the end is superfluous and I think there should be an additional bracket closing the doSomething method. As it stands, ThisClass is defined inside the doSomething method - the second line of doSomething has an open bracket which isn't closed until the end of the class, which is hard to see as the code is not indented after the opening bracket.
Move ThisClass definition outside of the doSomething() method.

Categories

Resources