Update in real time GraphicalView of AChartEngine - android

I want to have an app that shows me a textview and a line chart dynamically updated with the values that I receive from a range sensor.
I used a modified TextView which manages the messages and it works well.
I tried to do the same thing with a GraphicalView from AChartEngine, but the Chart doesn't change with the arrival of new messages.
Here is my code, any suggestion or advice?
public class NxtActivity extends RosActivity{
private XYSeries mCurrentSeries = new XYSeries("range data series");
private XYSeriesRenderer mCurrentRenderer = new XYSeriesRenderer();
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
private LineChart linec;
private Canvas canvas = new Canvas();
private RosChartView<std_msgs.String> rdrawview;
private RosTextView<std_msgs.String> rosTextView;
private Android_Talker talker;
private java.net.URI master_uri;
//costruttore
public NxtActivity() {
// The RosActivity constructor configures the notification title and ticker
// messages.
super("Pubsub Tutorial mod", "Pubsub Tutorial mod");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nxt);
//setto i parametri del renederer relativo alla singola seria
mCurrentRenderer.setPointStyle(PointStyle.CIRCLE);
mCurrentRenderer.setFillPoints(true);
mCurrentRenderer.setLineWidth(2);
//setto i parametri del renderer globale
mRenderer.addSeriesRenderer(mCurrentRenderer);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setAxisTitleTextSize(16);
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setPointSize(10);
mRenderer.setXTitle("time");
mRenderer.setYTitle("ranges");
//setto la serie
mCurrentSeries.add(1,1);
//setto il dataset
mDataset.addSeries(mCurrentSeries);
//setto LineChart
linec = new LineChart(mDataset,mRenderer);
//inizializzo RosChartView
rdrawview=new RosChartView<std_msgs.String>(this,linec,canvas);
rdrawview.setTopicName("chatter_nxt");
rdrawview.setMessageType(std_msgs.String._TYPE);
rdrawview.setMessageToStringCallable(new MessageCallable<String, std_msgs.String>() {
#Override
public String call(std_msgs.String message) {
return message.getData();
}
});
//assegno RosChartView al Layout corrispondente
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
layout.addView(rdrawview, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
rdrawview.repaint();
//rdrawview.setup(3,3);
rosTextView = (RosTextView<std_msgs.String>) findViewById(R.id.text1);
rosTextView.setTopicName("chatter_nxt");
rosTextView.setMessageType(std_msgs.String._TYPE);
rosTextView.setMessageToStringCallable(new MessageCallable<String, std_msgs.String>() {
#Override
public String call(std_msgs.String message) {
return message.getData();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_nxt, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//case android.R.id.home:
// NavUtils.navigateUpFromSameTask(this);
// return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void init(NodeMainExecutor nodeMainExecutor) {
talker = new Android_Talker();
NodeConfiguration nodeConfiguration = NodeConfiguration.newPrivate();
// At this point, the user has already been prompted to either enter the URI
// of a master to use or to start a master locally.
try {
master_uri = new java.net.URI("http://150.145.11.98:11311");
nodeConfiguration.setMasterUri(master_uri);
}
catch(URISyntaxException e){
System.out.println("URI is a malformed URL");
}
rdrawview.setup(3,3);
nodeConfiguration.setMasterUri(master_uri);
nodeMainExecutor.execute(talker, nodeConfiguration);
// The RosTextView is also a NodeMain that must be executed in order to
// start displaying incoming messages.
nodeMainExecutor.execute(rosTextView, nodeConfiguration);
nodeMainExecutor.execute(rdrawview, nodeConfiguration);
}
}
Modified textview:
public class RosTextView<T> extends TextView implements NodeMain {
private String topicName;
private String messageType;
private int count=0;
private MessageCallable<String, T> callable;
public RosTextView(Context context) {
super(context);
}
public RosTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RosTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public void setMessageToStringCallable(MessageCallable<String, T> callable) {
this.callable = callable;
}
#Override
public GraphName getDefaultNodeName() {
return GraphName.of("android_gingerbread/ros_text_view");
}
#Override
public void onStart(ConnectedNode connectedNode) {
Subscriber<T> subscriber = connectedNode.newSubscriber(topicName, messageType);
subscriber.addMessageListener(new MessageListener<T>() {
#Override
public void onNewMessage(final T message) {
if (callable != null) {
post(new Runnable() {
#Override
public void run() {
setText(callable.call(message));
count++;
if((count%2)==0){setTextColor(Color.RED);}
else{setTextColor(Color.BLUE);}
}
});
} else {
post(new Runnable() {
#Override
public void run() {
setText(message.toString());
}
});
}
postInvalidate();
}
});
}
#Override
public void onShutdown(Node node) {
}
#Override
public void onShutdownComplete(Node node) {
}
#Override
public void onError(Node node, Throwable throwable) {
}
}
Modifed graphicalview:
public class RosChartView<T> extends GraphicalView implements NodeMain {
//---------
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
private XYSeries mCurrentSeries = new XYSeries("range data series");
private int x;
private int y;
Context context;
Canvas canvas;
//---------
private String topicName;
private String messageType;
private int count=0;
private MessageCallable<String, T> callable;
public RosChartView(Context context, LineChart xyc, Canvas canvas_) {
super(context,xyc);
this.context=context;
mDataset = xyc.getDataset();
mRenderer = xyc.getRenderer();
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(100);
x=0;
y=0;
canvas=canvas_;
}
public RosChartView(Context context, AttributeSet attrs, LineChart xyc) {
super(context, xyc);
mDataset = xyc.getDataset();
mRenderer = xyc.getRenderer();
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(100);
x=0;
y=0;
}
public RosChartView(Context context, AttributeSet attrs, int defStyle, LineChart xyc) {
super(context, xyc);
mDataset = xyc.getDataset();
mRenderer = xyc.getRenderer();
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(100);
x=0;
y=0;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public void setMessageToStringCallable(MessageCallable<String, T> callable) {
this.callable = callable;
}
#Override
public GraphName getDefaultNodeName() {
return GraphName.of("android_gingerbread/ros_text_view");
}
#Override
public void onStart(ConnectedNode connectedNode) {
Subscriber<T> subscriber = connectedNode.newSubscriber(topicName, messageType);
subscriber.addMessageListener(new MessageListener<T>() {
#Override
public void onNewMessage(final T message) {
if (callable != null) {
post(new Runnable() {
#Override
public void run() {
count++;
x=count;
y=Integer.parseInt(callable.call(message));
XYSeries series=new XYSeries("new_series");
series=mCurrentSeries;
series.add(2,2);
mDataset.removeSeries(mCurrentSeries);
mCurrentSeries=series;
mDataset.addSeries(mCurrentSeries);
repaint();
}
});
} else {
post(new Runnable() {
#Override
public void run() {
count++;
x=count;
y=Integer.parseInt(message.toString());
mCurrentSeries.add(x,y);
}
});
}
postInvalidate();
}
});
}
#Override
public void onShutdown(Node node) {
}
#Override
public void onShutdownComplete(Node node) {
}
#Override
public void onError(Node node, Throwable throwable) {
}
public void setup(double x,double y)
{
mCurrentSeries.add(x,y);
this.repaint();
}
}
layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<org.ros.android.view.RosTextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dip"
/>
<LinearLayout
android:id="#+id/chart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="#id/text1"
android:orientation="horizontal" />
</RelativeLayout>

When a message is received, you do the following:
XYSeries series=new XYSeries("new_series");
series=mCurrentSeries;
series.add(2,2);
mDataset.removeSeries(mCurrentSeries);
mCurrentSeries=series;
mDataset.addSeries(mCurrentSeries);
This means that you create a new series, then the reference to the current series is given to the variable that was previously created as new series then you add a point at location 2, 2 then you remove the series and add it back. This is totally wrong.
The following should be sufficient:
mCurrentSeries.add(x, y); // NOT 2, 2

Related

Hello, please tell me how to send ArrayList to another activity

I tried all the possible options that I just found.
I can’t send ArrayList to another activity via the Parcelable interface.
To implement a media player
String format information it sends.
I would be very grateful, maybe there are some other options. This is the first time I'm asking a question here
Here is my activity that I use to send, the code is still very raw
public class MainActivity extends AppCompatActivity {
ScheduledExecutorService scheduledExecutorService;
public MediaPlayer mediaPlayer;
private SeekBar seekBar;
private ImageView btn_Play;
private ImageView btn_Next;
private ImageView btn_Pre;
private TextView setCurrentDuration, setTotalDuration;
private ArrayList<SoundInfo> audioList = new ArrayList<>();
SoundAdapter adapter = new SoundAdapter();
public Handler handler = new Handler();
AudioEffect audioEffect;
private int currentPosition = 0;
private SoundInfo soundInfo = new SoundInfo(this);
SoundEffects soundEffects;
boolean mediaPauseStat = false;
Context context;
PageFragmentOne pageFragmentOne;
//public MainActivity(PageFragmentOne pageFragmentOne) {
// this.pageFragmentOne = pageFragmentOne;
//}
MediaManager mediaManager = new MediaManager(this, adapter, audioList);
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Старт сервиса
//Intent i = new Intent(this, MediaPlaybackService.class);
//i.putExtra("play", "письмо от главного активити");
//startService(i);
//mediaManager.LoadSounds();
/**
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
**/
////////////////////////////////////////////////////////////////////////////////////////////
setCurrentDuration = findViewById(R.id.current_Duration);
setTotalDuration = findViewById(R.id.total_Duration);
seekBar = findViewById(R.id.seekBar);
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(this));
// Оформление отображения адаптера
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayout.VERTICAL);
dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.list_item_divider, null));
list.addItemDecoration(dividerItemDecoration);
///////////////////////////////////////////////
soundInfo.setMassive(audioList);
adapter.setOnItemClickListener(new SoundAdapter.OnItemClickListener() {
#Override
public void onClick(View v, final SoundInfo obj, final int position, final ImageView onNext) {
final SoundInfo path = audioList.get(position);
String audioPath = obj.getData();
prepareMedia(position);
// Задаем текующию позицию трека
currentPosition = position;
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
// Всегда должен быть после старта плеера, что бы не вылазило 238
updateProgressBar();
//seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
btn_Play.setImageResource(R.drawable.btn_pause);
}
});
// Перемотка аудио
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Слишком часто обновляет
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(false);
soundInfo.setMediaRewind(false);
mediaPlayer.pause();
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mediaPlayer.seekTo(seekBar.getProgress());
return false;
}
});
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(true);
//soundInfo.setMediaRewind(true);
mediaPlayer.start();
}
}
});
// Кнопка проигрывания и паузы
btn_Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mediaPlayer.isPlaying()) {
onPlay();
} else {
onPaused();
}
}
});
// Следующий трек
btn_Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onNext();
}
});
// Предыдущий трек
btn_Pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPre();
}
});
}
});
init();
}
private MyBroadcastReceiver myReceiver;
#Override
public void onResume() {
super.onResume();
myReceiver = new MyBroadcastReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
if (myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// String yourValue = b.getString("ser");
Bundle bundle = intent.getExtras();
}
}
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
//Intent i = new Intent(MainActivity.this, MediaPlaybackService.class);
//startService(i);
////////////////////////////////////////////////////////////////////////////////////////////
}
public void init() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Разрешение не предоставляется
// Должны ли мы показать объяснение?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Показать объяснение пользователю * асинхронно* -- не блокировать
// этот поток ждет ответа пользователя! После пользователя
// увидев объяснение, попробуйте еще раз запросить разрешение.
} else {
// Никаких объяснений не требуется; запросить разрешение
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.RECORD_AUDIO},
101);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS является
// app-определенная константа int. Метод обратного вызова получает
// результат запроса.
}
} else {
// Разрешение уже предоставлено
//loadSounds();
mediaManager.LoadSounds();
}
//bPlayPause = findViewById(R.id.bPlayPause);
//lv = (ListView) findViewById(R.id.lvPlayList);
btn_Play = findViewById(R.id.btn_Play);
btn_Next = findViewById(R.id.btn_Next);
btn_Pre = findViewById(R.id.btn_Pre);
}
Here is my SoundInfo
public class SoundInfo implements Parcelable {
private String data, artist, title;
private Context context;
private String pathData;
public SoundInfo(MainActivity context) {
this.context = context;
}
public SoundInfo() {
}
public SoundInfo(MainMediaPlayList context) {
this.context = context;
}
public SoundInfo(MediaPlaybackService mediaPlaybackService, String star) {
this.context = mediaPlaybackService;
this.star = star;
}
protected SoundInfo(Parcel in) {
data = in.readString();
artist = in.readString();
title = in.readString();
pathData = in.readString();
mediaPauseStat = in.readByte() != 0;
ismediaRewind = in.readByte() != 0;
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
star = in.readString();
}
public static final Creator<SoundInfo> CREATOR = new Creator<SoundInfo>() {
#Override
public SoundInfo createFromParcel(Parcel in) {
return new SoundInfo(in);
}
#Override
public SoundInfo[] newArray(int size) {
return new SoundInfo[size];
}
};
public void SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public String getData() {
return data;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public void setData(String artist) {
this.data = data;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void setTitle(String title) {
this.title = title;
}
public void setpathData(String pathData) {
this.pathData = pathData;
}
public String getpathData() {
return pathData;
}
// Запись в память для отображения времени
boolean mediaPauseStat = true;
boolean ismediaRewind = true;
public void setMediaPauseStat(boolean mediaPauseStat) {
this.mediaPauseStat = mediaPauseStat;
}
public boolean getMediaPauseStat() {
return mediaPauseStat;
}
public void setMediaRewind(boolean isMediaRewind) {
this.ismediaRewind = ismediaRewind;
}
public boolean getMediaRewind() {
return ismediaRewind;
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
// Массив
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
public ArrayList<SoundInfo> getMassive() {
return audioList;
}
public void setMassive(ArrayList<SoundInfo> audioList) {
this.audioList = audioList;
}
private String star;
public String getStar() {
return star;
}
public void setStar(String star) {
this.star = star;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(data);
dest.writeString(artist);
dest.writeString(title);
dest.writeString(pathData);
dest.writeByte((byte) (mediaPauseStat ? 1 : 0));
dest.writeByte((byte) (ismediaRewind ? 1 : 0));
dest.writeTypedList(audioList);
dest.writeString(star);
}
}
Here is my adater which I use
public class SoundAdapter extends RecyclerView.Adapter<SoundAdapter.ViewHolder> {
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
Context context;
//private String[] items;
private OnItemClickListener onItemClickListener;
public void setItems(Context context, ArrayList<SoundInfo> audioList) {
this.context = context;
this.audioList = audioList;
//audioList.addAll(items);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_audio, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(audioList.get(position));
holder.clickFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final SoundInfo path = audioList.get(position);
onItemClickListener.onClick(view, path, position, holder.onNext);
}
});
}
#Override
public int getItemCount() {
return audioList == null ? 0 : audioList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView data, title, artist;
private ImageView onNext;
private View clickFile;
ViewHolder(View view) {
super(view);
title = view.findViewById(R.id.tvSoundTitle);
artist = view.findViewById(R.id.tvSoundArtist);
clickFile = view.findViewById(R.id.clickFile);
//data = view.findViewById(R.id.item_title);
//onNext = view.findViewById(R.id.imageNext);
}
public void bind(SoundInfo soundInfo) {
title.setText(soundInfo.getTitle());
artist.setText(soundInfo.getArtist());
//clickFile.setText(soundInfo.getData());
}
}
// Передача данных в основной активити
public interface OnItemClickListener {
void onClick(View view, SoundInfo obj, int position, ImageView onNext);
}
}
Here is the second activity that an ArrayList gets.
Bundle bundle = getIntent().getExtras();
ArrayList<SoundInfo> audioList = bundle.getParcelableArrayList("MEDIA_MASSIVE");
adapter.setItems(MainMediaPlayList.this, audioList);
adapter.notifyDataSetChanged();
// загрузка адаптера
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(MainMediaPlayList.this));
When you open a new activity, the application crashes
does not display any errors in the log, the problem is as I understand that intent can not find
audioList as it seems to me
If I remove the method everything loads
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
Here I took off the launch log, it may somehow help
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: get the overscroller config
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication D/HwFrameworkSecurityPartsFactory: HwFrameworkSecurityPartsFactory in.
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication I/HwFrameworkSecurityPartsFactory: add HwFrameworkSecurityPartsFactory to memory.
2020-03-08 18:09:43.506 15730-15730/com.shimmer.myapplication D/ActivityThread: add activity client record, r= ActivityRecord{e3185e4 token=android.os.BinderProxy#837d3d7 {com.shimmer.myapplication/com.shimmer.myapplication.MainActivity}} token= android.os.BinderProxy#837d3d7
I don't think so, You can send an ArrayList like this.
I recommend you sending Class instead of sending an Arraylist.
So, just create a class like AudiolistHolder and put your ArrayList inside this class and don't forget to implement Parcelable interface for this class, too, and send this class between activities this should solve your problem. I always use this way.
EDIT:
You can use this to send your data
Intent intent2 = new Intent(this, MainMediaPlayList.class);
MassiveAudioList m = new MassiveAudioList(audioList);
intent2.putExtra("MEDIA_MASSIVE”, m);
startActivity(intent2);
and you can use this in your second activity to retrieve data
MassiveAudioList massiveAudio=getIntent().getParcelableExtra("MEDIA_MASSIVE");
ArrayList<SoundInfo> audioList = massiveAudio.getMassiveAudioList();
Have you tried like this with arraylist
I think it can be,
In MainActivity.java
ArrayList<String> audioList= new ArrayList<>();
audioList.add("ChipThrills");
Intent i = new Intent(MainActivity.this, Secondactivity.class);
i.putExtra("Musickey", audioList);
startActivity(i);
In SecondActivity.java
ArrayList<String> audioList = (ArrayList<String>) getIntent().getSerializableExtra("Musickey");
I am writing to you here because I did not understand how to add code to the comment
And how do I extract data by adding it to an array. If of course I did the right thing, I'm new to this field. Thanks.
public class MassiveAudioList implements Parcelable {
private ArrayList<SoundInfo> audioList = new ArrayList<>();
private Context context;
public MassiveAudioList(Context context) {
this.context = context;
}
public MassiveAudioList(ArrayList audioList) {
this.audioList = audioList;
}
protected MassiveAudioList(Parcel in) {
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
}
public static final Creator<MassiveAudioList> CREATOR = new Creator<MassiveAudioList>() {
#Override
public MassiveAudioList createFromParcel(Parcel in) {
return new MassiveAudioList(in);
}
#Override
public MassiveAudioList[] newArray(int size) {
return new MassiveAudioList[size];
}
};
public ArrayList<SoundInfo> getMassiveAudioList() {
return audioList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(audioList);
}
}
public void onMainMediaPlayList(View view) {
Log.d("TAG", "soundinfo" + soundInfo.getData());
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
massiveAudioList = new MassiveAudioList(this);
MassiveAudioList m = new MassiveAudioList(audioList);
Bundle bundle = new Bundle();
bundle.putParcelable("MEDIA_MASSIVE", m);
intent2.putExtras(bundle);
startActivity(intent2);
}

Button's click listener in listiview not working which extends Fragment

When the listview in Activity,the button works,as long as my class extends Fragment ,there nothing happen.
public class OnlineNopaymentInsuranceFragment extends Fragment implements OnItemClickListener,OnItemSelectedListener,OnListViewListener,OnClickListener {
private ScrollListView MainView;
private BasicAdapter Adapter;
private Integer Step=3;
private Integer Start=0;
private Integer End=Step;
private Handler handler,handler2;
//private List<Map<String, Object>> Lists;
private DataTable Table;
public static String SelectCode="";
private static final int OVER = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_online_insurance,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.MainView=(ScrollListView)getView().findViewById(R.id.contractlistView1);
this.MainView.setOnItemClickListener(this);
this.MainView.setOnItemSelectedListener(this);
this.MainView.setPullLoadEnable(true);
this.MainView.setXListViewListener(this);
handler2 = new Handler();
Control.StartDialog(getActivity());
new Thread(new Runnable() {
public void run() {
Looper.prepare();
handler2.post(runSetList);
handler1.sendEmptyMessage(1);
Looper.loop();
}
}).start();
this.MainView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getActivity(), "nothing", Toast.LENGTH_LONG).show();
}
});
}
private void SetList(){
Start=0;
End=3;
this.Table = new DataTable(getActivity(),"newcontracta");
this.Table.Load("AgentCode="+OnlineNopaymentInsuranceFragment.SelectCode+"&Start=0&End="+Step);
if(Table.GetRowCount()>0){
this.MainView.setVisibility(0);
this.StartData(this.Table.GetList(),R.layout.userlistitem3);
}else{
this.MainView.setVisibility(8);
TextView NullView=(TextView) getView().findViewById(R.id.listViewNull1);
NullView.setVisibility(0);
NullView.setHeight(50);
}
}
private void StartData(ArrayList<Map<String, Object>> List, int Resource) {
this.Adapter = new BasicAdapter(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
new int[] {R.id.contractitem_label_Provider,
R.id.contractitem_label_ProdName,
R.id.contract_label_cno,
R.id.contractitem_label_contractNo,
R.id.contractitem_label_acceptTime,
R.id.contractitem_label_contractStatus,
R.id.contractitem_label_premium,
R.id.contractitem_label_feilv,
R.id.contractitem_label_receivedPremium,
R.id.contractitem_label_Name },
new int[] {R.id.listitem_button_look, R.id.listitem_button_pay,R.id.listitem_main1 });
handler = new Handler();
this.Adapter.Start(this.MainView);
this.Start += Step;
this.End += Step;
}
private void LoadData(){
this.Table.Load("AgentCode="+OnlineNopaymentInsuranceFragment.SelectCode+"&Start="+Start+"&End="+End);
this.Start += Step;
this.End += Step;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.listitem_button_pay:
LogUtil.e("OnlineNopaymentInsuranceFragment", "nothing happen in here");
Toast.makeText(getActivity(),"nothing happen in here", Toast.LENGTH_SHORT).show();
break;
case R.id.listitem_main1:
Toast.makeText(getActivity(),"nothing happen in here,too", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int Index, long id) {}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
#Override
public void onItemClick(AdapterView<?> parent, View view, int Index, long id) {}
private void stopRefresh() {
this.MainView.stopRefresh();
this.MainView.setRefreshTime("刚刚");
}
private void stopLoadMore() {
this.MainView.stopLoadMore();
}
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
SetList();
stopRefresh();
}
}, 2000);
}
#Override
public void onLoadMore() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoadData();
stopLoadMore();
}
}, 2000);
}
#SuppressLint("HandlerLeak")
Handler handler1 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case OVER:
Control.ExitDialog();
break;
default:
break;
}
super.handleMessage(msg);
}
};
Runnable runSetList = new Runnable() {
#Override
public void run() {
SetList();
}
};
}
Adapter code:
public class BasicAdapter extends SimpleAdapter {
private Context context;
private ArrayList<Integer> Indexs;
public BasicAdapter(Context context,List<? extends Map<String,?>> data,int resource,String[] from,int[] to){
super(context,data,resource,from,to);
this.context=context;
this.Indexs =new ArrayList<Integer>();
}
public BasicAdapter(Context context,List<? extends Map<String,?>> data,int resource,String[] from,int[] to,int[] Ids){
super(context,data,resource,from,to);
this.context=context;
this.Indexs =new ArrayList<Integer>();
if (Ids != null) {
for (int i = 0; i < Ids.length; i++) {
this.Indexs.add(Ids[i]);
}
}
}
public void Add(Integer ViewId){this.Indexs.add(ViewId);}
#Override
public View getView(int position,View convertView,ViewGroup parent){
LogUtil.e("===basicadapter", "getview");
View view = super.getView(position, convertView, parent);
for(int i=0;i<this.Indexs.size();i++){
View TempView=(View) view.findViewById(this.Indexs.get(i));
TempView.setOnClickListener((OnClickListener) this.context);
TempView.setTag(position);
}
return view;
}
public void Start(ListView View){
View.setAdapter(this);
this.setViewBinder(new ViewBinder() {
#Override
public boolean setViewValue(View view,Object data,String textRepresentation) {
if(view instanceof TextView && data instanceof HkBoolean){
HkBoolean Data = (HkBoolean) data;
view.setVisibility(Data.GetVisibility());
return true;
}else if(view instanceof ImageView && data instanceof Bitmap){
ImageView iv = (ImageView) view;
iv.setImageBitmap((Bitmap) data);
return true;
}else if(view instanceof ImageView && data instanceof Integer){
ImageView iv = (ImageView) view;
iv.setBackgroundResource((Integer) data);
return true;
}else {
return false;
}
}
});
}
}
If I put button lister in BasicAdapter,it can call ,too.But I want the button'click listener in Fragment.Any suggestion will be appreciated.
this.Adapter = new BasicAdapter(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
Fragment is implementing the listener and not the activity. So you should do
this.Adapter = new BasicAdapter(this, List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },

android update custom view

Hello I am new programmer and I have a custom view in my app that i try to make to redraw itself after i give him new data i tried using invalidate but it seem to not work I'm not sure if the problem is the way i update the data or the way i try to make the view redraw itself. any help will be appreciated.
view:
public class BlackJackView extends View {
private PlayerView playerView, computerView;
private BlackJackGame game;
private Context contex;
public void setPlayer(BlackJackPlayer player) {
playerView = new PlayerView(contex, player);
}
public void setComputer(BlackJackPlayer computer) {
computerView = new PlayerView(contex, computer);
}
public BlackJackView(Context context) {
super(context);
init(context);
}
public BlackJackView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public BlackJackView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
this.contex = context;
game = new BlackJackGame();
playerView = new PlayerView(contex, game.getPlayer());
computerView = new PlayerView(contex, game.getComputer());
}
public void init(BlackJackGame game) {
this.game = new BlackJackGame(game.getPlayer().getName(),game.getPlayer().getMoney());
playerView = new PlayerView(contex, game.getPlayer());
computerView = new PlayerView(contex, game.getComputer());
this.invalidate();
}
#Override
public void onDraw(Canvas canvas) {
playerView.onDraw(canvas);
computerView.onDraw(canvas);
}
}
activity:
public class BlackJackActivity extends Activity {
private UsersDataSource dataSource;
private List<User> values;
private BlackJackView view;
private BlackJackGame game;
private int userID;
private int playerMoney;
private String playerName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
game = new BlackJackGame();
view = new BlackJackView(this);
view.setPlayer(game.getPlayer());
setContentView(R.layout.black_jack_activity);
GetId(savedInstanceState);
GetPlayerData();
view = (BlackJackView) findViewById(R.id.blackJackView);
view.init(game);
}
private void GetId(Bundle savedInstanceState) {
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
userID = -1;
} else {
userID = extras.getInt("ID");
}
} else {
userID = (int) savedInstanceState.getSerializable("ID");
}
}
private void GetPlayerData() {
//data base open
dataSource = new UsersDataSource(this);
dataSource.open();
//get list of database
values = dataSource.getAllUsers();
playerName = values.get(userID).getUsername();
playerMoney = (int) values.get(userID).getTokens();
}
#Override
protected void onResume() {
dataSource.open();
super.onResume();
}
#Override
protected void onPause() {
dataSource.close();
super.onPause();
}
}

I have 4 different Charts in 4 fragment in one Activity but it dose not work?

I want Show 4 Charts in one Activity into 4 Fragments. I use achartengine for my Line Chart ,Bar Chart ,Pie Chart ,Doughnut Char ; I have chart class and Fragment class for each charts and one ChartItemEntity class, my main class is ChartsFragmentActivity,
I do not know where is my fault, can anyone help?
My ChartsFragmentActivity Class:
public class ChartsFragmentActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public LineFragment LineChart_Show(View view) {
LineFragment _containerLineChart = (LineFragment) getFragmentManager().findFragmentById(R.id.lfLineFragment);
return (_containerLineChart);
}
public BarFragment BarChart_Show(View view) {
BarFragment _containerBarChart = (BarFragment) getFragmentManager().findFragmentById(R.id.bfBarFragment);
return (_containerBarChart);
}
public PieFragment PieChart_Show(View view) {
PieFragment _containerPieChart = (PieFragment) getFragmentManager().findFragmentById(R.id.pfPieFragment);
return (_containerPieChart);
}
public DoughnutFragment dounutChart_Show(View view) {
DoughnutFragment continer = (DoughnutFragment) getFragmentManager().findFragmentById(R.id.dfDonutFragment);
return (continer);
}
}
my ChartItemEntity
public class ChartItemEntity {
public String Caption;
public double Value;
public int Color;
}
line chart:
public class LineChart extends Activity {
private GraphicalView mChart;
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
private XYSeries mCurrentSeries;
private XYSeriesRenderer mCurrentRenderer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.line_continer);
List<ChartItemEntity> items = new ArrayList<ChartItemEntity>();
items.add(GetChartItemEntity("Amir", 20));
items.add(GetChartItemEntity("Doctor", 15));
items.add(GetChartItemEntity("Hassan", 18));
items.add(GetChartItemEntity("Zahra", 7));
ShowData(items);
}
public ChartItemEntity GetChartItemEntity(String caption, double value)
{
ChartItemEntity item = new ChartItemEntity();
item.Caption = caption;
item.Value = value;
return item;
}
public void ShowData(List<ChartItemEntity> items)
{
mCurrentSeries = new XYSeries("Sample Data");
mDataset.addSeries(mCurrentSeries);
mCurrentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(mCurrentRenderer);
mRenderer.setInScroll(true);
mRenderer.setXAxisMin(0);
mRenderer.setXAxisMax(items.size());
mRenderer.setBarSpacing(0.2);
mRenderer.setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01));
mRenderer.setAxesColor(Color.WHITE);
mRenderer.setLabelsColor(Color.BLACK);
mRenderer.setPanEnabled(true, true);
mRenderer.setYLabelsAlign(Align.CENTER);
mCurrentRenderer.setFillPoints(false);
mCurrentRenderer.setColor(Color.GREEN);
for (int i = 0; i < items.size(); i++)
{
ChartItemEntity item = items.get(i);
mRenderer.addXTextLabel(i, item.Caption);
mCurrentSeries.add(i, item.Value);
}
if (mChart != null) {
mChart.repaint();
}
}
#Override
protected void onResume() {
super.onResume();
if (mChart == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.line_chart);
mChart = ChartFactory.getLineChartView(this, mDataset, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChart.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(LineChart.this, "No chart element was clicked", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(LineChart.this, "Chart element data point index " + (seriesSelection.getPointIndex() + 1) + " was clicked" + " point value=" + seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});
mChart.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChart.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(LineChart.this, "No chart element was long pressed", Toast.LENGTH_SHORT);
return false;
}
else {
Toast.makeText(LineChart.this, "Chart element data point index " + seriesSelection.getPointIndex() + " was long pressed", Toast.LENGTH_SHORT);
return true;
}
}
});
layout.addView(mChart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
else {
mChart.repaint();
}
}
}
fragment line
public class LineFragment extends Fragment {
#SuppressWarnings("unused")
private ViewGroup _containerLineChart;
#SuppressWarnings("unused")
private LayoutInflater _inflaterLineChart;
#Override
public View onCreateView(LayoutInflater inflaterLineChart, ViewGroup containerLineChart, Bundle savedInstanceState) {
// TODO Auto-generated method stub
_containerLineChart = containerLineChart;
_inflaterLineChart = inflaterLineChart;
try {
return inflaterLineChart.inflate(R.layout.line_continer, containerLineChart, false);
}
catch (Exception ex)
{
Log.e(ex.getMessage(), "");
return null;
}
}
}

Custom View Async Task

ublic class SectionsList extends LinearLayout implements OnOffChangeListener,OnClickListener,MessageListener{
private Context mContext;
private Dialog dialog;
private List<TextView> tList = new ArrayList<TextView>();
private List<EditValueButton> editList = new ArrayList<EditValueButton>();
private List<OnOffButton> onOffList = new ArrayList<OnOffButton>();
private List<String> sectionNames = NewsReader.getInstance().getSectionNamesListWithFunStories();
private final int ChangeBannerDeliveryBetweenTimeDialog_ID = 1;
private final int ChangeBannerDeliveryBetweenDateTimeDialog_ID = 2;
private Handler mHandler;
private EditValueButton editButton;
private long startTime;
private View setView;
private OnOffButton Id;
private Boolean sectionOn = false;
private Boolean setOff;
private Boolean checkSection = false;
private String activeSection;
private OnOffButton onOff;
private boolean cancel;
private TextView sectionName;
private TableLayout table;
private Resources resources;
private int textNormalColor;
private HashMap<String, Time> getSectiontime;
private HashMap<String, Time> hm = new HashMap<String, Time>();
#Override
public boolean handleMessage(Message msg) {
boolean ret;
Bundle bundle = msg.getData();
switch ( msg.what)
{
case Constants.message_SetBannerTime:
startTime = bundle.getLong(Constants.KEY_ARG_1);
setDisplayDuringLabel(startTime, setView);
ret = true;
break;
case Constants.message_setOff:
cancel = bundle.getBoolean(Constants.KEY_ARG_1);
if(cancel){
setOff();
ret = true;
break;
}
default:
{
ret = false;
break;
}
}
return ret;
}
public SectionsList(Context context) {
super(context);
mContext = context;
init(context, null);
}
public SectionsList(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
//new CustomTask().execute();
Log.d("secnames", "section names" + sectionNames);
getSectiontime = PersistedScheduledBannerStore.getInstance().getScheduledBanners();
resources = context.getResources();
textNormalColor = resources.getColor(R.color.app_button_normal_text_color);
if(getSectiontime != null){hm = getSectiontime;}
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.sectiontable, this, true);
table = (TableLayout) findViewById(R.id.mainTable);
for(int i =0; i< sectionNames.size();i++){
TableRow tr = new TableRow(context);
View line = new View(context);
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
line.setBackgroundColor(textNormalColor);
line.setPadding(0, 10, 0, 10);
layoutInflater.inflate(R.layout.sectiontablerow, tr);
table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
table.addView(line);
setIds(tr);
setTagstoViews(i);
addViewstoList();
setListeners();
checkIfSectionIsOn(i);
tList.get(i).setText("sai ram");
}
}
private void loopThroughViews(Context context, LayoutInflater layoutInflater) {
}
private void checkIfSectionIsOn(int i) {
if(getSectiontime.containsKey(sectionNames.get(i))){
String key = sectionNames.get(i);
Time value = getSectiontime.get(key);
editList.get(i).setText(DateFormat.format("h:mm a", value).toString());
onOff.setOn(true);
}else{
editList.get(i).setText("-:-");
}
}
public void onOffChanged(OnOffButton button, boolean isOn) {
setView = button;
if(isOn){
sectionOn = true;
}
else if (!isOn){
sectionOn = false;
makeSectionActive(button);
hm.remove(activeSection);
getSectiontime.remove(activeSection);
}
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case ChangeBannerDeliveryBetweenTimeDialog_ID:
{
long curStartTime = 0;
dialog = new ChangeBannerTimeDialog(getContext(), curStartTime, mHandler,0);
break;
}
case ChangeBannerDeliveryBetweenDateTimeDialog_ID:
{
long curStartTime = 0;
dialog = new ChangeBannerdateTimeDialog(getContext(), curStartTime, mHandler, 0);
break;
}
default:
dialog = null;
}
return dialog;
}
private void setDisplayDuringLabel(long startTime, View v){
changeTimeText(v, DateFormat.format("h:mm a", startTime).toString());
Time time = new Time(startTime);
if(sectionOn){
hm.put(activeSection, time);
}
}
#Override
public void onClick(View v) {
setView = v;
if(v.getId() == R.id.sectionOnOff){
if(sectionOn){
TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
String secName = tt.getText().toString();
showDateTimeDialogIfHoroscopes(secName);
setOff = true;
Id = onOffList.get(Integer.parseInt(v.getTag().toString()));
Id.setOn(true);
makeSectionActive(v);
}
}
else if(v.getId() == R.id.editTime){
setView = v;
Id = onOffList.get(Integer.parseInt(v.getTag().toString()));
if(Id.isOn()){
TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
String secName = tt.getText().toString();
showDateTimeDialogIfHoroscopes(secName);
setOff = false;
Id.setOn(true);
makeSectionActive(v);
}
}
}
private void showDateTimeDialogIfHoroscopes(String secName) {
if(secName.equals("Horoscopes")){
onCreateDialog(ChangeBannerDeliveryBetweenDateTimeDialog_ID).show();
}else{
onCreateDialog(ChangeBannerDeliveryBetweenTimeDialog_ID).show();
}
}
private void setOff() {
if(setOff){
Id.setOn(false);
}
else if(!setOff){
Id.setOn(true);
}
}
private void setIds(TableRow tr){
onOff = (OnOffButton) tr.findViewById(R.id.sectionOnOff);
editButton = (EditValueButton) tr.findViewById(R.id.editTime);
sectionName = (TextView) tr.findViewById(R.id.sectionName);
}
private void setTagstoViews(int i){
onOff.setTag(""+i);
editButton.setTag(""+i);
}
private void setListeners(){
editButton.setOnClickListener(this);
onOff.setOnOffChangeListener(this);
onOff.setOnClickListener(this);
}
public HashMap<String, Time> getBannerSectionwithTime(){
return hm;
}
private void addViewstoList(){
onOffList.add(onOff);
editList.add(editButton);
tList.add(sectionName);
}
private void makeSectionActive(View v){
TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
activeSection = tt.getText().toString();
}
private void changeTimeText(View v, String text){
EditValueButton tt = editList.get(Integer.parseInt(v.getTag().toString()));
tt.setText(text);
}
public boolean checkSectionOn(){
return checkSection;
}
private class CustomTask extends AsyncTask<String, Void, Boolean>{
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=ProgressDialog.show(getContext(), "", "Loading...");
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected Boolean doInBackground(String... params) {
return null;
}
}
}
I want to use Async task to put all Ui in postexecute and loops in doinbackground?
In loop i have my table row which consumens 5secs to 8sec to load so can we somehow add the loop in do in background? Any help would be appreciated. Please provide code sample for better understanding
First define what is your time consuming task. If you want creation of your Table to be in asyncTask here is a hint how to do it. First you need to create entire Table off screen and then add it to your Layout
private TableLayout table;
private void init(){
new CustomTask().execute();
}
private class CustomTask extends AsyncTask<String, Void, Boolean>{
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=ProgressDialog.show(getContext(), "", "Loading...");
}
#Override
protected Boolean doInBackground(String... params) {
// Here is the part where you create your table and do extensive work
// For example
for(int i =0; i< sectionNames.size();i++){
TableRow tr = new TableRow(context);
View line = new View(context);
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
line.setBackgroundColor(textNormalColor);
line.setPadding(0, 10, 0, 10);
layoutInflater.inflate(R.layout.sectiontablerow, tr);
table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
table.addView(line);
setIds(tr);
setTagstoViews(i);
addViewstoList();
setListeners();
checkIfSectionIsOn(i);
tList.get(i).setText("sai ram");
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//And now add your tableLayout in your Layout
layout.addView(tableLayout);
// Adjust layout params per need
dialog.dismiss();
}
}
Adjust all of this according to your needs.
Hope this helps and enjoy your work.

Categories

Resources