Hi!
I'm developing an App that register the data speed sended and received. The problem is that the app shows a very similar speed between upload and upload, and the data speed seems to be incorrect.
Could anyone solve my problem?
Sorry form my BAD English [emoji29]
This is my code:
Code:
public class Traffic extends TextView {
private int mDelaytime = 3000;
private Handler mHandler = new Handler();
private int mLastReceive = 0;
private int mLastTransmit = 0;
private int mTxRate = 0;
private int mRxRate = 0;
File traffic = new File("/data/.traffic");
private Runnable task = new Runnable() {
public void run() {
if (!traffic.exists() || mLastReceive == getTotalDataBytes(true) && mLastTransmit == getTotalDataBytes(false)){
mTxRate = (getTotalDataBytes(false) - mLastTransmit);
mRxRate = (getTotalDataBytes(true) - mLastReceive);
mLastReceive = getTotalDataBytes(true);
mLastTransmit = getTotalDataBytes(false);
Traffic.this.setText(formatSize(mTxRate/3) + "\n" + formatSize(mRxRate/3));
} else {
Traffic.this.setText("");
}
mHandler.postDelayed(task, mDelaytime);
}
};
private int getTotalDataBytes(boolean Transmit) {
String readLine;
String[] DataPart;
int line = 0;
int Data = 0;
try {
FileReader fr = new FileReader("/proc/net/dev");
BufferedReader br = new BufferedReader(fr);
while((readLine = br.readLine()) != null) {
line++;
if (line <= 2) continue;
DataPart = readLine.split(":");
DataPart = DataPart[1].split("\\s+");
if (Transmit) {
Data += Integer.parseInt(DataPart[1]);
} else {
Data += Integer.parseInt(DataPart[9]);
}
}
fr.close();
br.close();
} catch (IOException e) {
return -1;
}
return Data;
}
public Traffic(Context context) {
this(context, null);
}
public Traffic(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Traffic(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mHandler.postDelayed(task, mDelaytime);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHandler.removeCallbacks(task);
}
private static final String BYTES = "B/s";
private static final String MEGABYTES = "MB/s";
private static final String KILOBYTES = "KB/s";
private static final String GIGABYTES = "GB/s";
private static final long KILO = 1024;
private static final long MEGA = KILO * 1024;
private static final long GIGA = MEGA * 1024;
static String formatSize(final long pBytes) {
if (pBytes < KILO) {
return pBytes + BYTES;
} else if (pBytes < MEGA) {
return (int) (0.5 + (pBytes / (double) KILO)) + KILOBYTES;
} else if (pBytes < GIGA) {
return (int) (0.5 + (pBytes / (double) MEGA)) + MEGABYTES;
} else {
return (int) (0.5 + (pBytes / (double) GIGA)) + GIGABYTES;
}
}
}
Thanks!!
Come on please! :'(
Enviado desde mi GT-S7580 mediante Tapatalk
DannyGM16 said:
Hi!
I'm developing an App that register the data speed sended and received. The problem is that the app shows a very similar speed between upload and upload, and the data speed seems to be incorrect.
Could anyone solve my problem?
Sorry form my BAD English [emoji29]
This is my code:
Code:
public class Traffic extends TextView {
private int mDelaytime = 3000;
private Handler mHandler = new Handler();
private int mLastReceive = 0;
private int mLastTransmit = 0;
private int mTxRate = 0;
private int mRxRate = 0;
File traffic = new File("/data/.traffic");
private Runnable task = new Runnable() {
public void run() {
if (!traffic.exists() || mLastReceive == getTotalDataBytes(true) && mLastTransmit == getTotalDataBytes(false)){
mTxRate = (getTotalDataBytes(false) - mLastTransmit);
mRxRate = (getTotalDataBytes(true) - mLastReceive);
mLastReceive = getTotalDataBytes(true);
mLastTransmit = getTotalDataBytes(false);
Traffic.this.setText(formatSize(mTxRate/3) + "\n" + formatSize(mRxRate/3));
} else {
Traffic.this.setText("");
}
mHandler.postDelayed(task, mDelaytime);
}
};
private int getTotalDataBytes(boolean Transmit) {
String readLine;
String[] DataPart;
int line = 0;
int Data = 0;
try {
FileReader fr = new FileReader("/proc/net/dev");
BufferedReader br = new BufferedReader(fr);
while((readLine = br.readLine()) != null) {
line++;
if (line <= 2) continue;
DataPart = readLine.split(":");
DataPart = DataPart[1].split("\\s+");
if (Transmit) {
Data += Integer.parseInt(DataPart[1]);
} else {
Data += Integer.parseInt(DataPart[9]);
}
}
fr.close();
br.close();
} catch (IOException e) {
return -1;
}
return Data;
}
public Traffic(Context context) {
this(context, null);
}
public Traffic(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Traffic(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mHandler.postDelayed(task, mDelaytime);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHandler.removeCallbacks(task);
}
private static final String BYTES = "B/s";
private static final String MEGABYTES = "MB/s";
private static final String KILOBYTES = "KB/s";
private static final String GIGABYTES = "GB/s";
private static final long KILO = 1024;
private static final long MEGA = KILO * 1024;
private static final long GIGA = MEGA * 1024;
static String formatSize(final long pBytes) {
if (pBytes < KILO) {
return pBytes + BYTES;
} else if (pBytes < MEGA) {
return (int) (0.5 + (pBytes / (double) KILO)) + KILOBYTES;
} else if (pBytes < GIGA) {
return (int) (0.5 + (pBytes / (double) MEGA)) + MEGABYTES;
} else {
return (int) (0.5 + (pBytes / (double) GIGA)) + GIGABYTES;
}
}
}
Thanks!!
Click to expand...
Click to collapse
Maybe this help: https://github.com/NetEase/Emmagee
I don't understand Chinese xD
And it doesn't help me... but anyway Thanks!
Any other solution?
Enviado desde mi GT-S7580 mediante Tapatalk
Oh didnt see that, but there are other data traffic apps on github just search with google. Sorry thats all i can do
Related
I am currently working on an App Switcher with the ability to also add custom apps in the app switcher. So, I already got the recent apps loader built. This is the code for this part of the app:
Code:
public class Corners_RecentApps extends Activity {
private ArrayList<PanelItemDetail> rowItems = null;
private ListView listView;
private ArrayList<String> packageName = null;
private ArrayList<String> className = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
if(rightpanel){
overridePendingTransition(R.anim.left_slide_in_fast, 0);
setContentView(R.layout.right_side_panel);
}
else
{
overridePendingTransition(R.anim.right_slide_in_fast, 0);
setContentView(R.layout.activity_left_side_panel);
}
ImageView imgbtn = (ImageView) findViewById(R.id.transparentbackground);
ImageView panelbg = (ImageView) findViewById(R.id.panelbackground);
listView = (ListView)findViewById(R.id.panelcontents);
packageName = new ArrayList<String>();
className = new ArrayList<String>();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = am.getRecentTasks(30, 0);
rowItems = new ArrayList<PanelItemDetail>();
PackageManager pacMgr = getPackageManager();
for (ActivityManager.RecentTaskInfo recentTask : tasks) {
try {
rowItems.add(new PanelItemDetail(pacMgr.getApplicationIcon(recentTask.origActivity.getPackageName())));
packageName.add(recentTask.origActivity.getPackageName());
className.add(recentTask.origActivity.getClassName());
Log.d("#@#", "getPackageName = " + recentTask.origActivity.getPackageName());
Log.d("#@#", "getClassName = " + recentTask.origActivity.getClassName());
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String itembg = myPreference.getString("itembg_list", "");
if(itembg.equals("defaults"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_default, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("dark"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_dark, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("light"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_light, rowItems);
listView.setAdapter(adapter);
}
else
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_none, rowItems);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
try{
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
Intent taskintent = getPackageManager().getLaunchIntentForPackage(packageName.get(postion).toString());
startActivity(taskintent);
if(rightpanel){
overridePendingTransition(R.anim.right_slide_in, R.anim.zoom_out);
}
else
{
overridePendingTransition(R.anim.left_slide_in, R.anim.zoom_out);
}
finish();
}
catch (NullPointerException fail) {
Toast.makeText(getApplicationContext(), "!", Toast.LENGTH_SHORT).show();
}
}
});
SharedPreferences panelbgpref = PreferenceManager.getDefaultSharedPreferences(this);
String panelbgset = panelbgpref.getString("panelbg_list", "");
if(panelbgset.equals("light"))
{
panelbg.setImageResource(R.drawable.panelbg_light);
}
else
{
panelbg.setImageResource(R.drawable.panelbg);
}
imgbtn.setOnClickListener(new View.OnClickListener(){
[user=439709]@override[/user]
public void onClick(View v) {
if(v.getId() ==R.id.transparentbackground){
moveTaskToBack(true);
finish();
}
}
});
}
Now I want to let the users define in the app settings up to 3 own apps that should be shown on every moment.
How should I do that?
Thank you
I have an async task that loads a list view of items. I am currently trying to set the onClick to load a new fragment with an "id" that is being retrieved from the list item that is clicked. I have no errors in my code that the Android Studio shows me.
When I run the app and click on the item in the list view I get this FC:
02-13 19:49:56.813 20334-20334/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.ReadJSONResult$1.onItemClick(ReadJSONResult.java:140)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
02-13 19:50:42.112 20864-20870/? E/jdwp﹕ Failed sending reply to debugger: Broken pipe
line 140 in ReadJSONResult is:
listenerBeer.onArticleSelected(idToSend);
That line is part of this whole onClick:
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
All the code for ReadJSONResult is:
public class ReadJSONResult extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public ReadJSONResult(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//code for on click
OnArticleSelectedListener listenerBeer;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
//end code for onClick
@override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Searching Beer Cellar");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(c ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
//todo: all the get functions go here
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
BeerSearchAdapter is:
public class BeerSearchAdapter extends ArrayAdapter<BeerData> {
Context context;
int layoutResourceId;
List<BeerData> data = null;
public BeerSearchAdapter(Context context, int layoutResourceId, List<BeerData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data.get(position);
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
My Search.java where the interface comes form is here:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//todo: code body goes here
// Inflate the layout for this fragment
return v;
}
@override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
Log.d("click", "inside the on create");
//inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setIconified(false);
searchView.setOnQueryTextListener(this);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult(getActivity()).execute(jsonUrl);
return false;
}
@override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
@override
public void onArticleSelected(String b){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
//todo: set to beer fragment
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
Let me know if you need any other code, I am stomped on this and could use a second pair of eyes. Thanks.
I am trying to make listview [slidable from left] of navigation drawer layout fullscreen that is make its width to fullscreen.But i am not able to do it.any suggestions?
I want to remove the right gap
Sent from my GT-S5570 using XDA Premium 4 mobile app
Yes, you have to extend DrawerLayout and override some methods because MIN_DRAWER_MARGIN is private
Code:
public class FullDrawerLayout extends DrawerLayout {
private static final int MIN_DRAWER_MARGIN = 0; // dp
public FullDrawerLayout(Context context) {
super(context);
}
public FullDrawerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FullDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
throw new IllegalArgumentException(
"DrawerLayout must be measured with MeasureSpec.EXACTLY.");
}
setMeasuredDimension(widthSize, heightSize);
// Gravity value for each drawer we've seen. Only one of each permitted.
int foundDrawers = 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (isContentView(child)) {
// Content views get measured at exactly the layout's size.
final int contentWidthSpec = MeasureSpec.makeMeasureSpec(
widthSize - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY);
final int contentHeightSpec = MeasureSpec.makeMeasureSpec(
heightSize - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (isDrawerView(child)) {
final int childGravity =
getDrawerViewGravity(child) & Gravity.HORIZONTAL_GRAVITY_MASK;
if ((foundDrawers & childGravity) != 0) {
throw new IllegalStateException("Child drawer has absolute gravity " +
gravityToString(childGravity) + " but this already has a " +
"drawer view along that edge");
}
final int drawerWidthSpec = getChildMeasureSpec(widthMeasureSpec,
MIN_DRAWER_MARGIN + lp.leftMargin + lp.rightMargin,
lp.width);
final int drawerHeightSpec = getChildMeasureSpec(heightMeasureSpec,
lp.topMargin + lp.bottomMargin,
lp.height);
child.measure(drawerWidthSpec, drawerHeightSpec);
} else {
throw new IllegalStateException("Child " + child + " at index " + i +
" does not have a valid layout_gravity - must be Gravity.LEFT, " +
"Gravity.RIGHT or Gravity.NO_GRAVITY");
}
}
}
boolean isContentView(View child) {
return ((LayoutParams) child.getLayoutParams()).gravity == Gravity.NO_GRAVITY;
}
boolean isDrawerView(View child) {
final int gravity = ((LayoutParams) child.getLayoutParams()).gravity;
final int absGravity = Gravity.getAbsoluteGravity(gravity,
child.getLayoutDirection());
return (absGravity & (Gravity.LEFT | Gravity.RIGHT)) != 0;
}
int getDrawerViewGravity(View drawerView) {
final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity;
return Gravity.getAbsoluteGravity(gravity, drawerView.getLayoutDirection());
}
static String gravityToString(int gravity) {
if ((gravity & Gravity.LEFT) == Gravity.LEFT) {
return "LEFT";
}
if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) {
return "RIGHT";
}
return Integer.toHexString(gravity);
}
}
Can you elaborate more.how to use this class
Sent from my GT-S5570 using XDA Premium 4 mobile app
I have an android application that is receiving a string from an arduino via Bluetooth, names the string "data" and displays it by setting a TextView to the string "data". I want a chronometer to start when the incoming string matches a predefined string.
For example:
Code:
if data.equals(startChrono)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
I actually have the arduino sending a "g" and am setting my string goL to be "g" but cannot get the chronometer to start when the g is received. My TextView shows the g. Code is below. I've tried several things and at a loss. Using same code for chronometer.start() with onClickListener with a button works great. I just need it to start the chronometer when i receive a specific string from the arduino.
Code:
beginListenForData();
// text.setText("Bluetooth Opened");
}
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; // This is the ASCII code for a newline
// character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
text.setText(data);
String goL = "g";
String goR = "f";
chronometerLeft = (Chronometer)findViewById(R.id.chronometerLeft);
chronometerRight = (Chronometer)findViewById(R.id.chronometerRight);
if(data.equals(goL)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
if(data.equals(goR))
chronometerRight.setBase(SystemClock.elapsedRealtime());
chronometerRight.start();
}
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
Sorry to bother, but in your while loop condition, what does the '!' before Thread do?
As what was stated on the header I want to implement either a "paint" function for user to edit paint/censor unwanted parts of a photo displayed on a imageview before uploading it to a server in the edited format and a redo function if user makes a mistake while editing?
How do I come about doing it, I've read relevant topics on Canvas, or FingerPaint but still puzzled on how to implement it based on my project here? Tried referencing to the links here and here but without success in implementing the codes into my project code due to my lack of programming skills.
Thanks for any help rendered!
Tried integrating the codes below into my code above (image preview after taking a photo with the camera) for user to start editing via painting but still not working? Thanks for any help rendered!
Code:
public class Drawing extends View {
private Paint mPaint, mBitmapPaint;
Intent intent = getIntent();
Bitmap mBitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
private Canvas mCanvas;
private Path mPath;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private int color, size, state;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Integer> colors = new ArrayList<Integer>();
private ArrayList<Integer> sizes = new ArrayList<Integer>();
public Drawing(Context c) {
super(c);
}
public Drawing(Context c,int width, int height, int size, int color, int state) {
super(c);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
// mBitmapPaint = new Paint(Paint.DITHER_FLAG);
// mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
setColor(color);
setSize(size);
setState(state);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
// canvas.drawColor(Color.TRANSPARENT);
// canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
//
// if (state == 0)
// mBitmap.eraseColor(Color.TRANSPARENT);
for (int i = 0; i < paths.size(); i++) {
mPaint.setColor(colors.get(i));
mPaint.setStrokeWidth(sizes.get(i));
canvas.drawPath(paths.get(i), mPaint);
}
mPaint.setColor(color);
mPaint.setStrokeWidth(size);
canvas.drawPath(mPath, mPaint);
}
public void setColor(int color) {
this.color = color;
}
public void setSize(int size) {
this.size = size;
}
public void setState(int state) {
this.state = state;
// if (state == 0)
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
// else
// mPaint.setXfermode(null);
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
sizes.remove(sizes.size() - 1);
colors.remove(colors.size() - 1);
invalidate();
}
}
private void touch_start(float x, float y) {
undonePaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
colors.add(color);
sizes.add(size);
paths.add(mPath);
mPath = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}