[Java]Programming Help - Off-topic

So I'm learning Java right now, starting off with simple programs. I need to make a program that displays "1-10" when the user inputs one of the numbers and ""11-20" if it's one of those. I have no idea what lines I'm missing, and I'm sure someone here can help me.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package coinflip2;
/**
*
* @author Class
*/
import java.util.Scanner;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Input a Number from 1-20: ");
int num = scan.nextInt();
while (num < 1 || num > 20)
{
System.out.print ("Not in range. Please enter a number from 1 to 20. ");
{
if (num >= 1 || num <=10)
System.out.print("1-10");
else
System.out.print("11-20");
}
}
}
}
Click to expand...
Click to collapse

im also really new to java im kinda self teaching. when u tried to compile what were ur error messages

Wait, I messed something up. before I posted it I was able to actually input a number. Let me take a look at it and I'll edit the first post.

Ok so I edited the first post.
I get no errors. It prompts me to input a number, and after I do it just says "Build Successful" and if I put in a number less than 1 or greater than 20 it prompts me to input a different number. So the first part I got right, I just need to get the print functions to work in the if/else statements.

EDIT!!! Ok I got it to work. This is now the final version if you want to know, even though it's very simple.
Just an update on what I have so far. Everything works but no matter what number between 1 and 20 I put I still get the same answer.
Also sorry for spamming like that, but I'm sure someone can actually learn from my mistakes .
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package coinflip2;
/**
*
* @author Class
*/
import java.util.Scanner;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Input a Number from 1-20: ");
int num = scan.nextInt();
while (num < 1 || num > 20)
{
System.out.print ("Not in range. Please enter a number from 1 to 20. ");
num = scan.nextInt();
}
{
if (num >= 1 && num <=10)
System.out.println("1-10");
else
System.out.println("11-20");
}
}
}
Click to expand...
Click to collapse

Related

Android Code: Downloading from within an app

I've searched the android website but I cannot find any sample code that will allow you to download something from a webpage/website. I'm trying to create a simple application that will allow you to download a podcast from a website straight onto the phone's sdcard. Any help is appreciated. Thanks!
[Edit]: I've found http://developer.android.com/reference/android/webkit/DownloadListener.html it seems right but I'm still a beginner and not sure how to apply the code / modify it and where to place it.
Networking is a big series of tests. Just about everything needs to be within a try/catch block, and you need to think of and test every possible contingency. Without doing that, you WILL get crashes and ugliness.
It is not the simplest thing for a newb to implement.
The SECOND thing you need to note is that WEBKIT is not what you want to mess with for *pure downloads*. If you just want to pull a file and do something manual with it, you do NOT want to be messing with an html rendering engine (that's what webkit is...).
Third, network requests should be done in a SEPARATE THREAD from the UI, otherwise it will result in a terrible user experience, ANR's, and general appearance of FREEZUPS.
You can try some of this:
Code:
public class HTTPGetData {
private byte[] data;
public HTTPGetData(){
}
public byte[] toByteArray(){
return data;
}
public void getViaHttpConnection(String url) throws IOException{
HttpClient httpClient = new DefaultHttpClient();
Log.d("***HTTPGetData",url);
HttpGet request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
HttpResponse response;
try {
response = httpClient.execute(request);
boolean gzip = false;
if (response.containsHeader("Content-Encoding")){
Header[] headers = response.getHeaders("Content-Encoding");
for (int i=0; i<headers.length; i++){
if (headers[i].getValue().compareToIgnoreCase("gzip")==0) gzip = true;
}
}
int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
Log.e("HTTP_CLIENT", ostream.toString());
throw new IOException("HTTP response code: " + status);
} else {
int len = (int)response.getEntity().getContentLength();
InputStream content;
if (gzip) content = new GZIPInputStream(response.getEntity().getContent());
else content = response.getEntity().getContent();
if (len>0 && !gzip){
byte[] theData = new byte[len];
int rec = 0;
int cread = 0;
boolean fail=false;
while (rec < len){
if ((cread=content.read(theData, rec, len-rec))==0){
Log.e("HTTP_CLIENT","Short");
fail=true;
break;
}
rec+=cread;
}
if (!fail) data=theData;
} else {
int ch;
ByteVector bv = new ByteVector(1000);
while ((ch = content.read()) != -1){
bv.add((byte)ch);
}
data = bv.toByteArray();
}
content.close(); // this will also close the connection
}
} catch (ClientProtocolException e) {
Log.e("HTTP_CLIENT","ClientProtocolException");
throw new IOException("ClientProtocolException caught in HTTPGetData.getViaHttpConnection(String url)");
} catch (IOException e) {
Log.e("HTTP_CLIENT","IOException");
throw new IOException("IOException caught in HTTPGetData.getViaHttpConnection(String url)");
}
}
}
What you can do with that is something like this;
try{
HTTPGetData hgd = new HTTPGetData();
hgd.getViaHttpConnection("http://someurl");
//open file and dump in hgd.toByteArray();
catch(IOException e){
//do something with e
}
... and of course, put that in some new thread and while its running, make something spin to give the user the impression of progress.
Thanks lb. I don't really understand perfectly but I will look up the stuff I do not understand. Thanks for the help

Development team V2

Hello everyone,
I want to start again with a development team. After miroslav decided to finish the project on his own, I want to try it again. But this time with a real team Only with people who want to participate, and not just type make. Who wants to join?
miroslav_mm said:
So, I opened your eyes and showed real face our "superstar"!?
Ok! Let's stop this stupid discussion and continuous develop ROM.
At this moment I have main part:
Torchscreen +
BT (BT-calling) +
WiFi (need to test) +
Sensor +
GSM (Waiting call) +
Mobile Data +
Audio +
Vibrate +
HW + 3D ??? (need new kernel or port new 3D kernel driver (kgsl) (in progress))
usb storage ??? (only with special app (native in progress))
Camera ??? (in progress)
Video codec ??? (in progress)
Anyone doing something? Maybe fix some stuff?
Click to expand...
Click to collapse
He just want to clean his topic. Send him a PM.
I understand that but there is still no team. He just made his project open for patches. And I think, personally, a team could help the speed on development of a ROM So please join
Sent from my GT540 using Tapatalk
So join his team , and start patching?
wwenigma said:
So join his team , and start patching?
Click to expand...
Click to collapse
Since when does he have a team? What I know about it, is that he just made some kind of open-source project where you can add your own updates and where he gets no credit.
Sent from my GT540 using Tapatalk
I can help you with Java stuff!
I think miroslav_mm wants to release ICS under name of SWIFT-TEAM, with developer names in credits.... may you ask him about it?
Do not split guys...
Miroslav said that it's only him on the team...so i don't see any team there..if we are more than 1 guy in a team we can get faster a daily ROM for our Phones
rexes13 said:
Miroslav said that it's only him on the team
Click to expand...
Click to collapse
Jep, because PCF+MGP join then leave and jasper580 cant make neccessary steps... ask him. All two, ask him about it.
wwenigma said:
Jep, because PCF+MGP join then leave and jasper580 cant make neccessary steps... ask him. All two, ask him about it.
Click to expand...
Click to collapse
I can make nesseccary steps if I want, but I don't want to. I want to start cleaned up. That's why I created this topic. So:
If you want to join: welcome.
If you don't want to: stop spamming
@rexes13 Welcome to the team!
Sent from my GT540 using Tapatalk
Good news.
Yesterday I successfully ported 3d kernel driver (kgsl) from 35, so now we have full functionality kernel with OpenGL ES-CM 1.1.
So HW, 3D and other stuff with support OpenGL working, not excellent but working, need improve source code Surfaceflinger and HardwareDisplay.
Maybe next weak I will make new thread and publish first public test version, but all development moments we can discus here.
Before I need redownload all sources CM9 again. Yesterday I had the same error like in wwenigma and aaa801
Code:
target thumb C: libhardware_legacy <= hardware/libhardware_legacy/power/power.c
arm-linux-androideabi-gcc: ": No such file or directory
<command-line>: warning: missing terminating " character
and I dont know WTF, so delete all source tree. Maybe today will try download again and build again.
hell yeah! im just another non-dev member LOL sry
Need help!
Look on code:
Code:
//static int32_t msm_tscal_scaler = 65536;
static int32_t msm_tscal_xscale = 70046;
static int32_t msm_tscal_xoffset = -4191987;
static int32_t msm_tscal_yscale = 71735;
static int32_t msm_tscal_yoffset = -3004437;
this pointers for torch 320*240. So when I using that I need tap on 2mm high on icon for open something. This pointer need for screen calibration. Need find right pointer.
I can't find a logic in this numbers.
miroslav_mm said:
Need help!
Look on code:
Code:
//static int32_t msm_tscal_scaler = 65536;
static int32_t msm_tscal_xscale = 70046;
static int32_t msm_tscal_xoffset = -4191987;
static int32_t msm_tscal_yscale = 71735;
static int32_t msm_tscal_yoffset = -3004437;
this pointers for torch 320*240. So when I using that I need tap on 2mm high on icon for open something. This pointer need for screen calibration. Need find right pointer.
I can't find a logic in this numbers.
Click to expand...
Click to collapse
The offsets appear to have a ~4:3 ratio. It doesn't make sense though why it's x:y=4:3, and not the other way around, since the screen is usually 3:4(e.g. 320x480 or 240x320). Also, considering our screen is 320x480, which is a ratio of 1,5 and not 1,(3), I think those would be totally wrong for our phone. Maybe try to modify one of the two to match 1,5 ratio. E.g. make xoffset=-4506655. I don't know. :/
Please discuss development on your page. I want to make a dev team here
Sent from my GT540 using Tapatalk
deleted
10 character
This numbers working with this java code together:
]
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read current values
final int xoffset = (readValue("xoffset")*240+480)/960;
final int yoffset = (readValue("yoffset")*320+460)/920;
final int xscale = readValue("xscale");
final int yscale = readValue("yscale");
view = new View(this) {
private int step = 1;
private int rawx1;
private int rawy1;
private int rawx2;
private int rawy2;
private void writeValue(String parameter, int value) {
try {
FileOutputStream fos = new FileOutputStream(new File("/sys/module/msm_touch/parameters/tscal_" + parameter));
fos.write(String.valueOf(value).getBytes());
fos.flush();
fos.getFD().sync();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() != MotionEvent.ACTION_UP)
return true;
if(step==1) {
rawx1 = ((int)ev.getRawX()*65536-xoffset+32768)/xscale;
rawy1 = ((int)ev.getRawY()*65536-yoffset+32768)/yscale;
if(rawx1<100 && rawy1<100)
step = 2;
} else if(step==2) {
rawx2 = ((int)ev.getRawX()*65536-xoffset+32768)/xscale;
rawy2 = ((int)ev.getRawY()*65536-yoffset+32768)/yscale;
if(rawx2>140 && rawy2>220)
step = 3;
} else {
int distx = rawx2 - rawx1;
int new_xscale = (140*65536 + distx/2)/distx;
int disty = rawy2 - rawy1;
int new_yscale = (220*65536 + disty/2)/disty;
int new_xoffset = 1;
new_xoffset += 50*65536-rawx1*new_xscale;
new_xoffset += 190*65536-rawx2*new_xscale;
new_xoffset /= 2;
new_xoffset = (new_xoffset*960+120)/240;
int new_yoffset = 1;
new_yoffset += 50*65536-rawy1*new_yscale;
new_yoffset += 270*65536-rawy2*new_yscale;
new_yoffset /= 2;
new_yoffset = (new_yoffset*920+160)/320;
// Pass new calibration to kernel
writeValue("xoffset", new_xoffset);
writeValue("yoffset", new_yoffset);
writeValue("xscale", new_xscale);
writeValue("yscale", new_yscale);
// Save calibraiton data to /data/system/pointercal
StringBuilder sb = new StringBuilder();
sb.append(new_xscale);
sb.append(" ");
sb.append(0);
sb.append(" ");
sb.append(new_xoffset);
sb.append(" ");
sb.append(0);
sb.append(" ");
sb.append(new_yscale);
sb.append(" ");
sb.append(new_yoffset);
sb.append(" ");
sb.append(65536);
App + ui input framework + kernel working together.
App - creation poinercal
ui input framework - reading pointercal send correct info to kernel
kernel touch driver - doing move.
Öhm, the touchscreen driver use a virtual square (320*320) to detect touch, stretched to a rectangle(320*480)?
mod: about calibration, http://code.google.com/p/openeve/issues/detail?id=91
jasper580 said:
Please discuss development on your page. I want to make a dev team here
Click to expand...
Click to collapse
I cant understand you! What do you mean? Do you wanna make new dev team? Working on my sources but without me?
I exactly want to ask that. Maybe he start from scratch, his github is near empty.

XML parsing-best method, general discussion

I am relatively new to programing and have been teaching myself as I go. I am trying to now integrate ESPN's API into my app which outputs XML data. I have done enough research to understand that I need to use an XML parser and that the XML can be displayed as a list view or web view by adding HTML markup.
I would like this thread to become a general discussion for all new developers on what XML parsing is and what it does. How it works, the code behind it etc.
I am currently trying to modify a code snippet from the developer.google.com website.
Android includes built in libraries for XML Parsing.
You can see a minimal use of the library here:
Code:
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class SimpleXmlPullApp
{
public static void main (String args[])
throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
}
So essentially, you can grab the xml from ESPN, save it to a file, parse it with that library, and output as desired.
Full details here: http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
the fastest way I know is the parser written in c/c++ and compiled with ndk.
bitpushr said:
Android includes built in libraries for XML Parsing.
So essentially, you can grab the xml from ESPN, save it to a file, parse it with that library, and output as desired.
Full details here: http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
Click to expand...
Click to collapse
I will have to try out this code. Because I am learning as I go there are many things in java I don't yet understand which ultimately make it a lot harder to accomplish tasks but I am slowly catching on
If you want to do this in a .NET (Windows x86/64, Windows Mobile, Windows Phone) environment, or a Linux MONO environment then the following will carry out the bare minimum of parsing.
Assuming you have the data in an XML file :- PARAMS.XML in the same folder as the program, created similar to this:
Code:
<?xml version="1.0" encoding="UTF-8" ?>
<PARAMS>
<Library>TESTLIB</Library>
<Source>C:\RetData\</Source>
</PARAMS>
Then the following C# code will read and extract the parameters:
Code:
using System.Xml;
string LibName,RetDir;
XmlReader xrdr = XmlReader.Create(Application.StartupPath+"\\PARAMS.xml");
xrdr.ReadToFollowing("Library");
Libname=xrdr.ReadElementContentAsString();
xrdr.ReadToFollowing("Source");
RetDir = xrdr.ReadElementContentAsString();
xrdr.Close();
After executing this code then:
LibName = "TESTLIB"
RetDir = "C:\RetData\"
CAVEAT:
I mentioned that this is the bare minimum. An XmlReader object is a forward only reader. Also, this code has no error checking.
In this case the elements must be read in the order they occur or the reader will encounter a null element and throw an error.

[Q] hooking RecentLocationApps.getAppList()

I am trying to hook this method, I want to filter out the "Google Play services" from there...(is under settings app)
Code:
/**
* Fills a list of applications which queried location recently within
* specified time.
*/
public List<Preference> getAppList() {
// Retrieve a location usage list from AppOps
AppOpsManager aoManager =
(AppOpsManager) mActivity.getSystemService(Context.APP_OPS_SERVICE);
List<AppOpsManager.PackageOps> appOps = aoManager.getPackagesForOps(
new int[] {
AppOpsManager.OP_MONITOR_LOCATION,
AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION,
});
// Process the AppOps list and generate a preference list.
ArrayList<Preference> prefs = new ArrayList<Preference>();
long now = System.currentTimeMillis();
for (AppOpsManager.PackageOps ops : appOps) {
// Don't show the Android System in the list - it's not actionable for the user.
// Also don't show apps belonging to background users.
int uid = ops.getUid();
boolean isAndroidOs = (uid == Process.SYSTEM_UID)
&& ANDROID_SYSTEM_PACKAGE_NAME.equals(ops.getPackageName());
if (!isAndroidOs && ActivityManager.getCurrentUser() == UserHandle.getUserId(uid)) {
Preference pref = getPreferenceFromOps(now, ops);
if (pref != null) {
prefs.add(pref);
}
}
}
return prefs;
}
I can't hook this method, I'v tried something like :
Code:
if (lpparam.packageName.equals("com.android.settings")) {
findAndHookMethod("com.android.settings.location.LocationSettings", lpparam.classLoader, "getAppList", new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("Called");
}
what is the best approach to achieve this?
devtrop said:
I can't hook this method
Click to expand...
Click to collapse
Why not? Are there any errors in the Xposed log?
If not, I'd make sure the package name is correct and that the method is actually called when you expect it to be.
Code:
09-29 11:06:53.600 5277 5277 I Xposed : java.lang.NoSuchMethodError: com.android.settings.location.RecentLocationApps#getAppList(java.util.List)#exact
running on Samsumg Note 3.
devtrop said:
Code:
09-29 11:06:53.600 5277 5277 I Xposed : java.lang.NoSuchMethodError: com.android.settings.location.RecentLocationApps#getAppList(java.util.List)#exact
running on Samsumg Note 3.
Click to expand...
Click to collapse
That error doesn't correspond to the code you've posted in the first post. Post the modified code and the error.
Purely guessing, though: Samsung modified the code you're trying to hook. You're hooking the methods you're seeing in the AOSP code, but that's not the case on your device.
You are correct, sorry. I'm trying a lot of different stuff.
this is the code:
Code:
try
{
findAndHookMethod("com.android.settings.location.RecentLocationApps", lpparam.classLoader,
"getAppList", List.class, new XC_MethodHook() {
@SuppressWarnings("unchecked")
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable
{
XposedBridge.log("RecentLocationApps.getAppList()");
}
});
}
catch(Throwable t)
{
XposedBridge.log(t);
}
the throwable is :
Code:
09-29 11:56:08.559 5282 5282 I Xposed : java.lang.NoSuchMethodError: com.android.settings.location.RecentLocationApps#getAppList(java.util.List)#exact
if tried to do that for every package, not just com.android.settings or com.android.settings.location and it doesn't seem to work.
do you know what's the correct package? do I have to start dedexing Samsung's packages to get the answer?
devtrop said:
do you know what's the correct package?
Click to expand...
Click to collapse
com.android.settings should be the correct package, if I'm not mistaken.
devtrop said:
do I have to start dedexing Samsung's packages to get the answer?
Click to expand...
Click to collapse
That'd be the best thing to do as it looks like Samsung has changed some things.

Help enabling downloads through webview (Kotlin)

Good day. I'm new to android development and I'm trying to develop a simple webview application, picked a nice template and went through the steps and made good progress, I managed to load my site fully and enable javascript, that works as intended, however I'm not able to make the app download anything, I host a few pdf files that should open or download through it, but nothing happens.
I looked at a few answers here and it is to my understanding that I need to specifically add a function for that, could you give me a hand? I have tried multiple different code and tweaking them, but I wasn't able to get it to work, here is my base code:
Code:
package com.logista.test.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.app.DownloadManager
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.logista.test.R
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
val myWebView: WebView = root.findViewById(R.id.webview)
myWebView.webViewClient = WebViewClient()
myWebView.settings.javaScriptEnabled = true
myWebView.loadUrl("https://www.example.org/")
return root
}
}
I believe I should be adding
Code:
import android.app.DownloadManager
And tweak this
Code:
// Set web view download listener
web_view.setDownloadListener(DownloadListener {
url,
userAgent,
contentDescription,
mimetype,
contentLength ->
// Initialize download request
val request = DownloadManager.Request(Uri.parse(url))
// Get the cookie
val cookies = CookieManager.getInstance().getCookie(url)
// Add the download request header
request.addRequestHeader("Cookie",cookies)
request.addRequestHeader("User-Agent",userAgent)
// Set download request description
request.setDescription("Downloading requested file....")
// Set download request mime tytpe
request.setMimeType(mimetype)
// Allow scanning
request.allowScanningByMediaScanner()
// Download request notification setting
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
// Guess the file name
val fileName = URLUtil.guessFileName(url, contentDescription, mimetype)
// Set a destination storage for downloaded file
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
// Set request title
request.setTitle(URLUtil.guessFileName(url, contentDescription, mimetype));
// DownloadManager request more settings
request.setAllowedOverMetered(true)
request.setAllowedOverRoaming(false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
request.setRequiresCharging(false)
request.setRequiresDeviceIdle(false)
}
request.setVisibleInDownloadsUi(true)
// Get the system download service
val dManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
// Finally, request the download to system download service
dManager.enqueue(request)
})
// Load button click listener
button_load.setOnClickListener{
// Load url in a web view
web_view.loadUrl(url)
}
}
Taken from here: https://android--code.blogspot.com/2018/03/android-kotlin-webview-file-download.html
I did the basics, renaming the function accordingly and such, but it gives me quite a few errors when building the app, for instance uri isn't defined, cookiemanager isn't defined, environment isn't defined, build isn't defined, and such, could you give me some guidance?

Categories

Resources