if anyone could help would be great (if or else statement) - Android Studio

i have been designing my own android app and have fell into a problem
im trying to call all avi, mp4, m3u8 and mkv files from my server this is my code i have but im unable to set it up to call all 4 i can only call the the other 2 file formats
PHP:
protected void onStart() {
super.onStart();
boolean isMxPlayerInstalled=isAppInstalled(PlayerActivty.this,MX_PLAYER_PACKAGE_NAME);
try {
if(isMxPlayerInstalled) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setPackage("nppl3.hd.video.player");
String username = getIntent().getStringExtra("USERNAME");
String password = getIntent().getStringExtra("PASSWORD");
String mode = getIntent().getStringExtra("stream_type");
String stream_id = getIntent().getStringExtra("stream_id");
String action = getIntent().getStringExtra("action");
if (action.equalsIgnoreCase("get_vod_streams")) {
extension = ".mp4";
} else {
extension = ".avi";
}

Related

[Q] How can I convert a vector to an array?

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
//Write your own version of the x.split()method
public class Splitting
{
public static void main (String[] args)
{
System.out.println(mySplit("A/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/t/s/t/u/v/w/x/y/z/","/"));
}
public static String [] mySplit(String x, String y)
{
{
Vector<String > Final = new Vector<String>();
String f = null;
String z = null;
for(int i = 0; i < x.length();i++)
{
z = (x.substring(x.indexOf,x.indexOf+1));
f = x.replace(z, "\n");
Final.add(f);
}
String []Finale = Final.toArray(new String[Final.size()]);
System.out.println(Finale[0]);
return Finale;
}
}
}
This is a coding assignment for High School where I have to write my own .Split() method, I have understood how to do it as a String but am having trouble converting the vector to an array if anyone could please help me it would be much appreciated. Also I don't know what would be more convenient an array list or a vector?
summerkiss said:
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
//Write your own version of the x.split()method
public class Splitting
{
public static void main (String[] args)
{
System.out.println(mySplit("A/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/t/s/t/u/v/w/x/y/z/","/"));
}
public static String [] mySplit(String x, String y)
{
{
Vector<String > Final = new Vector<String>();
String f = null;
String z = null;
for(int i = 0; i < x.length();i++)
{
z = (x.substring(x.indexOf,x.indexOf+1));
f = x.replace(z, "\n");
Final.add(f);
}
String []Finale = Final.toArray(new String[Final.size()]);
System.out.println(Finale[0]);
return Finale;
}
}
}
This is a coding assignment for High School where I have to write my own .Split() method, I have understood how to do it as a String but am having trouble converting the vector to an array if anyone could please help me it would be much appreciated. Also I don't know what would be more convenient an array list or a vector?
Click to expand...
Click to collapse
I am not sure how to do what you are asking, but, as a general rule, mathematical operations will be faster with vector representations...
summerkiss said:
String []Finale = Final.toArray(new String[Final.size()]);
Click to expand...
Click to collapse
That's it - you convert it to an array already and then return that. You don't actually return the Vector. Also, you'd be better using an ArrayList as Vectors have been deprecated (I believe). I'm not overly familiar with Java, coming from a .Net background but I believe that's the case.
Thanks for your help!
Archer said:
That's it - you convert it to an array already and then return that. You don't actually return the Vector. Also, you'd be better using an ArrayList as Vectors have been deprecated (I believe). I'm not overly familiar with Java, coming from a .Net background but I believe that's the case.
Click to expand...
Click to collapse
Anyway, thanks!
justmpm said:
I am not sure how to do what you are asking, but, as a general rule, mathematical operations will be faster with vector representations...
Click to expand...
Click to collapse
Why would you re-search for the character to replace, when you are passing it as an argument to your method anyways ( I am referring here to "/" character)
And since you are doing a replace string method for your custom split, that basically does all the job for you... there is no need to use any arrays, vectors or anything else.
All your code can be reduced to smth like this:
public static String myCustomSplit(String myString, CharSequence splitByThisChar) {
String newString = myString.replace(splitByThisChar, "\n");
System.out.println(newString);
return newString;
}
Also you should learn about the naming convention (i.e. use camelCase on variable/method names etc.) if you plan to learn Java.

[Q] How to update a textView every second.

I have a textview that shows your amount of money and i would like the ui to update every second to visually show how much money you have in real time. Would i be able to accomplish this with a timer?, and if so what would it look like.
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
I have attached 2 screenshots showing the errors i was given after inputting. Any idea how to fix this?
mmdeveloper10 said:
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
Click to expand...
Click to collapse
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Ok I fixed the problems stated and now only have these two errors remaining
mmdeveloper10 said:
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Click to expand...
Click to collapse
Have you imported this?
Code:
import java.util.logging.Handler;
If so, change it to
Code:
import android.os.Handler;
Im not at the computer but I think that should solve my issue I will keep you updated
Sent from my HTC6525LVW using XDA Free mobile app
Hey thanks so much its working perfectly now :good:

Handler android

Dear People,
I´m working on a app to control my robot with bluetooth.
So i made a thread to handle the bluetooth device, and a handler to read the information in the Gui thread.
(See code below)
The problem is that i´m not able to print the information to the textview in the handler.
When i print somthing to the textview in de onCreate function, everythings works fine, but when i print something to the textview in the handler, nothing happens.
There are also no errors or something like that.
I know that the handler function is called, because the receive messages are printed well in the log.d.
I hope that there is anyone who can help me.
thanks in advance.
Tom
public class InteractionActivity extends Activity {
private ConnectThread mConnectThread;
private interface MessageConstants
{
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
}
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interaction);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
BluetoothDevice device = getIntent().getExtras().getParcelable("btdevice");
((TextView) findViewById(R.id.textView5)).setText("Hallo"); // works fine, print correct to the screen
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
((TextView) findViewById(R.id.textView5)).setText("Hallo1111"); //Nothing happens
Log.d(TAG, writeMessage); //is printed fine in the log
}
};
private class ConnectThread extends Thread {
etc ............

Help with db manipulation

Hello everyone, I have a problem, i made an app in android studio and i want to use an existing db which i already transferred in assets and project them into a list where every table will be a "category" and every record will be able to have its values manipulated i.e. "Name" "Value" [Item1,1] [Item2,2] Item1(value)+Item2(value)=3. I don't know if i'm being understandable...thanks anyway below i will attach my DatabaseHelper
Code:
import android.content.Context;
import android.database.sqlite.SQLiteAbortException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static String DB_NAME = "my.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null,1);
this.myContext = context;
DB_PATH= myContext.getDatabasePath(DB_NAME).toString();
}
//Create an empty db to overwrite your own db on it
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//does nothing cause db already exists
}else{
//Overwrites db
this.getWritableDatabase();
try{
copyDataBase();
} catch(IOException e){
throw new Error("Error copying database");
}
}
}
// Check if db exists every time app opens
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY);
}catch (SQLiteException e){
//db doesn't exist yet
}
if (checkDB!=null){
checkDB.close();
}
return checkDB != null ? true : false;
}
//Copies your db from assets to the new db
private void copyDataBase() throws IOException{
//open your local db as input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
//Path to the empty db
String outFileName = DB_PATH;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from I to O
byte[] buffer = new byte[1024];
int length;
while((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
//Close streams
myOutput.flush();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

Module stops working as soon as I load a native library (Please help)

Hi,
First, a disclaimer.
I am a Java and xposed noob. My background is in embedded C development so I can get by with some simple Java code and thanks to the great tutorials online I have been able to put together an xposed module but I'm struggling with a problem that is beyond my abilities now and am reaching out to the community for help.
Next, the background.
I have an Android head unit in my car. There is an app that provides me with CarPlay functionality but none of the controls on the steering wheel work with the app. When I analysed the code I found that they handle all of their button inputs using proprietary methods that do not inject an event into any input streams. I wrote an xposed module to hook the button press methods and then inject a proper input into one of the event streams.
Initially I tried to use the command line 'input' command to do this but since it is a Java app and takes about 1s to load it was too slow. My only other option was to create a virtual device on an input stream that I could then use to inject keypresses through the hooked method. To create a virtual device I needed to write C code that my xposed module would be able to access through the JNI. Long story short, after some pain I was able to get the native library integrated into the project and compiling using the NDK.
Finally, the problem.
When I was using the module without the native library it worked but just with a large delay because of the time it takes to load the 'input' java app. I was able to see logs from the module in the logcat as I hooked the method and as I went through the various actions within the hook.
As soon as I introduce the native library though the entire xposed module just stops running completely. I do not get any logs from the module even though I have installed, activated and rebooted. It shows up in the xposed installer but it just does nothing. The funny thing is that this happens even if I make no reference whatsoever to any native functions within the library. All I need to do to kill the module is to build it with the System.loadlibrary line in the Main.java uncommented. As soon as I comment that piece of code out the module starts to hook the function and output logs again. Below is the code from the Main.Java that I am referring to. I am happy to make any manifest, C and gradle files available too. Looking for any ideas as to why the module dies completely as soon as I include this...
Code:
package projects.labs.spike.zlink_xposed_swc;
import de.robv.android.xposed.XposedBridge;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import de.robv.android.xposed.XposedHelpers;
import android.app.AndroidAppHelper;
import android.content.Intent;
import android.os.Bundle;
import android.content.Context;
/* shellExec and rootExec methods */
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import android.view.KeyEvent;
import android.media.AudioManager;
public class Main implements IXposedHookLoadPackage {
public static final String TAG = "ZLINK_XPOSED ";
public static void log(String message) {
XposedBridge.log("[" + TAG + "] " + message);
}
//public native int CreateVirtualDevice();
//public native int SendPrev();
@Override
public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
log("handleLoadPackage: Loaded app: " + lpparam.packageName);
if (lpparam.packageName.equals("com.syu.ms")) {
findAndHookMethod("module.main.HandlerMain", lpparam.classLoader, "mcuKeyRollLeft", new XC_MethodHook() {
@Override
protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
// previous
log("PREVKEYHIT");
//rootExec("input keyevent 88");
log("EVENTSENT");
//Below was trying to use media keys which zlink never responded to...
/* Context context = (Context) AndroidAppHelper.currentApplication();
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
mAudioManager.dispatchMediaKeyEvent(event);
KeyEvent event2 = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
mAudioManager.dispatchMediaKeyEvent(event2);*/
//Below is the failed broadcast intent method...
/*Context mcontext = (Context) AndroidAppHelper.currentApplication();
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mcontext.sendBroadcast(i);*/
}
});
}
}
public static String rootExec(String... strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try {
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
s = s.trim();
outputStream.writeBytes(s + "\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e) {
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
[COLOR="Red"] static {
System.loadLibrary("native-lib");
}[/COLOR]
}
The issue with native library is quite strange and I cannot help with it as my experience with native libs is zero.
But maybe try a different method of injecting media key events.
Create a method:
Code:
void injectKey(int keyCode) {
try {
final long eventTime = SystemClock.uptimeMillis();
final InputManager inputManager = (InputManager)
mContext.getSystemService(Context.INPUT_SERVICE);
int flags = KeyEvent.FLAG_FROM_SYSTEM;
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 50, KeyEvent.ACTION_DOWN,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 25, KeyEvent.ACTION_UP,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
} catch (Throwable t) {
// something went wrong
XposedBridge.log(t.getMessage());
}
}
Then just do: injectKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
And maybe try playing with different KeyEvent flags and attrs.
Thanks so much for this suggestion! Any idea if this injects at a java level or if it depends on there being a keyboard input device available on one of the /dev/input/eventX streams? The android device that I am using has no keyboard available on any of those input streams. Will give it a try nonetheless
C3C076 said:
The issue with native library is quite strange and I cannot help with it as my experience with native libs is zero.
But maybe try a different method of injecting media key events.
Create a method:
Code:
void injectKey(int keyCode) {
try {
final long eventTime = SystemClock.uptimeMillis();
final InputManager inputManager = (InputManager)
mContext.getSystemService(Context.INPUT_SERVICE);
int flags = KeyEvent.FLAG_FROM_SYSTEM;
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 50, KeyEvent.ACTION_DOWN,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 25, KeyEvent.ACTION_UP,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
} catch (Throwable t) {
// something went wrong
XposedBridge.log(t.getMessage());
}
}
Then just do: injectKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
And maybe try playing with different KeyEvent flags and attrs.
Click to expand...
Click to collapse
looxonline said:
Thanks so much for this suggestion! Any idea if this injects at a java level or if it depends on there being a keyboard input device available on one of the /dev/input/eventX streams? The android device that I am using has no keyboard available on any of those input streams. Will give it a try nonetheless
Click to expand...
Click to collapse
Simply use whatever InputDevice that you think should work in your case.
The method basically calls this:
https://android.googlesource.com/pl.../android/hardware/input/InputManager.java#869
which is then propagated to Input Manager Service here:
https://android.googlesource.com/pl...oid/server/input/InputManagerService.java#598
which then calls nativeInjectInputEvent

Categories

Resources