Java socket declaration breaks the code execution - java

I am working on a project in android studio. The application is a client that connects to host written in c# using sockets. I am new to java this being my first project I am doing on my own. I am used with sockets in c# and in java I found a lot of similarities, but I encountered a strange problem: everything is fine until a new socket is initialized when the code execution seems to be interrupted. I will post the code than I will explain exactly what is happening.
First part, the main thread:
package com.example.alexandru.news;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Connection;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class login extends Activity {
EditText emadr;
EditText pasword;
Button log_in_butt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
log_in_butt = (Button) findViewById(R.id.login);
emadr= (EditText) findViewById(R.id.EmailAdr);
pasword= (EditText) findViewById(R.id.Password);
}
public void loginOnClick(View v)
{
final String mesaj=emadr.getText().toString()+"%"+pasword.getText().toString()+"%"+"^STOP^";
String[] perm={"android.permission.CAMERA"}; int a=200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(perm,a);
}
com.example.alexandru.news.Connection log_in_connection=new com.example.alexandru.news.Connection(mesaj);
log_in_connection.start();
}
}
The connection class is a class I created in the same folder with the "log in" class(the main class). The code behind the Connection class:
package com.example.alexandru.news;
import android.content.Context;
import android.util.Xml;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
/**
* Created by Alexandru on 14.08.2016.
*/
public class Connection extends Thread {
String ip="some ip";
int port=60000;
String mesaj;
Socket soc;
public Connection(String mesaj) {
this.mesaj=mesaj;
}
#Override
public void run() {
try {
int a=2;
soc= new Socket(ip, port);
DataOutputStream outstream =new DataOutputStream(soc.getOutputStream());
byte[] buffer;
buffer = this.mesaj.getBytes("UTF-8");
outstream.write(buffer);
outstream.flush();
outstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run the app and I press the button everything is executed until the statement =new Socket(ip,port) is met when this happen the thread isn't executing anymore (I think). When I am debugging and the breakpoint is set before that problematic line everything works. When that line is highlighted and I press F8 the debugging tab says: "Application is running" and then pressing F8 again doesn't make any changes. If I press the "log in" button again nothing happens.
I am using a USB device to debug the app which is connected to the same network as the PC trough WiFi.No port forward is made. I worked with sockets in a project with my high school team before and we had a java client and a c# host and everything worked. But we were using the Emulator. I used all the ip addresses "ipconfig" gave me I changed the port, nothing happens. It doesn't work. I seems that I am the only one with this problem. Sorry for long post and lack of details.
This is the log:
08-17 12:09:38.875 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libEGL_MRVL.so
08-17 12:09:38.882 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libGLESv1_CM_MRVL.so
08-17 12:09:38.890 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libGLESv2_MRVL.so
08-17 12:09:38.898 30326-30326/com.example.alexandru.news D/GC: <tid=30326> OES20 ===> GC Version : GC Ver SS_rls_pxa988_JB42_R1_RC2_GC13.16
08-17 12:09:38.914 30326-30326/com.example.alexandru.news D/OpenGLRenderer: Enabling debug mode 0
08-17 12:09:38.929 30326-30326/com.example.alexandru.news D/WritingBuddyImpl: getCurrentWritingBuddyView()
08-17 12:09:39.054 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60b55588
08-17 12:09:39.492 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60e51d40
08-17 12:09:39.984 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60ef84b8
08-17 12:14:05.617 30326-30350/com.example.alexandru.news D/Er: Eroare
08-17 12:14:17.765 30326-30350/com.example.alexandru.news W/System.err: java.net.SocketTimeoutException: failed to connect to /25.74.114.6 (port 60000) after 1000ms
08-17 12:14:17.765 30326-30350/com.example.alexandru.news W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:159)
08-17 12:14:17.781 30326-30350/com.example.alexandru.news W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:112)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.Socket.connect(Socket.java:842)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at com.example.alexandru.news.Connection.run(Connection.java:45)
08-17 12:14:17.828 30326-30350/com.example.alexandru.news D/dalvikvm: threadid=13: still suspended after undo (sc=1 dc=1)
08-17 12:14:17.828 30326-30330/com.example.alexandru.news D/dalvikvm: GC_CONCURRENT freed 360K, 17% free 8692K/10472K, paused 11ms+7ms, total 60ms

Related

Whenever Iam not entering anything in EditText the app is crashes [duplicate]

This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 2 years ago.
Iam making a weather app but whenever Iam not entering or entering wrong city name in EditText the app crashes even though I have used try and catch blocks for error handling.The below is the java,xml code and the logs where it is showing a runtime error.
Java
package com.atul.whatstheweather;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView weatherInfo;
public class Content extends AsyncTask<String, Void ,String>
{
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherData = jsonObject.getString("weather");
JSONArray array = new JSONArray(weatherData);
for(int i=0;i<array.length();i++)
{
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
weatherInfo.setText("Weather: "+main+"\n\n"+"Description: "+description);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
weatherInfo = (TextView)findViewById(R.id.textView);
}
public void clicked(View view)
{
Content content = new Content();
content.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=c20cea76c84b519d67d4e6582064db92");
Log.i("clicked","is working");
}
}
In the Logs given below it is showing Runtime error
Run Logs
05/03 17:35:25: Launching app
Cold swapped changes.
$ adb shell am start -n "com.atul.whatstheweather/com.atul.whatstheweather.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18757 on device xiaomi-redmi_note_3-9b51ac51
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
W/ResourceType: No package identifier when getting name for resource number 0x00000000
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
I/InstantRun: Instant Run Runtime started. Android package is com.atul.whatstheweather, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AccessibilityManager: current package=com.atul.whatstheweather, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#9df51ef
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce6e4fc
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build : a7823f5, I59a6815413
Build Date : 09/23/16
OpenGL ES Shader Compiler Version: XE031.07.00.00
Local Branch : mybranch22028469
Remote Branch : quic/LA.BR.1.3.3_rb2.26
Remote Branch : NONE
Reconstruct Branch : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
I/clicked: is working
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.atul.whatstheweather, PID: 18757
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:356)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:266)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:60)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
I/Process: Sending signal. PID: 18757 SIG: 9
Application terminated.
App crashes because you are calling Toast in background thread.
Replace your Toast line in catch block Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show(); with :
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
});
Just delete the Toast.makeText

Floating Window Crash If Called When The App Killed

I want to show the floating layout on top of the screen when service Alarm or Call happened. Normally, when the app opens or it is in the background (before swiping it out) it shows and works well. even if I kill the app it still shows (kill = swipe the app)and it is still working. but, if the app is killed and not opened it tries to show (from service of alarm for example) it crashes and I cant even see the crash log in the android studio after terminating the app.
how can I fix that or find the issue?
my code Alarm BroadCast where it called: (the alarm broadcast called as needed)
public class BroadcastManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(context,FloatingWindow.class);
startService(intent);
}
my floating view code :
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.greenbook.greenlids.MainActivity;
import com.example.greenbook.greenlids.R;
public class FloatingWindow extends Service {
private WindowManager windowManager;
private LinearLayout layout;
private TextView txt;
private Button bttn1 , exitBttn;
private Context context;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layout = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setBackgroundColor(Color.argb(255,0,0,255));
layout.setLayoutParams(layoutParams);
final WindowManager.LayoutParams windowParams;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}else{
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
if (layoutInflater != null) {
layout = (LinearLayout) layoutInflater.inflate(R.layout.linear_layout_floating_window, null);
}
layout.setBackgroundColor(Color.argb(255,240,240,255));
bttn1 = layout.findViewById(R.id.LLbutton);
exitBttn = layout.findViewById(R.id.exitBttn);
txt = layout.findViewById(R.id.noteTxt);
txt.setTextSize(18);
txt.setText("Natan");
exitBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
windowManager.removeView(layout);
stopSelf();
}
});
bttn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean handler = new Handler().postDelayed(new Runnable() {
#Override
public void run() {
txt.setText("Natan The King");
}
}, 1000*5);
}
});
windowManager.addView(layout,windowParams);
layout.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams updateParam = windowParams;
int x , y;
float touchedX , touchedY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x = updateParam.x;
y = updateParam.y;
touchedX = event.getRawX();
touchedY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
updateParam.x = (int) (x+event.getRawX() - touchedX);
updateParam.y = (int) (y+event.getRawY() - touchedY);
windowManager.updateViewLayout(layout,updateParam);
break;
}
return false;
}
});
}
}
logcat updated:
06-18 11:59:00.263 6722-6722/? E/Zygote: isWhitelistProcess - Process is Whitelisted
06-18 11:59:00.264 6722-6722/? E/libpersona: scanKnoxPersonas
Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory
06-18 11:59:00.268 6722-6722/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[2], Con:u:r:zygote:s0 RAM:SEPF_SM-G935F_8.0.0_0007, [-1 -1 -1 -1 0 1]
06-18 11:59:00.269 6722-6722/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.greenbook.greenlids
06-18 11:59:00.275 6722-6722/? I/zygote64: Late-enabling -Xcheck:jni
06-18 11:59:00.341 6722-6722/? D/TimaKeyStoreProvider: TimaKeyStore is not enabled: cannot add TimaSignature Service and generateKeyPair Service
06-18 11:59:00.341 6722-6722/? D/ActivityThread: Added TimaKeyStore provider
06-18 11:59:00.422 6722-6722/com.example.greenbook.greenlids I/zygote64: no shared libraies, dex_files: 1
06-18 11:59:00.723 6722-6722/com.example.greenbook.greenlids I/InstantRun: starting instant run server: is main process
06-18 11:59:00.750 6722-6722/com.example.greenbook.greenlids D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-18 11:59:00.755 6722-6722/com.example.greenbook.greenlids E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.greenbook.greenlids, PID: 6722
java.lang.RuntimeException: Unable to start receiver com.example.greenbook.greenlids.models.BroadcastManager: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3399)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1538)
at android.app.ContextImpl.startService(ContextImpl.java:1484)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at com.example.greenbook.greenlids.models.BroadcastManager.onReceive(BroadcastManager.java:40)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3392)
at android.app.ActivityThread.-wrap18(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6944) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 
Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:
Handling a high-priority Firebase Cloud Messaging (FCM) message.
Receiving a broadcast, such as an SMS/MMS message.
Executing a PendingIntent from a notification.
Starting a VpnService before the VPN app promotes itself to the foreground.
taked from the link below
i found the answer here:
https://stackoverflow.com/a/46445436/8675712
https://stackoverflow.com/a/47654126/8675712

Rally Rest Api-Android app-Getting No class found even after importing required jars

I am trying to build a rally Android app.I tried https://github.com/RallyTools/RallyRestToolkitForJava As given I have added the jars.
1.commons-codec-1.6.jar
2.gson-2.2.4.jar
3.httpclient-4.2.5.jar
4.org.apache.commons.logging-1.1.1.jar
5.httpcore-4.2.4.jar
My mainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.QueryResponse;
import org.apache.http.HttpHost;
import org.apache.http.client.utils.URIUtils;
public class MainActivity extends AppCompatActivity
{
String host = "https://rally1.rallydev.com";
String applicationName = "Android-Rally";
RallyRestApi restApi;
Button buttonlogin;
EditText etemail,etpass;
QueryRequest qtestset;
QueryResponse response;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etemail=(EditText) findViewById(R.id.etemail);
etpass=(EditText) findViewById(R.id.etpassword);
buttonlogin=(Button) findViewById(R.id.btnlogin);
buttonlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(etemail.equals("") && etpass.equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your Rally Credentials",Toast.LENGTH_LONG).show();
}
else
{
try
{
getRally();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
qtestset = new QueryRequest("Defects");
qtestset.setLimit(1);
try
{
response = restApi.query(qtestset);
if(!response.wasSuccessful())
{
Toast.makeText(getApplicationContext(),"Login Un-Successful",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Login Successful",Toast.LENGTH_LONG).show();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
}
public RallyRestApi getRally() throws URISyntaxException {
String password = etemail.getText().toString();
String email=etpass.getText().toString();
restApi = new RallyRestApi(new URI(host), email,password);
restApi.setApplicationName(applicationName);
return restApi;
}
}
My error log
04-18 14:07:16.299 11364-11364/com.example.apetkar.rally_poc D/AndroidRuntime: Shutting down VM
04-18 14:07:16.299 11364-11364/com.example.apetkar.rally_poc E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.apetkar.rally_poc, PID: 11364
java.lang.NoSuchMethodError: No static method extractHost(Ljava/net/URI;)Lorg/apache/http/HttpHost; in class Lorg/apache/http/client/utils/URIUtils; or its super classes (declaration of 'org.apache.http.client.utils.URIUtils' appears in /system/framework/org.apache.http.legacy.boot.jar)
at org.apache.http.impl.client.DecompressingHttpClient.getHttpHost(DecompressingHttpClient.java:113)
at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:108)
at com.rallydev.rest.client.HttpClient.executeRequest(HttpClient.java:157)
at com.rallydev.rest.client.HttpClient.doRequest(HttpClient.java:145)
at com.rallydev.rest.client.BasicAuthClient.doRequest(BasicAuthClient.java:56)
at com.rallydev.rest.client.HttpClient.doGet(HttpClient.java:221)
at com.rallydev.rest.RallyRestApi.query(RallyRestApi.java:172)
at com.example.apetkar.rally_poc.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Can anyone help here..stuck at this for days now..Thanks
Does android run some special mobile version of java? It seems like the 4.2 http components are likely not compatible. I haven't had a chance to look into it much, but I wonder if there is a newer set of those components that are compatible with the android environment? You could try forking the RallyRestToolkitForJava repo and updating the dependencies locally to see if you can get it to run...
There's a class conflict with the included Apache HTTP jars and the ones used by native Android. I got around this by forking the Rally project and replacing Apache HTTP with OKHttp to remove the conflict. My changes are in my fork in github: https://github.com/rawslaw/RallyRestToolkitForJava

Android Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 29092

I'm try to play a loading animation on my loading screen, and I read somewhere that android doesn't support gifs so either you have to break in into frames and then play it or we can use the Movie class.
Heres the leading activity -
package com.myapp.mehul.login.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.myapp.mehul.login.MYGIFView;
import com.myapp.mehul.login.MainActivity;
import com.myapp.mehul.login.R;
import com.myapp.mehul.login.app.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/**
* Created by mehul on 2/6/16.
*/
public class LoadingScreen extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 1000;
/** Called when the activity is first created. */
private Socket mSocket;
String you;
String opponentId;
String username;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new MYGIFView(getApplicationContext()));
//initialise the socket
mSocket.connect();
//call add user
mSocket.emit("add user");
//start a listener for opponent
mSocket.on("opponent", onOpponent);
//initialise the username
username = getIntent().getExtras().getString("username");
}
private Emitter.Listener onOpponent = new Emitter.Listener(){
#Override
public void call(final Object... args){
LoadingScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
you = data.getString("you");
opponentId = data.getString("opponent");
Log.d("LoadingScreen", data.toString());
//setResult(RESULT_OK, i);
finish();
} catch (JSONException e) {
return;
}
Intent i = new Intent(LoadingScreen.this, MainActivity.class);
i.putExtra("opponentId", opponentId);
i.putExtra("you", you);
i.putExtra("username", username);
Log.d("goToChat", username);
startActivity(i);
}
});
}
};
#Override
public void onBackPressed(){
AlertDialog.Builder builder = new AlertDialog.Builder(LoadingScreen.this);
builder.setMessage("I knew you didn't have BALLS.").setCancelable(
false).setPositiveButton("I am a LOSER",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//send the logout information to the server
JSONObject discon = new JSONObject();
try {
discon.put("opponent", opponentId);
discon.put("you", you);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSocket.emit("discon", discon);
mSocket.disconnect();
//finish the current activity.
Intent intent = new Intent(LoadingScreen.this, MainMenu.class);
startActivity(intent);
LoadingScreen.this.finish();
}
}).setNegativeButton("I'll fkin face it",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
In the above code I've set content view by passing it an instance of MYGIFView.class -
Heres MYGIFView.class
package com.myapp.mehul.login;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.view.View;
import java.io.InputStream;
/**
* Created by mehul on 2/7/16.
*/
public class MYGIFView extends View{
Movie movie,movie1;
InputStream is=null,is1=null;
long moviestart;
public MYGIFView(Context context) {
super(context);
is=context.getResources().openRawResource(+ R.drawable.loading);
movie=Movie.decodeStream(is);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
long now=android.os.SystemClock.uptimeMillis();
System.out.println("now="+now);
if (moviestart == 0) { // first time
moviestart = now;
}
System.out.println("\tmoviestart="+moviestart);
int relTime = (int)((now - moviestart) % movie.duration()) ;
System.out.println("time="+relTime+"\treltime="+movie.duration());
movie.setTime(relTime);
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
this.invalidate();
}
}
The loading activity IS creating an instance of MYGIFView.class and it logs the data but then it gives fatal signal 11. I tried to search but I didn't get any answer.
console log -
02-07 12:22:30.321 29092-29092/? I/art: Late-enabling -Xcheck:jni
02-07 12:22:30.341 29092-29102/? I/art: Debugger is no longer active
02-07 12:22:30.422 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.422 29092-29092/? D/LoginActivity: already logged in
02-07 12:22:30.425 29092-29092/? I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71360781
02-07 12:22:30.487 29092-29092/? D/MainMenu: painted again
02-07 12:22:30.490 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.554 29092-29149/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-07 12:22:30.559 29092-29092/? D/Atlas: Validating map...
02-07 12:22:30.596 29092-29149/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030_msm8974_LA.BF.1.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 04/15/15 Wed
Local Branch: mybranch9068252
Remote Branch: quic/LA.BF.1.1.1_rb1.19
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030 + NOTHING
02-07 12:22:30.597 29092-29149/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-07 12:22:30.611 29092-29149/? D/OpenGLRenderer: Enabling debug mode 0
02-07 12:22:30.660 29092-29092/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#387f1572 time:71361016
02-07 12:22:31.898 29092-29092/com.myapp.mehul.login D/go to chat: was called
02-07 12:22:31.899 29092-29092/com.myapp.mehul.login I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71362255
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: now=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: moviestart=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: time=0 reltime=1850
02-07 12:22:32.007 29092-29092/com.myapp.mehul.login A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 29092 (app.mehul.login)
02-07 12:22:32.541 29092-29092/com.myapp.mehul.login W/app.mehul.login: type=1701 audit(0.0:302): auid=4294967295 uid=10250 gid=10250 ses=4294967295 subj=u:r:untrusted_app:s0 reason="memory violation" sig=11
I received a batch for this question which means its being viewed a lot, so I'll answer this question -
What I figured out was the line below was throwing the error -
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
Now the problem is that this error specifically can be caused by lots of reasons, its never a specific reason.. the reason mine wasn't working out was because my device didn't work well with hardware acceleration, so I just had to disable it in the manifest application, like this -
<android:hardwareAccelerated="false">
Now its possible that the reason might not be the same....but the core reason is the same, its memory related, and most chances are its a bug in the firmware of the device or emulator you are testing upon.
In the Manifest set in your activity :
<activity
android:name="LoadingScreen"
android:hardwareAccelerated="false">
</activity>
I got here with the exact same problem but in React Native, so I will put a solution for those who need it too. The error may be triggered by react-native-webview and/or React Navigation. In some cases, like me, you don't want to disable Hardware Acceleration on the whole app, so here's a workaround:
react-native-webview
<WebView
androidHardwareAccelerationDisabled
source={source}
/>
React Navigation 5
<NavigationContainer>
<Stack.Navigator initialRouteName="HomeScreen">
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{
animationEnabled: false,
}}
/>
</Stack.Navigator>
</NavigationContainer>
https://github.com/react-native-webview/react-native-webview/issues/575

Sending String to PHP file via android application

I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));

Categories

Resources