I'm trying to make an app that connects to my tcp server on my pc to send text but every time I start the thread, my app crashes. please help. I just started using android studio so im not that familiar with it.
Here's my code:
package com.example.alex.hahanice;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Handler UIHandler;
Thread Thread1 = null;
public static final int SERVERPORT = 6000;
public static final String SERVERIP = "192.168.1.76";
#Override
protected void onCreate(Bundle savedInstanceState) {
this.Thread1 = new Thread(new Thread1());
this.Thread1.start();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
View view;
runOnUiThread(new Runnable() {
public void run() {
Thread1.start();
}
});
}
class Thread1 implements Runnable
{
public void run() {
Socket socket = null;
try
{
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
socket = new Socket(serverAddr, SERVERPORT);
Thread2 commThread = new Thread2(socket);
new Thread(commThread).start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Thread2 implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public Thread2(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void run()
{
while(!Thread.currentThread().isInterrupted())
{
try
{
String read = input.readLine();
if(read != null)
{
//UIHandler.post(new updateUIThread(read));
}
else
{
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Here's what the debugger says when I click on the button to start the thread to connect to my pc
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alex.hahanice, PID: 3772
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4659)
at android.view.View$PerformClick.run(View.java:19462)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5692)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4659)
at android.view.View$PerformClick.run(View.java:19462)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5692)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalThreadStateException: Thread already started
at java.lang.Thread.checkNotStarted(Thread.java:871)
at java.lang.Thread.start(Thread.java:1025)
at com.example.alex.hahanice.MainActivity$1.run(MainActivity.java:50)
at android.app.Activity.runOnUiThread(Activity.java:5001)
at com.example.alex.hahanice.MainActivity.onClick(MainActivity.java:48)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4659)
at android.view.View$PerformClick.run(View.java:19462)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5692)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
You are starting Thread at onCreate()
this.Thread1 = new Thread(new Thread1());
this.Thread1.start();
Then again starting the same thread at onClick()
Your problem is on this line:
Thread Thread1 = null;
You are setting the thread to a null value and that's where it says the error is coming from. Try assigning it a different value and see if that changes anything.
Related
I'm trying to run a code in my android studio emulator but after I run it, the emulator keeps showing "(App name) has stopped. Open app again".
This is an app to get accelerometer and gyro sensor data from Android wear.
I've checked the logcat and found this error in the process.
03-06 04:18:57.364 3189-3189/com.drejkim.androidwearmotionsensors E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.drejkim.androidwearmotionsensors, PID: 3189
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.hardware.Sensor.getStringType()' on a null object reference
at com.drejkim.androidwearmotionsensors.SensorFragment.onCreateView(SensorFragment.java:63)
at android.app.Fragment.performCreateView(Fragment.java:2353)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:563)
at android.support.wearable.view.FragmentGridPagerAdapter.finishUpdate(FragmentGridPagerAdapter.java:196)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1161)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1008)
at android.support.wearable.view.GridViewPager.onMeasure(GridViewPager.java:1322)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.wearable.view.WatchViewStub.onMeasure(WatchViewStub.java:136)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:690)
at android.view.View.measure(View.java:19857)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1675)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6338)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
at android.view.Choreographer.doCallbacks(Choreographer.java:686)
at android.view.Choreographer.doFrame(Choreographer.java:621)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
And here're three of my java codes:
SensorFragments.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SensorFragment extends Fragment implements SensorEventListener {
private static final float SHAKE_THRESHOLD = 1.1f;
private static final int SHAKE_WAIT_TIME_MS = 250;
private static final float ROTATION_THRESHOLD = 2.0f;
private static final int ROTATION_WAIT_TIME_MS = 100;
private View mView;
private TextView mTextTitle;
private TextView mTextValues;
private SensorManager mSensorManager;
private Sensor mSensor;
private int mSensorType;
private long mShakeTime = 0;
private long mRotationTime = 0;
public static SensorFragment newInstance(int sensorType) {
SensorFragment f = new SensorFragment();
// Supply sensorType as an argument
Bundle args = new Bundle();
args.putInt("sensorType", sensorType);
f.setArguments(args);
return f;
}
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if(args != null) {
mSensorType = args.getInt("sensorType");
}
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(mSensorType);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.sensor, container, false);
mTextTitle = (TextView) mView.findViewById(R.id.text_title);
mTextTitle.setText(mSensor.getStringType());
mTextValues = (TextView) mView.findViewById(R.id.text_values);
return mView;
}
#Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
// If sensor is unreliable, then just return
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
{
return;
}
mTextValues.setText(
"x = " + Float.toString(event.values[0]) + "\n" +
"y = " + Float.toString(event.values[1]) + "\n" +
"z = " + Float.toString(event.values[2]) + "\n"
);
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
detectShake(event);
}
else if(event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
detectRotation(event);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// References:
// - http://jasonmcreynolds.com/?p=388
// - http://code.tutsplus.com/tutorials/using-the-accelerometer-on-android--mobile-22125
private void detectShake(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mShakeTime) > SHAKE_WAIT_TIME_MS) {
mShakeTime = now;
float gX = event.values[0] / SensorManager.GRAVITY_EARTH;
float gY = event.values[1] / SensorManager.GRAVITY_EARTH;
float gZ = event.values[2] / SensorManager.GRAVITY_EARTH;
// gForce will be close to 1 when there is no movement
float gForce = FloatMath.sqrt(gX*gX + gY*gY + gZ*gZ);
// Change background color if gForce exceeds threshold;
// otherwise, reset the color
if(gForce > SHAKE_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
private void detectRotation(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mRotationTime) > ROTATION_WAIT_TIME_MS) {
mRotationTime = now;
// Change background color if rate of rotation around any
// axis and in any direction exceeds threshold;
// otherwise, reset the color
if(Math.abs(event.values[0]) > ROTATION_THRESHOLD ||
Math.abs(event.values[1]) > ROTATION_THRESHOLD ||
Math.abs(event.values[2]) > ROTATION_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
}
MainActivity.Java:
package com.drejkim.androidwearmotionsensors;
import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.DotsPageIndicator;
import android.support.wearable.view.GridViewPager;
import android.support.wearable.view.WatchViewStub;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override public void onLayoutInflated(WatchViewStub stub) {
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new SensorFragmentPagerAdapter(getFragmentManager()));
DotsPageIndicator indicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
indicator.setPager(pager);
}
});
}
}
SensorFragmentPagerAdapter.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.app.FragmentManager;
import android.hardware.Sensor;
import android.support.wearable.view.FragmentGridPagerAdapter;
public class SensorFragmentPagerAdapter extends FragmentGridPagerAdapter {
private int[] sensorTypes = {
Sensor.TYPE_ACCELEROMETER,
Sensor.TYPE_GYROSCOPE
};
public SensorFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getFragment(int row, int column) {
return SensorFragment.newInstance(sensorTypes[column]);
}
#Override
public int getRowCount() {
return 1; // fix to 1 row
}
#Override
public int getColumnCount(int row) {
return sensorTypes.length;
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.drejkim.androidwearmotionsensors" >
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can someone help me out? I got this code from some source and I don't know how to fix it since the logcat is showing a long fatal exception script highlighted in red. Thank you, I'll really appreciate it if someone can help.
From the error message in LogCat you can read that mSensor is null when you try to execute
mTextTitle.setText(mSensor.getStringType());
This means that the your sensor manager is unable to find a default sensor that matches the requested type
mSensor = mSensorManager.getDefaultSensor(mSensorType);
as stated in the documentation.
I want to convert byt[] to image in client side. I have tried the below code but it isn't working. I receive the data1 value but not able to convert it to image.
Client Side :
function getPic(name) {
$.post("/Chat/ProfliePic", {
name : name+".png"
}, function(data1, status) {
alert(data1);
$("#profImg").attr("src","data:image/png;base64," + data1);
});
}
Server Side :
package servlets;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ProfliePic")
public class ProfliePic extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProfliePic() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
File f = new File("/Users/shilu/MyProject/Chat/Photo/" + name);
byte[] data = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new java.io.FileInputStream(f));
in.readFully(data);
in.close();
response.setContentType("image/png");
ServletOutputStream out = response.getOutputStream();
out.write(data);
out.flush();
out.close();
}
Please tell me where I went wrong...
I have implemented websocket in spring but the JavaScript client cannot connect to the websocket.
Here is the WebSocketConfig class:
package com.myapp.spring.security.config;
import com.myapp.spring.web.controller.MyWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
//import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.PerConnectionWebSocketHandler;
#Configuration
#EnableWebMvc
#EnableWebSocket
#ComponentScan(basePackages={"com.myapp.spring.*"})
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry
.addHandler(myWebSocketHandler(), "/endpoint")
.setAllowedOrigins("*");
}
#Bean
public WebSocketHandler myWebSocketHandler() {
return new PerConnectionWebSocketHandler(MyWebSocketHandler.class);
}
}
Here is the test.html page that tries to connect to the websocket:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<body>
<p>Going to connect to the WebSocket at /endpoint. Check Console</p>
<button onclick="ss()">Send</button>
</body>
<script type="text/javascript">
var webSocket = new WebSocket("wss://"+document.location.hostname+":8443"+"/endpoint");
webSocket.onopen = function(message) {
processOpen(message);
};
webSocket.onmessage = function(message) {
processMessage(message);
};
webSocket.onclose = function(message) {
processClose(message);
};
webSocket.onerror = function(message) {
processError(message);
};
function processOpen(message) {
console.log("JS: Server Connected... "+message);
}
function processMessage(message) {
console.log("Getting a mess: "+message);
}
function processClose(message) {
console.log("JS: Client disconnected... "+message);
}
function processError(message) { //
console.log("Error occured: "+message);
}
function ss() {
webSocket.send("test");
}
</script>
</html>
I initialized the websocket path to be at /endpoint. This is evident by my server logs which say that this has occurred:
[org.springframework.web.socket.server.support.WebSocketHandlerMapping] (ServerService Thread Pool -- 75) Mapped URL path [/endpoint] onto handler of type [class org.springframework.web.socket.server.support.WebSocketHttpRequestHandler]
When I open up test.html, the connection opens and immediately disconnects. The processOpen(message) and processClose(message) function are immediately called, one after the other. So what am I doing wrong, and how can I fix this?
Your java-script code in test.html looks fine. There could be some issue with Spring Web socket configuration which is closing the connection. Following is the working code for web socket with spring boot. Please compare with your configuration.
Web socket dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketHandler class
#Component
public class EchoHandler extends TextWebSocketHandler {
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
TextMessage echoMessage = new TextMessage("Echo :" + message.getPayload());
System.out.println("Sending "+echoMessage.getPayload());
session.sendMessage(echoMessage);
}
}
WebSocket Controller class
#EnableWebSocket
#Controller
public class WSController implements WebSocketConfigurer {
#Autowired
private EchoHandler echoHandler;
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(echoHandler, "/echo").setAllowedOrigins("*");
}
}
Spring Boot application class
#SpringBootApplication
public class WSApplication {
public static void main(String[] args) {
SpringApplication.run(WSApplication.class, args);
}
}
I am using Android Studio 2.0(preview).
In order to display some info about certain movies , I downloaded Themoviedb.com API Wrapper by holgerbrandl
, added a dependency but just after I add two lines of the wrapper-related code I get a lot of errors I'm not familiar how to deal with.
TmdbMovies movies = new TmdbApi("myAPIkey_here").getMovies();
MovieDb movie = movies.getMovie(5353, "en");
I'm a very inexperienced newbie - thus the need of your help :)
If any details needed, please remind me to add them.
Here's my logcat :
11-29 02:35:26.710 5736-5736/com.example.michael.movienight W/System.err: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
11-29 02:35:26.710 5736-5736/com.example.michael.movienight W/System.err: SLF4J: Defaulting to no-operation (NOP) logger implementation
11-29 02:35:26.710 5736-5736/com.example.michael.movienight W/System.err: SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
11-29 02:35:26.720 5736-5736/com.example.michael.movienight D/AndroidRuntime: Shutting down VM
11-29 02:35:26.720 5736-5736/com.example.michael.movienight E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.michael.movienight, PID: 5736
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.michael.movienight/com.example.michael.movienight.MainActivity}: info.movito.themoviedbapi.tools.MovieDbException: Failed to read configuration
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: info.movito.themoviedbapi.tools.MovieDbException: Failed to read configuration
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:48)
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:35)
at com.example.michael.movienight.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getHeaders(HttpURLConnectionImpl.java:150)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getHeaderFields(HttpURLConnectionImpl.java:210)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getHeaderFields(DelegatingHttpsURLConnection.java:178)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getHeaderFields(HttpsURLConnectionImpl.java)
at info.movito.themoviedbapi.tools.WebBrowser.readHeader(WebBrowser.java:226)
at info.movito.themoviedbapi.tools.WebBrowser.request(WebBrowser.java:143)
at info.movito.themoviedbapi.tools.WebBrowser.request(WebBrowser.java:112)
at info.movito.themoviedbapi.TmdbApi.requestWebPage(TmdbApi.java:64)
at info.movito.themoviedbapi.AbstractTmdbApi.mapJsonResult(AbstractTmdbApi.java:58)
at info.movito.themoviedbapi.AbstractTmdbApi.mapJsonResult(AbstractTmdbApi.java:45)
at info.movito.themoviedbapi.AbstractTmdbApi.mapJsonResult(AbstractTmdbApi.java:40)
at info.movito.themoviedbapi.TmdbConfig.getConfig(TmdbConfig.java:18)
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:44)
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:35)
at com.example.michael.movienight.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
(full MainActivity.java below)
package com.example.michael.movienight;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import info.movito.themoviedbapi.TmdbApi;
import info.movito.themoviedbapi.TmdbMovies;
import info.movito.themoviedbapi.model.MovieDb;
public class MainActivity extends AppCompatActivity {
TextView MainText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MainText = (TextView) findViewById(R.id.main_text);
TmdbMovies movies = new TmdbApi("my_API_key_here").getMovies();
MovieDb movie = movies.getMovie(5353, "en");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm actually learning TheMovieDB API for a school project right now.
Apparently, whenever you want to use the network on android and connect to something, you need to put the statement inside an async task; something to do with network connections not working on the main thread.
To do this you can create a custom AsyncTask in your activity like so:
protected class MovieTask extends AsyncTask<Void, Void, MovieDB> {
protected MovieDB doInBackground(Void... v) {
TmdbMovies movies = new TmdbApi("myAPIkey_here").getMovies();
MovieDb movie = movies.getMovie(5353, "en");
return movie;
}
protected void onPostExecute(MovieDB movie) {
// Do something with movie
}
}
And your MainActivity onCreate would look like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MainText = (TextView) findViewById(R.id.main_text);
MovieTask mt = new MovieTask();
mt.execute();
}
I'm kind of new to android, actually this is my first app. The app is not completed through, i wanted to test the UI, it works fine on AVD, but when I copy the .apk file from bin folder to my phone, it installs fine, but wont work ends up with force close error. I have no idea what's the problem, I saw on other post about parsing the content in edittext, i took out the layout and ran it again still not working. again, I am new to this, please help me.
Mainactivity.java
package com.example.studentapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import com.example.studentapp.ExpandableListAdapter;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DrawerLayout mDrawerLayout;
ExpandableListView mDrawerList;
ExpandableListAdapter listAdapter;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getfragment(125);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
mDrawerList.setAdapter(listAdapter);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
// 2.3 enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);
// Listview Group click listener
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Toast.makeText(getApplicationContext(),
"Group Clicked " + (groupPosition),
Toast.LENGTH_SHORT).show();
//return true for non collapsable items, and false for collapsable items.
if(groupPosition==1 || groupPosition==2)
{ // getfragment(groupPosition);
getActionBar().setTitle(listDataHeader.get(groupPosition));
return true;}
else
return false;
}
});
// Listview Group expanded listener
mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
mDrawerList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
getActionBar().setTitle(listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition));
return false;
}
});
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding header data
listDataHeader.add("Center Details");
// Adding child data
List<String> CentDet = new ArrayList<String>();
CentDet.add("Study Center");
CentDet.add("Information Center");
CentDet.add("Overseas Center");
listDataHeader.add("Login");
listDataHeader.add("PCP Schedule");
listDataHeader.add("Course");
List<String> courseS = new ArrayList<String>();
courseS.add("Study Materials");
courseS.add("Syllabus");
listDataHeader.add("Exam");
List<String> Exams = new ArrayList<String>();
Exams.add("Hall Ticket");
Exams.add("Exam Venue");
Exams.add("Exam Schedule");
Exams.add("Practical Schedule");
Exams.add("Model Question Papers");
listDataHeader.add("Results");
List<String> Resultss= new ArrayList<String>();
Resultss.add("Regular Stream");
Resultss.add("Overseas");
listDataChild.put(listDataHeader.get(0), CentDet); // Header, Child data
listDataChild.put(listDataHeader.get(1), null);
listDataChild.put(listDataHeader.get(2), null);
listDataChild.put(listDataHeader.get(3), courseS);
listDataChild.put(listDataHeader.get(4), Exams);
listDataChild.put(listDataHeader.get(5), Resultss);
}
void getfragment(int x)
{
android.app.FragmentManager fragmentManager1 = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmenttwo lm_fragment = new fragmenttwo();
switch (x)
{
// case 1:
// lm_fragment.fragmenttwoo(1);
//
//break;
case 2:
lm_fragment.fragmenttwoo(2);
break;
case 3:
lm_fragment.fragmenttwoo(3);
break;
case 125:
lm_fragment.fragmenttwoo(125);
break;
}
fragmentTransaction1.replace(R.id.content_frame, lm_fragment);
fragmentTransaction1.commit();
}
}
fragmenttwo.java
package com.example.studentapp;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class fragmenttwo extends Fragment{
public int x;
public fragmenttwo(){}
public void fragmenttwoo(int n)
{
switch(n)
{
case 125:
x = com.example.studentapp.R.layout.sample;
break;
// case 1:
// x = com.example.studentapp.R.layout.login;
// break;
case 2:
x = com.example.studentapp.R.layout.pcpschedule;
break;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
/** * Inflate the layout for this fragment */
// switch(x)
// {
// int idno= r.layout.layoutu want for each case
//put the idno on below as parameter instead of r.layout.sample
//}
return inflater.inflate( x, container, false);
}
}
ExpandableListAdpater.java
package com.example.studentapp;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
any help would be appreciated.
As suggested i used adb and here is the logcat log, it says virtual method getfragment cannot be resolved...
06-03 21:18:03.789: W/dalvikvm(11126): VFY: unable to resolve virtual method 8281: Lcom/example/studentapp/MainActivity;.getFragmentManager ()Landroid/app/FragmentManager;
06-03 21:18:03.789: D/dalvikvm(11126): VFY: replacing opcode 0x6e at 0x0000
06-03 21:18:03.789: D/dalvikvm(11126): VFY: dead code 0x0003-0029 in Lcom/example/studentapp/MainActivity;.getfragment (I)V
06-03 21:18:03.812: W/dalvikvm(11126): VFY: unable to resolve virtual method 8279: Lcom/example/studentapp/MainActivity;.getActionBar ()Landroid/app/ActionBar;
06-03 21:18:03.812: D/dalvikvm(11126): VFY: replacing opcode 0x6e at 0x005b
06-03 21:18:03.812: D/dalvikvm(11126): VFY: dead code 0x005e-008b in Lcom/example/studentapp/MainActivity;.onCreate (Landroid/os/Bundle;)V
06-03 21:18:03.820: I/ApplicationPackageManager(11126): cscCountry is not German : INS
06-03 21:18:03.976: D/AndroidRuntime(11126): Shutting down VM
06-03 21:18:03.976: W/dalvikvm(11126): threadid=1: thread exiting with uncaught exception (group=0x40018578)
06-03 21:18:03.976: E/AndroidRuntime(11126): FATAL EXCEPTION: main
06-03 21:18:03.976: E/AndroidRuntime(11126): java.lang.NoSuchMethodError: com.example.studentapp.MainActivity.getFragmentManager
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.example.studentapp.MainActivity.getfragment(MainActivity.java:223)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.example.studentapp.MainActivity.onCreate(MainActivity.java:42)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.os.Handler.dispatchMessage(Handler.java:99)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.os.Looper.loop(Looper.java:130)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.main(ActivityThread.java:3687)
06-03 21:18:03.976: E/AndroidRuntime(11126): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 21:18:03.976: E/AndroidRuntime(11126): at java.lang.reflect.Method.invoke(Method.java:507)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
06-03 21:18:03.976: E/AndroidRuntime(11126): at dalvik.system.NativeStart.main(Native Method)
Read the logcat: noSuchMethodError on line 223. Double click that line in the logcat and you will end up on line 223 of your MainActivity. Tell us the code.
CscCountry is not German?
Or you are running on a device that does not know getActionBar().