Hello people of stack....
Please see my class code and my LogCat below...
I am getting a force close when trying to connect. If someone could help me to figure out why it would be much appreciated.
Basically what the code is doing is:
Taking an IP Address from an intent.
Connecting to the IP with port 32
Then send a command, wait for response and the send another command.
After the 2 commands our sent I should get a response of "SNX_COM>"
Once the connection is established, I want the connection to stay open to send specific commands on button click.
Please help :)
package com.smarte.smartipcontrol;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
public class IPControl extends Activity {
private Socket socket;
private String serverIpAddress = "com.smarte.smartipcontrol.ACTU_IP";
private static final int REDIRECTED_SERVERPORT = 32;
public PrintWriter out;
public BufferedReader in;
public String data;
public Object pd;
public void getModel(View view) {
try {
out.println("[m\r\n");
//System.out.print("root\r\n");
while(!in.ready());
String textStatus = readBuffer();
} catch(IOException e) {}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_ipcontrol);
try{
this.pd = ProgressDialog.show(this, "Loading..", "Please Wait...", true, false);
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
} catch (IOException e) {}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//resultis the data returned from doInbackground
IPControl.this.data = result;
if (IPControl.this.pd != null) {
((Dialog) IPControl.this.pd).dismiss();
}
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else return msg;
}
}
Logcat.......
12-03 15:39:56.346: E/AndroidRuntime(2697): FATAL EXCEPTION: AsyncTask #5
12-03 15:39:56.346: E/AndroidRuntime(2697): java.lang.RuntimeException: An error occured while executing doInBackground()
12-03 15:39:56.346: E/AndroidRuntime(2697): at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-03 15:39:56.346: E/AndroidRuntime(2697): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-03 15:39:56.346: E/AndroidRuntime(2697): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-03 15:39:56.346: E/AndroidRuntime(2697): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-03 15:39:56.346: E/AndroidRuntime(2697): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-03 15:39:56.346: E/AndroidRuntime(2697): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-03 15:39:56.346: E/AndroidRuntime(2697): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-03 15:39:56.346: E/AndroidRuntime(2697): at java.lang.Thread.run(Thread.java:856)
12-03 15:39:56.346: E/AndroidRuntime(2697): Caused by: java.lang.NullPointerException
12-03 15:39:56.346: E/AndroidRuntime(2697): at com.smarte.smartipcontrol.IPControl$AsyncAction.doInBackground(IPControl.java:71)
12-03 15:39:56.346: E/AndroidRuntime(2697): at com.smarte.smartipcontrol.IPControl$AsyncAction.doInBackground(IPControl.java:1)
12-03 15:39:56.346: E/AndroidRuntime(2697): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-03 15:39:56.346: E/AndroidRuntime(2697): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-03 15:39:56.346: E/AndroidRuntime(2697): ... 4 more
I think your problem is here:
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
I can't find where your serverIpAddress is assigned, thus you get NullPointerException.
Related
This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 9 years ago.
The idea is when the TCP server receives a String message, if it is equal to "::turnOnBluetoothOn::". Will simply turn on the bluetooth on the device. By using the runCommand Method of the MessageHandler class. The problem is that I am getting the error Can't create handler inside thread that has not called Looper.prepare()
Here is my code:
import android.os.Looper;
import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClient
{
private String serverMessage;
// <<<<<<< .mine
public static final String SERVERIP = "xx.xxx.xx.xx"; // your computer IP
public static final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedReader in;
// Test for Thread
private volatile Looper mMyLooper;
/**
* Constructor of the class. OnMessagedReceived listens for the messages
* received from server
*/
public TCPClient(OnMessageReceived listener)
{
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message
* text entered by client
*/
public void sendMessage(String message)
{
if (out != null && !out.checkError())
{
out.println(message);
out.flush();
}
}
public void stopClient()
{
mRun = false;
}
public void run()
{
mRun = true;
try
{
// here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
// create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try
{
// send the message to the server
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
// receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// in this while the client listens for the messages sent by the
// server
while (mRun)
{
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null)
{
// call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
System.out.println(serverMessage);
MessageHandler handler = new MessageHandler(serverMessage);
handler.runCommand();
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '"
+ serverMessage + "'");
} catch (Exception e)
{
Log.e("TCP", "S: Error", e);
}
finally
{
// the socket must be closed. It is not possible to reconnect to
// this socket
// after it is closed, which means a new socket instance has to
// be created.
socket.close();
}
} catch (Exception e)
{
Log.e("TCP", "C: Error", e);
}
}
// Declare the interface. The method messageReceived(String message) will
// must be implemented in the MyActivity
// class at on asynckTask doInBackground
public interface OnMessageReceived
{
public void messageReceived(String message);
}
}
//AND THIS IS THE HANDLER CLASS
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
public class MessageHandler extends Activity
{
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private String Instruction;
MessageHandler(String Command)
{
Instruction = Command;
}
public void runCommand()
{
if (Instruction.equals("::turnBluetoothOn::"))
{
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
return;
}
}
}
Update:
Here is the LogCat:
03-01 18:16:09.486: I/System.out(4752): ::turnBluetoothOn::
03-01 18:16:09.526: D/AndroidRuntime(4752): Shutting down VM
03-01 18:16:09.526: W/dalvikvm(4752): threadid=1: thread exiting with uncaught exception (group=0x4193a700)
03-01 18:16:09.546: E/AndroidRuntime(4752): FATAL EXCEPTION: main
03-01 18:16:09.546: E/AndroidRuntime(4752): java.lang.NullPointerException
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.example.myactivity.MessageHandler.runCommand(MessageHandler.java:22)
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.example.myactivity.TCPClient$1.run(TCPClient.java:108)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.os.Handler.handleCallback(Handler.java:730)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.os.Handler.dispatchMessage(Handler.java:92)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.os.Looper.loop(Looper.java:137)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-01 18:16:09.546: E/AndroidRuntime(4752): at java.lang.reflect.Method.invokeNative(Native Method)
03-01 18:16:09.546: E/AndroidRuntime(4752): at java.lang.reflect.Method.invoke(Method.java:525)
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-01 18:16:09.546: E/AndroidRuntime(4752): at dalvik.system.NativeStart.main(Native Method)
try this:
if (serverMessage != null && mMessageListener != null)
{
// call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
MessageHandler handler = new MessageHandler(serverMessage);
handler.runCommand();
}
});
}
According to the error information,you create handler inside a non-ui thread, you have declared mMyLooper,why not use it?
so my advice is that add this code:
mMyLooper = Looper.getMainLooper();
Looper.prepare();
before while (mRun).
i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
I have an android application project that connect to PHP server that I write it in codeigniter.
My JSONparser is:
package com.example.com.tourism;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and my activity java code that connect to the server is
package com.example.com.tourism;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SignUp extends Activity {
EditText first,last,birth ,pass;
private ProgressDialog pDialog;
private static String url_create_user = "http://10.0.2.2/tourism/index.php/site/register";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
Button signUp=(Button)findViewById(R.id.sign_up);
first =(EditText) findViewById(R.id.edfname);
last =(EditText) findViewById(R.id.edlname);
pass =(EditText) findViewById(R.id.edpass);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createnewuser().execute();
}
});
}
class Createnewuser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUp.this);
pDialog.setMessage("Creating User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = first.getText().toString();
String price = last.getText().toString();
String description = pass.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name", name));
params.add(new BasicNameValuePair("last_name", price));
params.add(new BasicNameValuePair("password", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
and the error in log cat is
07-07 11:30:44.159: E/JSON Parser(20514): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-07 11:30:44.189: W/dalvikvm(20514): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-07 11:30:44.229: E/AndroidRuntime(20514): FATAL EXCEPTION: AsyncTask #1
07-07 11:30:44.229: E/AndroidRuntime(20514): java.lang.RuntimeException: An error occured while executing doInBackground()
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.lang.Thread.run(Thread.java:856)
07-07 11:30:44.229: E/AndroidRuntime(20514): Caused by: java.lang.NullPointerException
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:98)
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:1)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-07 11:30:44.229: E/AndroidRuntime(20514): ... 4 more
07-07 11:30:44.429: I/Choreographer(20514): Skipped 49 frames! The application may be doing too much work on its main thread.
07-07 11:30:44.779: I/Choreographer(20514): Skipped 222 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.069: I/Choreographer(20514): Skipped 149 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.369: I/Choreographer(20514): Skipped 194 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.459: I/Choreographer(20514): Skipped 50 frames! The application may be doing too much work on its main thread.
07-07 11:30:46.019: E/WindowManager(20514): Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): android.view.WindowLeaked: Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.Dialog.show(Dialog.java:281)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$Createnewuser.onPreExecute(SignUp.java:75)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.execute(AsyncTask.java:534)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$1.onClick(SignUp.java:57)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View.performClick(View.java:4204)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View$PerformClick.run(View.java:17355)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.handleCallback(Handler.java:725)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Looper.loop(Looper.java:137)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:30:46.019: E/WindowManager(20514): at dalvik.system.NativeStart.main(Native Method)
i don't know where the problem is, please help me
is my code incorrect ???
if any one have correct code please give it to me i am using codeigniter for php and this is the code that i call it above
function register_get()
{
$json = array('status' => false );
if($this->input->post()==null){
$this -> response($json, 200);
}
$firstname = $this->post("first_name");
$lastname = $this->post("last_name");
$password = $this->post("password");
if(!$firstname || !$lastname || !$password){
$json['status'] = "wrong insert";
$this -> response($json, 200);
}
$this->load->model('Data_model');
$result = $this->Data_model->search($firstname, $lastname);
if($result)
{
$this->Data_model->insert($firstname,$lastname,$password);
$json['status'] = true;
}
// here if false..
$this -> response($json, 200);
}
There are issues with your PHP. You are not passing back any JSON. You will need to change your script to encode your array into JSON.
$result = json_encode($json)
Returning the actual JSON will help. Make sure you are not returning any HTML either. Your Java is trying to parse a JSON response, but you are responding with <!DOCTYPE...
I'm hoping you can all help me out here.
Basically I have been having a few problems with my app. My previous questions on Stack have now all been solved so thanks to everyone who helped me out.
I am now getting a NPE but no idea why.
Basically my code is:
Connecting to a device (IP address from an intent and fixed port of 32)
Once connected send the command "root/r/n" twice. (This is the login for the device not the actual connection, the connection is not protected.
Once there is return of "SNX_COM>" or "SCX_COM>" await commands.
I then want to be able to send them commands from a button click.
The problem I have is that I cannot get the initial connection active. It would be grateful if someone could help me.
Java class:
package com.smarte.smartipcontrol;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
public class IPControl extends Activity {
private Socket socket;
private static final int REDIRECTED_SERVERPORT = 32;
public PrintWriter out;
public BufferedReader in;
public String data;
public Object pd;
//get the message from intent
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
public void getModel(View view) {
try {
out.println("[m\r\n");
//System.out.print("root\r\n");
while(!in.ready());
String textStatus = readBuffer();
} catch(IOException e) {
e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_ipcontrol);
try {
new AsyncAction().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(actu_ip);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
out.println("[c,l#,i5,o*\r\n");
while (! in .ready());
readBuffer();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
IPControl.this.data = result;
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else if(msg.indexOf("SCX_COM> ") != -1) return msg.substring(0, msg.indexOf("SCX_COM> "));
else return msg;
}
}
LogCat:
12-07 09:29:24.596: E/AndroidRuntime(772): FATAL EXCEPTION: main
12-07 09:29:24.596: E/AndroidRuntime(772): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.smarte.smartipcontrol/com.smarte.smartipcontrol.IPControl}: java.lang.NullPointerException
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.os.Handler.dispatchMessage(Handler.java:99)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.os.Looper.loop(Looper.java:137)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.reflect.Method.invokeNative(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.reflect.Method.invoke(Method.java:511)
12-07 09:29:24.596: E/AndroidRuntime(772): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-07 09:29:24.596: E/AndroidRuntime(772): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-07 09:29:24.596: E/AndroidRuntime(772): at dalvik.system.NativeStart.main(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): Caused by: java.lang.NullPointerException
12-07 09:29:24.596: E/AndroidRuntime(772): at com.smarte.smartipcontrol.IPControl.<init>(IPControl.java:29)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.Class.newInstanceImpl(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.Class.newInstance(Class.java:1319)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
12-07 09:29:24.596: E/AndroidRuntime(772): ... 11 more
Thanks in advanced.
The problem that prevents your app to start is in these two lines:
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
I can't use getIntent() in the initialization, you should move it to the onCreate():
Intent intent;
String actu_ip;
#Override
public void onCreate(Bundle savedInstanceState) {
....
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
....
}
Regards.
I'm trying to connect to a database on my server. I've only just started working with AsyncTask since it was recommend to me. Before that I had the HTTP request on the main UI thread which of course meant it didn't work. It's working a little better now but I'm still having problems. If my server is off I get a force close. If you look at my code below I included a toast to tell me if the connection could not be established. However this is not showing.
Is there something I need to change in order to get it to stop Force closing and just show the toast?
When I have my server on and the database is up I looked at the logcat and my android app does retrieve the data but it's in the logcat and not presented on the page. Some of this code is from tutorials and searching google so I know that the "// PARSING DATA" bit only counts the length of the data at the moment and nothing else. I presume that's where I need to add the code for it to be displayed. Just goes to show how new this is all to me.
Really getting frustrated by all this which is definitely not helping :(.
Here is my code:
package com.android.history;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CurrentSeasonDrivers extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentseason_drivers);
new HttpTask().execute();
}
private static class HttpTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
doStuff();
return null;
}
public static void doStuff() {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
HttpResponse response;
HttpEntity entity;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// HTTP POST REQUEST
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(null, "Could not connect to server", Toast.LENGTH_LONG).show();
}
// CONVERT RESPONSE TO STRING
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result = sb.toString();
Log.i("json string", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// PARSING DATA
String drivername;
String drivesfor;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
System.out.println("Length " + jArray.length());
Log.d("DB", "Length " + jArray.length());
for (int i = 0; i < jArray.length(); i++) {
System.out.println("counter " + i);
json_data = jArray.getJSONObject(i);
drivername = json_data.getString("Driver_full_name");
drivesfor = json_data.getString("Drives_for");
System.out.println("Drives_for" + drivesfor);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
}
Here are the errors in my log_cat:
08-22 12:26:39.405: E/log_tag(14327): Error in http connectionorg.apache.http.conn.HttpHostConnectException: Connection to http://192.168.0.13 refused
08-22 12:26:39.405: W/dalvikvm(14327): threadid=13: thread exiting with uncaught exception (group=0x40a051f8)
08-22 12:26:39.455: E/AndroidRuntime(14327): FATAL EXCEPTION: AsyncTask #2
08-22 12:26:39.455: E/AndroidRuntime(14327): java.lang.RuntimeException: An error occured while executing doInBackground()
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.lang.Thread.run(Thread.java:856)
08-22 12:26:39.455: E/AndroidRuntime(14327): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.Handler.<init>(Handler.java:121)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.widget.Toast$TN.<init>(Toast.java:317)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.widget.Toast.<init>(Toast.java:91)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.widget.Toast.makeText(Toast.java:233)
08-22 12:26:39.455: E/AndroidRuntime(14327): at com.android.history.CurrentSeasonDrivers$HttpTask.doStuff(CurrentSeasonDrivers.java:74)
08-22 12:26:39.455: E/AndroidRuntime(14327): at com.android.history.CurrentSeasonDrivers$HttpTask.doInBackground(CurrentSeasonDrivers.java:44)
08-22 12:26:39.455: E/AndroidRuntime(14327): at com.android.history.CurrentSeasonDrivers$HttpTask.doInBackground(CurrentSeasonDrivers.java:1)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-22 12:26:39.455: E/AndroidRuntime(14327): ... 5 more
doInBackground runs on a separate thread. You cannot show a Toast from a chaild thread.
use the following code instead, inside the catch block.
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(null, "Could not connect to server", Toast.LENGTH_LONG).show();
}
});
Toast should be shown through UI thread. Android does not allow to modify UI from background thread. As Umesh suggested.
And one more thing that may cause crash on following line
jArray = new JSONArray(result);
here in case if the code comae on this line after above two exceptions then result will null.
so you should add a null check above this line like
if(null != result){
jArray = new JSONArray(result);
}
else{
//Do something else
}