[Q] Item separator in ListView fails! Why? - Android Software Development

i have a problem with ListView, i don't view line separator for each item, why ? see where is mouse pointer:
h_t_t_p://tinyurl.com/2vqg52n
and this is source code:
Java Class:
Code:
public class ScienzeInfoNewsActivity extends Activity {
private class Link {
private String title;
private String href;
public Link(String title, String href) {
this.title = title;
this.href = href;
}
public String toString() {
return title;
}
public String getHref() {
return href;
}
}
private FeedReader feedReader;
private ArrayAdapter<Link> adapter;
private ListView list;
public void initialize() {
adapter = new ArrayAdapter<Link>(this, R.layout.textview);
list = (ListView) findViewById(R.id.ListView01);
list.setAdapter(adapter);
}
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
loadFeeds(adapter);
setAllListener();
}
private void setAllListener() {
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String link = adapter.getItem((int) id).getHref();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(intent);
}
});
Button exit = (Button) findViewById(R.id.Button02);
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ScienzeInfoNewsActivity.this.finish();
}
});
Button refresh = (Button) findViewById(R.id.Button01);
refresh.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
loadFeeds(adapter);
}
});
}
private void loadFeeds(ArrayAdapter<Link> adapter) {
if (adapter != null)
adapter.clear();
try {
feedReader = new FeedReader(new URL(
"rss.php"));
String feeds[][] = feedReader.getFeeds();
for (int i = 0; i < feeds.length; i++) {
adapter.add(new Link(feeds[i][0], feeds[i][1]));
}
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
R.layout.textview:
Code:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="h_t_t_p://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
I load entry item with this function loadFeeds()
If i select one of the items without a separator, it just one item.
Thanks for any reply.

Related

[Q] ExpandableView inside another ExpandableView won't inflate children

I've been struggling for a couple of weeks to solve this problem. I have two expandable views, one inside another. Whenever i click on the second level expandable view items, it won't inflate its children. All i see when i click is a small scroll bar that appears on the right side on the expandable view item itself. Using a simple layout with a fixed textview results in the same behaviour, meaning that the problem isn't within the ShiftListItem object/s.
Also, getChildView() is never been called.
YearListAdapter:
Code:
public class YearListAdapter extends BaseExpandableListAdapter {
private Context _context;
private SparseArray<SparseArray<ArrayList<Salary>>> _shiftYears;
public YearListAdapter(
SparseArray<SparseArray<ArrayList<Salary>>> shiftYears,
Context context) {
super();
_context = context;
_shiftYears = shiftYears;
}
public Object getChild(int arg0, int arg1) {
return (null == _shiftYears.get(_shiftYears.keyAt(arg0))) ? null
: _shiftYears.get(_shiftYears.keyAt(arg0)).get(
_shiftYears.get(_shiftYears.keyAt(arg0)).keyAt(arg1));
}
public long getChildId(int arg0, int arg1) {
return arg1;
}
public View getChildView(int arg0, int arg1, boolean arg2,
View convertView, ViewGroup arg4) {
MonthsListView monthLevelExpandable = new MonthsListView(_context);
MonthListAdapter adapter = new MonthListAdapter(_context,
_shiftYears.get(_shiftYears.keyAt(arg0)));
monthLevelExpandable.setAdapter(adapter);
adapter.forceReload();
monthLevelExpandable.setGroupIndicator(null);
return monthLevelExpandable;
}
public int getChildrenCount(int arg0) {
if (null == _shiftYears.get(_shiftYears.keyAt(arg0)))
return 0;
return _shiftYears.get(_shiftYears.keyAt(arg0)).size();
}
public Object getGroup(int arg0) {
return (null == _shiftYears) ? null : _shiftYears.get(_shiftYears
.keyAt(arg0));
}
public int getGroupCount() {
return _shiftYears.size();
}
public long getGroupId(int arg0) {
return arg0;
}
public View getGroupView(int arg0, boolean isExpanded, View convertView,
ViewGroup arg3) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.year_list_view_item, null);
}
TextView title = (TextView) convertView.findViewById(R.id.yearTitle);
title.setText("" + _shiftYears.keyAt(arg0));
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
public void forceReload() {
notifyDataSetChanged();
}
}
MonthListAdapter:
Code:
public class MonthListAdapter extends BaseExpandableListAdapter {
private Context _context;
private SparseArray<ArrayList<Salary>> _shiftMonths;
public MonthListAdapter(Context context,
SparseArray<ArrayList<Salary>> shiftMonths) {
super();
_context = context;
_shiftMonths = shiftMonths;
}
public Object getChild(int groupPosition, int childPosition) {
return (null == _shiftMonths) ? null : _shiftMonths.get(
_shiftMonths.keyAt(groupPosition)).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ShiftListItem sli;
if (null == convertView) {
sli = (ShiftListItem) View.inflate(_context,
R.layout.shift_list_item, null);
} else {
sli = (ShiftListItem) convertView;
}
sli.setSalary(_shiftMonths.get(_shiftMonths.keyAt(groupPosition)).get(
childPosition));
return sli;
}
public int getChildrenCount(int groupPosition) {
if (null == _shiftMonths
|| null == _shiftMonths.get(_shiftMonths.keyAt(groupPosition)))
return 0;
return _shiftMonths.get(_shiftMonths.keyAt(groupPosition)).size();
}
public Object getGroup(int groupPosition) {
return (null == _shiftMonths) ? null : _shiftMonths.get(_shiftMonths
.keyAt(groupPosition));
}
public int getGroupCount() {
return _shiftMonths.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.month_list_view_item, null);
}
TextView title = (TextView) convertView.findViewById(R.id.monthTitle);
title.setText("" + _shiftMonths.keyAt(groupPosition));
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void forceReload() {
notifyDataSetChanged();
}
}
ShiftListItem:
Code:
public class ShiftListItem extends LinearLayout {
private Salary salary;
private TextView itemTimeAndDate;
private TextView itemCashView;
public ShiftListItem(Context context, AttributeSet attrs) {
super(context, attrs);
salary = new Salary();
}
[user=439709]@override[/user]
protected void onFinishInflate() {
super.onFinishInflate();
itemTimeAndDate = (TextView) findViewById(R.id.itemTimeAndDate);
itemCashView = (TextView) findViewById(R.id.itemCashView);
}
public void setSalary(Salary salary) {
this.salary = salary;
Calendar start = salary.getShiftTime().getStart();
Calendar end = salary.getShiftTime().getEnd();
int tHour;
int tMinute;
int tSec;
tSec = salary.getShiftTime().getDifference(
salary.getShiftTime().getStart(),
salary.getShiftTime().getEnd());
tHour = tSec / 3600;
tSec -= tHour * 3600;
tMinute = tSec / 60;
tSec -= tMinute * 60;
itemTimeAndDate.setText("Time: (Start) "
+ returnTwoDigitString(start.get(Calendar.HOUR_OF_DAY)) + ":"
+ returnTwoDigitString(start.get(Calendar.MINUTE)) + " (End)"
+ returnTwoDigitString(end.get(Calendar.HOUR_OF_DAY)) + ":"
+ returnTwoDigitString(end.get(Calendar.MINUTE)) + "\n"
+ (start.get(Calendar.DAY_OF_MONTH)) + "-"
+ (end.get(Calendar.DAY_OF_MONTH)) + "/"
+ (start.get(Calendar.MONTH) + 1) + "-"
+ (end.get(Calendar.MONTH) + 1) + "/"
+ start.get(Calendar.YEAR) + "-" + end.get(Calendar.YEAR));
itemCashView.setText(salary.getCash() + " " + salary.getCurrency()
+ " Total Time Of: " + returnTwoDigitString(tHour) + ":"
+ returnTwoDigitString(tMinute) + ":"
+ returnTwoDigitString(tSec));
}
public Salary getSalary() {
return salary;
}
private String returnTwoDigitString(int time) {
if (time < 10) {
return "0" + time;
}
return "" + time;
}
}
shift_list_item.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<com...ShiftListItem xmlns:android="....."
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/itemTimeAndDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textIsSelectable="false" />
<TextView
android:id="@+id/itemCashView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textIsSelectable="false" />
</com.....ShiftListItem>

Playing videos using mediastore with custom player

Not that anyone will actually reply but I'm about to go insane to be honest, ALL i want to do is play a video from a list view using media store and a custom video player (Not stock player!) but so far all my attempts have failed.
So i need some professional help!
My MediaStore code:
Code:
public class VideoManager {
public VideoManager() {
}
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> getPlayList(Context c) {
/*use content provider to get beginning of database query that queries for all audio by display name, path
and mimtype which i dont use but got it incase you want to scan for mp3 files only you can compare with RFC mimetype for mp3's
*/
final Cursor mCursor = c.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA}, null, null,
"UPPER(" + MediaStore.Video.Media.TITLE + ") ASC");
String videoTitle = "";
String videoPath = "";
/* run through all the columns we got back and save the data we need into the arraylist for our listview*/
if (mCursor.moveToFirst()) {
do {
videoTitle = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
videoPath = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
HashMap<String, String> video = new HashMap<String, String>();
video.put("videoTitle", videoTitle);
video.put("videoPath", videoPath);
videoList.add(video);
} while (mCursor.moveToNext());
}
mCursor.close(); //cursor has been consumed so close it
return videoList;
}
public ArrayList<HashMap<String, String>> getPlayList() {
// TODO Auto-generated method stub
return null;
}
}
The list code along with an OnItemClick method and Intent:
Code:
public class VideoActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
ListView videolist;
Cursor mCursor;
int videoTitle;
int count;
int videoPath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos);
ArrayList<HashMap<String, String>> videoListData = new ArrayList<HashMap<String, String>>();
VideoManager plm = new VideoManager();
// get all songs from sdcard
this.videoList = plm.getPlayList(this);
// looping through playlist
for (int i = 0; i < videoList.size(); i++) {
// creating new HashMap
HashMap<String, String> video = videoList.get(i);
// adding HashList to ArrayList
videoListData.add(video);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, videoListData,
R.layout.video_item, new String[] { "videoTitle" }, new int[] {
R.id.videoTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int videoIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
VideoPlayerActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("videoPath", videoIndex);
startActivity(in);
// Closing PlayListView
finish();
}
});
}
}
And lastly, the players code:
Code:
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private VideoManager videoManager;
private int currentvideoIndex = 0;
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList(this);
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 0){
currentvideoIndex = data.getExtras().getInt("videoPath");
// play selected song
playVideo(currentvideoIndex);
}
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
try {
player.prepare();
player.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
@Override
public int getDuration() {
return player.getDuration();
}
@Override
public boolean isPlaying() {
return player.isPlaying();
}
@Override
public void pause() {
player.pause();
}
@Override
public void seekTo(int i) {
player.seekTo(i);
}
@Override
public void start() {
player.start();
}
@Override
public boolean isFullScreen() {
return false;
}
@Override
public void toggleFullScreen() {
}
}
Right now PLEASE HELP ME!! :crying:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
EmptinessFiller said:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
Click to expand...
Click to collapse
Hi, thanks for the reply but unfortunately it didn't work.
I assume the code i entered is correct..
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
playVideo(getIntent().getExtras().getInt("videoPath"));
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList();
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Passing data between two fragments

Hello guys,
I have a list of fragments created and I want to delete these fragment by long pressing on them. However, before doing so I want dialog fragment to pop up and offer the user the choice to delete or not. I have created the two fragments but I can't get the data across each other. I can't give functionality to the 'OK' button. Here is my code:
Code:
public class CourseListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "course_list";
public static final String YES_NO = "modify";
Activity activity;
ListView courseListView;
ArrayList<Course> courses;
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
private GetEmpTask task;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
courseDAO = new CourseDAO(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.schedule_fragment_course_list,
container, false);
findViewsById(view);
task = new GetEmpTask(activity);
task.execute((Void) null);
courseListView.setOnItemClickListener(this);
courseListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
courseListView = (ListView) view.findViewById(R.id.list_course);
}
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Course course = (Course) list.getItemAtPosition(position);
if (course != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedCourse", course);
CustomCourseDialogFragment customEmpDialogFragment = new CustomCourseDialogFragment();
customEmpDialogFragment.setArguments(arguments);
customEmpDialogFragment.show(getFragmentManager(),
CustomCourseDialogFragment.ARG_ITEM_ID);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Show dialogFragment
FragmentManager fm = getActivity().getSupportFragmentManager();
CheckDialogFragment dialog = new CheckDialogFragment();
dialog.show(fm, YES_NO);
Course employee = (Course) parent.getItemAtPosition(position);
// Use AsyncTask to delete from database
courseDAO.deleteEmployee(employee);
courseListAdapter.remove(employee);
return true;
}
public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Course>> {
private final WeakReference<Activity> activityWeakRef;
public GetEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected ArrayList<Course> doInBackground(Void... arg0) {
ArrayList<Course> courseList = courseDAO.getCourses();
return courseList;
}
@Override
protected void onPostExecute(ArrayList<Course> empList) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
courses = empList;
if (empList != null) {
if (empList.size() != 0) {
courseListAdapter = new CourseListAdapter(activity,
empList);
courseListView.setAdapter(courseListAdapter);
} else {
Toast.makeText(activity, "No Course Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}
/*
* This method is invoked from MainActivity onFinishDialog() method. It is
* called from CustomEmpDialogFragment when an employee record is updated.
* This is used for communicating between fragments.
*/
public void updateView() {
task = new GetEmpTask(activity);
task.execute((Void) null);
}
@Override
public void onResume() {
getActivity().setTitle("Course Schedule");
getActivity().getActionBar().setTitle("Course Schedule");
super.onResume();
}
}
//Dialog Fragment
Code:
public class CheckDialogFragment extends DialogFragment {
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("Do you want to delete?")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
return builder.create();
}
}
I have problems trying to get the data from onItemLongClick() of CourseListFragment to CourseListFragment. Any help would be greatly appreciated.

[Q] Changing to another Activity when pressing on a Gridviewpager

I am trying to start a new certain Activity based on which page I am clicking on in a Gridview.
I tried to understand the Sample GridViewPager which is coming along with the sdk and trying to adapt the given explanation on stackoverflow (question # 26343337). But I really don't know how to bring these two things together and even where to start.
The first java.file Selection
Code:
public class Selection extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_grid);
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new Workers(this, getFragmentManager()));
DotsPageIndicator dotsPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
dotsPageIndicator.setPager(pager);
}
}
and the second java.file Users (thats the Adapter):
Code:
public class Users extends FragmentGridPagerAdapter {
private static final int TRANSITION_DURATION_MILLIS = 100;
private final Context mContext;
private List<Row> mRows;
private ColorDrawable mDefaultBg;
private ColorDrawable mClearBg;
public Users (Context ctx, FragmentManager fm) {
super(fm);
mContext = ctx;
mRows = new ArrayList<Workers.Row>();
mRows.add(new Row(cardFragment(R.string.title, R.string.user1)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user2)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user3)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user4)));
// In case in one row several cardFragments are needed
// mRows.add(new Row(
// cardFragment(R.string.cards_title, R.string.cards_text),
// cardFragment(R.string.expansion_title, R.string.expansion_text)));
mDefaultBg = new ColorDrawable(R.color.dark_grey);
mClearBg = new ColorDrawable(android.R.color.transparent);
}
LruCache<Integer, Drawable> mRowBackgrounds = new LruCache<Integer, Drawable>(3) {
@Override
protected Drawable create(final Integer row) {
int resid = BG_IMAGES[row % BG_IMAGES.length];
new DrawableLoadingTask(mContext) {
@Override
protected void onPostExecute(Drawable result) {
TransitionDrawable background = new TransitionDrawable(new Drawable[] {
mDefaultBg,
result
});
mRowBackgrounds.put(row, background);
notifyRowBackgroundChanged(row);
background.startTransition(TRANSITION_DURATION_MILLIS);
}
}.execute(resid);
return mDefaultBg;
}
};
private Fragment cardFragment(int titleRes, int textRes) {
Resources res = mContext.getResources();
CardFragment fragment =
CardFragment.create(res.getText(titleRes), res.getText(textRes));
// Add some extra bottom margin to leave room for the page indicator
fragment.setCardMarginBottom(
res.getDimensionPixelSize(R.dimen.card_margin_bottom));
return fragment;
}
static final int[] BG_IMAGES = new int[] {
R.drawable.user1,
R.drawable.user2,
R.drawable.user3,
R.drawable.user4
};
/** A convenient container for a row of fragments. */
private class Row {
final List<Fragment> columns = new ArrayList<Fragment>();
public Row(Fragment... fragments) {
for (Fragment f : fragments) {
add(f);
}
}
public void add(Fragment f) {
columns.add(f);
}
Fragment getColumn(int i) {
return columns.get(i);
}
public int getColumnCount() {
return columns.size();
}
}
@Override
public Fragment getFragment(int row, int col) {
Row adapterRow = mRows.get(row);
return adapterRow.getColumn(col);
}
@Override
public Drawable getBackgroundForRow(final int row) {
return mRowBackgrounds.get(row);
}
@Override
public int getRowCount() {
return mRows.size();
}
@Override
public int getColumnCount(int rowNum) {
return mRows.get(rowNum).getColumnCount();
}
class DrawableLoadingTask extends AsyncTask<Integer, Void, Drawable> {
private static final String TAG = "Loader";
private Context context;
DrawableLoadingTask(Context context) {
this.context = context;
}
@Override
protected Drawable doInBackground(Integer... params) {
Log.d(TAG, "Loading asset 0x" + Integer.toHexString(params[0]));
return context.getResources().getDrawable(params[0]);
}
}
}

[Volley] Main UI extremely slow

In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Well it's hard to say what exactly is wrong with it. Maybe text is to long. You can try to measure each operation performance with System.nanoseconds(easiest) and localize the problem first. It would be easier to say what to do with it.
Yes you should try to figure out what part is causing the problem. Try to cut the code down to essentials and measure the execution time. Maybe you will be able to tell what part exactly is not working as wanted.

Categories

Resources