Iam trying to make a connection between my database on the MYSQL(iam using the WAMP server) and android application , but when i run the application an exception is raised , i fixed the log cat and its points to this statement
jArray = new JSONArray(result);
03-18 12:48:59.580: E/AndroidRuntime(458): at org.json.JSONArray.<init>(JSONArray.java:87)
why this exception occur ?and how i can solve it ?
thanks in advanced..
this is my code :
City.php:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("Deal");
$sql=mysql_query("select * from City where Name like 'R%' ");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
the java class:
public class ConnectionActivity extends ListActivity {
int ct_id;
String[] ct_name = null;
JSONArray jArray;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/city.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
// 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 = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// paring data
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
ct_name = new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
ct_id = json_data.getInt("City_ID");
ct_name[i] = json_data.getString("Name");
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
e1.printStackTrace();
}
ListView lv;
lv = getListView();
lv.setTextFilterEnabled(true);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ct_name);
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(this,"You have selected " + ct_name[position],Toast.LENGTH_SHORT).show();
}
}
log:
03-18 13:28:46.923: W/ActivityThread(623): Application Com.Connection is waiting for the debugger on port 8100...
03-18 13:28:46.973: I/System.out(623): Sending WAIT chunk
03-18 13:28:46.983: I/dalvikvm(623): Debugger is active
03-18 13:28:47.174: I/System.out(623): Debugger has connected
03-18 13:28:47.183: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.383: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.583: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.783: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.993: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.193: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.403: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.603: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.803: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.003: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.203: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.413: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.613: I/System.out(623): debugger has settled (1497)
03-18 13:30:17.593: E/log_tag(623): Error in http connectionandroid.os.NetworkOnMainThreadException
03-18 13:30:34.315: E/log_tag(623): Error converting result java.lang.NullPointerException
You get an error as you try to perform HTTP connection on the main thread:
03-18 13:30:17.593: E/log_tag(623): Error in http connectionandroid.os.NetworkOnMainThreadException
As far as I can see, the HTTP code is correct, but you are running it on the UI thread. This is not allowed. You need to perform such long actions on a background thread. Android gives you a very easy to use facilities to perform long action on the background and publish the results on the main (UI) thread. One of the most useful is AsyncTask. I would recommend that you read Painless Threading, as it will help you a lot IMO.
Related
I am trying to connect to a FTP server and displaying data on my android app after pulling it from the server, but I have not been able to figure it out. I am facing the above mentioned problem. FTPDownloader class is inside the MainActivity Class and I call it by
new FTPDownloader().execute();. I call the doInBackground() of FTPDownloader() after pressing a button in MainActivity class. But nothing happens as if the doInBackground() method never ran. The app does not freeze though but nothing happens either. Thanks in advance, any help appreciated.
private class FTPDownloader extends AsyncTask<Void, Void, Void> {
FTPClient ftp = null;
InputStream in;
public FTPDownloader() {
ftp = null;
}
public void disconnect() {
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// do nothing as file is already downloaded from FTP server
}
}
}
#Override
protected Void doInBackground(Void... voids) {
try {
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect("12.123.12.123");
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login("user1234","1234" );
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
in = ftp.retrieveFileStream("filePath");
} catch (Exception e) {
e.printStackTrace();
Log.i("FTP", "Error Occurred.");
}
try {
int data = in.read();
while (data != -1) {
String s = "";
char ch = (char) data;
if (ch != ',') {
s = s + ch;
} else {
s = s + " ";
gblprpd.add(s);
data = in.read();
}
}
in.close();
for (int i = 0; i < gblprpd.size(); ++i) {
String s = "";
for (int j = 0; j < 9; ++j) {
++i;
s = s + gblprpd.get(i);
}
dta.add(s);
}
} catch (IOException e) {
e.printStackTrace();
Log.i("FTP", "Error Occurred");
}
disconnect();
return null;
}
#Override
protected void onPreExecute()
{
}
#Override
protected void onPostExecute(Void cd) {
TextView output = (TextView) findViewById(R.id.output);
output.setText("Data Retrieved:");
for (int k = 0; k < dta.size(); ++k) {
roes.get(k + 1).setText(dta.get(k));
}
for (int k = dta.size() + 1; k < 16; ++k)
roes.get(k).setVisibility(View.GONE);
ScrollView sv = (ScrollView) findViewById(R.id.sv);
sv.setVisibility(View.VISIBLE);
HorizontalScrollView hsv = (HorizontalScrollView) findViewById(R.id.hsv);
hsv.setVisibility(View.VISIBLE);
}
}
}
The logs are:
06-12 21:08:30.797 23404-23469/com.example.quickstart I/System.out: 220 Microsoft FTP Service
06-12 21:08:30.800 23404-23469/com.example.quickstart I/System.out: USER user1234
06-12 21:08:30.861 23404-23469/com.example.quickstart I/System.out: 331 Password required
06-12 21:08:30.862 23404-23469/com.example.quickstart I/System.out: PASS 1234
06-12 21:08:30.936 23404-23469/com.example.quickstart I/System.out: 230 User logged in.
06-12 21:08:30.938 23404-23469/com.example.quickstart I/System.out: TYPE I
06-12 21:08:31.018 23404-23469/com.example.quickstart I/System.out: 200 Type set to I.
06-12 21:08:31.019 23404-23469/com.example.quickstart I/System.out: PASV
06-12 21:08:31.082 23404-23469/com.example.quickstart I/System.out: 227 Entering Passive Mode (14,141,70,165,66,149).
06-12 21:08:31.145 23404-23469/com.example.quickstart I/System.out: RETR File\Path
06-12 21:08:31.213 23404-23469/com.example.quickstart I/System.out: 125 Data connection already open; Transfer starting.
06-12 21:08:46.814 23404-23415/com.example.quickstart I/art: Background sticky concurrent mark sweep GC freed 910864(25MB) AllocSpace objects, 0(0B) LOS objects, 27% free, 29MB/40MB, paused 1.234ms total 106.681ms
06-12 21:08:46.976 23404-23415/com.example.quickstart I/art: Background sticky concurrent mark sweep GC freed 926388(25MB) AllocSpace objects, 0(0B) LOS objects, 28% free, 29MB/40MB, paused 1.118ms total 104.876ms
Please help, any help appreciated. Thanks in advance
You are reading bytes off of an FTP connection in onPostExecute(). onPostExecute() is run on the main application thread. Hence, you are doing network I/O on the main application thread.
Move all of your code that uses the FTP connection into doInBackground(). Use the downloaded data in onPostExecute().
Also note that you do not need runOnUiThread() in onPostExecute(), as onPostExecute() runs on the main application ("UI") thread already.
I'm working on register and login activity.
when I type the name, username, and password, the informations accessed android application.
and the Toast show the 'Registration Success' message.
But the data didn't inserted in mysql DB.
How can I solve it? Please help me.
Following is LoginActivity.java
public class LoginActivity extends Activity {
EditText ET_NAME,ET_PASS;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_main);
ET_NAME = (EditText)findViewById(R.id.user_name);
ET_PASS = (EditText)findViewById(R.id.user_pass);
}
public void userReg(View view)
{
startActivity(new Intent(this,RegisterActivity.class));
}
public void userLogin(View view)
{
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("ID", login_name);
intent.putExtra("PW", login_pass);
startActivity(intent);
finish();
}
}
This is BackgroundTask.java
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://35.160.135.119/webapp/register.php";
String login_url = "http://35.160.135.119/webapp/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url)
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (method.equals("login")) {
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("login_name", "UTF-8") + "=" + URLEncoder.encode(login_name, "UTF-8") + "&" +
URLEncoder.encode("login_pass", "UTF-8") + "=" + URLEncoder.encode(login_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if (result.equals("Registration Success...")) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
} else {
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
And this is Register.java
public class RegisterActivity extends Activity {
EditText ET_NAME, ET_USER_NAME, ET_USER_PASS;
String name, user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
ET_NAME = (EditText)findViewById(R.id.name);
ET_USER_NAME = (EditText)findViewById(R.id.new_user_name);
ET_USER_PASS = (EditText)findViewById(R.id.new_user_pass);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name, user_name, user_pass);
finish();
}
}
This is debugging log.
$ adb shell am start -n "com.example.jina.a1105gmdemo/com.example.jina.a1105gmdemo.LoginActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to com.example.jina.a1105gmdemo
Connected to the target VM, address: 'localhost:8605', transport: 'socket'
I/System.out: Sending WAIT chunk
W/ActivityThread: Application com.example.jina.a1105gmdemo is waiting for the debugger on port 8100...
I/dalvikvm: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1484)
I/MultiDex: VM with version 1.6.0 does not have multidex support
I/MultiDex: install
I/MultiDex: MultiDexExtractor.load(/data/app/com.example.jina.a1105gmdemo-46.apk, false)
I/MultiDex: Detected that extraction must be performed.
I/MultiDex: Trying to delete old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.dex of size 2898496
I/MultiDex: Deleted old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.dex
I/MultiDex: Trying to delete old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.zip of size 934986
I/MultiDex: Deleted old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.zip
I/MultiDex: Extraction is needed for file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip
I/MultiDex: Extracting /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2089171779.zip
I/MultiDex: Renaming to /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip
I/MultiDex: Extraction success - length /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip: 934986
I/MultiDex: load found 1 secondary dex files
D/dalvikvm: DexOpt: --- BEGIN 'com.example.jina.a1105gmdemo-46.apk.classes2.zip' (bootstrap=0) ---
D/dalvikvm: DexOpt: --- END 'com.example.jina.a1105gmdemo-46.apk.classes2.zip' (success) ---
D/dalvikvm: DEX prep '/data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip': unzip in 66ms, rewrite 778ms
I/MultiDex: install done
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: ()
OpenGL ES Shader Compiler Version: E031.24.00.08
Build Date: 03/21/14 Fri
Local Branch: AU200+patches_03212014
Remote Branch:
Local Patches:
Reconstruct Branch:
D/OpenGLRenderer: Enabling debug mode 0
D/OpenGLRenderer: GL error from OpenGLRenderer: 0x502
E/OpenGLRenderer: GL_INVALID_OPERATION
D/OpenGLRenderer: GL error from OpenGLRenderer: 0x502
E/OpenGLRenderer: GL_INVALID_OPERATION
D/dalvikvm: threadid=1: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
I/System.out: Thread-1263(HTTPLog):isShipBuild true
I/System.out: Thread-1263(HTTPLog):SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=1: still suspended after undo (sc=1 dc=1)
Disconnected from the target VM, address: 'localhost:8605', transport: 'socket'
put that code in post execute of async task that you want to execute after the async task complete.like..
finish();
and check your webservices for data that you recieved there and try to print the result in logcat what you got from your server script instead of static "success message".
I have an app that downloads the current unix timestamp from the internet. The code for the download task is as follows.
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
}
return null;
}
I run this code in onCreate
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.currenttimestamp.com/").get();
Pattern p = Pattern.compile("current_time = (.*?);");
Matcher m = p.matcher(result);
m.find();
String unixTime = (m.group(1));
timeStamp = Integer.parseInt(unixTime);
endTimeMaths = endTime/1000;
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
} catch (ExecutionException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
}
timeDelta = timeStamp-endTimeMaths;
Log.i("TimeDelta", timeDelta+"");
//If dem boys cheatin
if (timeDelta < 1){
Toast.makeText(SplashActivity.this, "You cheatin boi?", Toast.LENGTH_SHORT).show();
reward=false;
} else if (timeDelta >= 300){
reward = true;
Toast.makeText(SplashActivity.this, "Here is your reward for being gone", Toast.LENGTH_SHORT).show();
}
}
The Exception is as follows
09-04 21:26:42.853 8459-8493/com.firefluxentertainment.retroclicker E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.firefluxentertainment.retroclicker, PID: 8459
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
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:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
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:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:155)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:119)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Since all the code is in try catch braces I have no idea why it would be crashing. Any help is very much appreciated!
This is because you are trying to show toast in a non-UI thread. There are multiple solutions to your problem :
Create a handler in the Activity and pass it along to DownloadTask. Simply send a message in Handler and show the toast.
Another solution is to send the context in DownloadTask and show the toast as
context.runOnUIThread(new Runnable() {
public void run(){
Toast.showToast("your message here")
}
)
You can send the result of your task in onPostExecute() and show Toast there.
Hi there I have 2 classes in order to push a file into an android device.
My Server CLass:
public class FileServer {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File ("C:\\Users\\Petrica\\Desktop\\zzz.txt");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
And my Client Class:
public class TCPClient extends AsyncTask{
#Override
protected Object doInBackground(Object... params) {
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = null;
try {
sock = new Socket("127.0.0.1",13267);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Connecting...");
// receive file
try {
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/zzz.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
// TODO Auto-generated method stub
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
I get an error
09-09 15:52:39.261: E/AndroidRuntime(802): FATAL EXCEPTION: AsyncTask #1
09-09 15:52:39.261: E/AndroidRuntime(802): java.lang.RuntimeException: An error occured while executing doInBackground()
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.lang.Thread.run(Thread.java:841)
09-09 15:52:39.261: E/AndroidRuntime(802): Caused by: java.lang.NullPointerException
09-09 15:52:39.261: E/AndroidRuntime(802): at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:33)
09-09 15:52:39.261: E/AndroidRuntime(802): at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:1)
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-09 15:52:39.261: E/AndroidRuntime(802): ... 4 more
MainActivity:
public class MainActivity extends Activity {
TCPClient tcpc;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.send_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tcpc.execute();
}
});
}
}
Does anyone have an idea what should I do ??? In the future i would like to send 2 files :D .Thanks in advice .
You're really expected to be able to sort out your own NullPointerExceptions: at least I expect it, but when you get past that, your copy code is wrong. You are presently ignoring the count returned by read() and assuming it fills the buffer. It isn't guaranteed to do that. See the Javadoc.
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Use this at both ends, with any buffer size > 0, typically 8192.
I don't think your Socket is connecting, but its hard to tell. IN your log output, it says NullPointerException caused by doInBackground() line 33. You should check line 33 in your editor, and better yet, show us in your post which line is 33. I kind of have a feeling that you call Socket sock = null;, then you try and instantiate a new Socket in a try block, but that fails, so sock still == null, then you call a method on sock, and boom, NPE.
If you are running the Server on a computer, and the AsyncTask on an Android device, you won't be able to try and connect to localhost (127.0.0.1). You should instead try to connect to the internal network ip of your computer (something like 192.168.1.XXX), assuming both devices are on WiFi. If you are running an android emulator, then 127.0.0.1 refers back to the emulated device, and all emulator sessions run on an emulated router that you will have to configure for port forwarding before you can refer to the development machine, see here-->http://developer.android.com/tools/devices/emulator.html#emulatornetworking
As Andras Balazs Lajtha says, it looks like TCPClient isn't ever initialized/created during onCreate(), it is only declared. Since your logcat output shows errors from TCPClient though, I assume you have that code actually running.
In general, when you post a log output that refers to problems with a specific line of code, you should start there, and when you post, tell us or show us which line that is. And of course, if line 33 isn't related to a null Socket object, then I haven't been much help at all :)
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
android.os.NetworkOnMainThreadException . Need to use async task?
(2 answers)
Closed 9 years ago.
What is the error in this code?
I would like to add a facebook page name and get its json data, but there is something error I cannot discover. These are all files I use and added logcat messages:
PagesActivity.java
package com.engahmedphp.facebookcollector;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PagesActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
final Button button = (Button) findViewById(R.id.addPage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(
PagesActivity.this);
alert.setTitle("Add New Page");
alert.setMessage("Enter Page Name OR Valid Facebook Link");
// Set an EditText view to get user input
final EditText input = new EditText(PagesActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
// Do something with value!
String url = "http://graph.facebook.com/"
+ value + "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
// addPageData(value);
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
void addPageData(String pageName) {
String url = "http://graph.facebook.com/" + pageName
+ "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
}
JSONParser.java
package com.engahmedphp.facebookcollector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
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() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
}
LogCat
08-31 03:35:23.031: D/dalvikvm(15972): GC_FOR_ALLOC freed 39K, 6% free 2633K/2792K, paused 65ms, total 68ms
08-31 03:35:23.041: I/dalvikvm-heap(15972): Grow heap (frag case) to 3.767MB for 1136500-byte allocation
08-31 03:35:23.163: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 5% free 3740K/3904K, paused 116ms, total 116ms
08-31 03:35:23.511: D/gralloc_goldfish(15972): Emulator without GPU emulation detected.
08-31 03:35:26.611: I/Choreographer(15972): Skipped 30 frames! The application may be doing too much work on its main thread.
08-31 03:39:40.903: D/dalvikvm(15972): GC_FOR_ALLOC freed 47K, 4% free 4013K/4180K, paused 48ms, total 81ms
08-31 03:39:40.903: I/dalvikvm-heap(15972): Grow heap (frag case) to 4.638MB for 635812-byte allocation
08-31 03:39:41.023: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 4% free 4631K/4804K, paused 111ms, total 111ms
08-31 03:39:41.483: I/Choreographer(15972): Skipped 83 frames! The application may be doing too much work on its main thread.
08-31 03:39:48.701: D/AndroidRuntime(15972): Shutting down VM
08-31 03:39:48.701: W/dalvikvm(15972): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
08-31 03:39:48.741: E/AndroidRuntime(15972): FATAL EXCEPTION: main
08-31 03:39:48.741: E/AndroidRuntime(15972): android.os.NetworkOnMainThreadException
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.PagesActivity$1$1.onClick(PagesActivity.java:49)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Handler.dispatchMessage(Handler.java:99)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Looper.loop(Looper.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invoke(Method.java:525)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 03:39:48.741: E/AndroidRuntime(15972): at dalvik.system.NativeStart.main(Native Method)
You are getting NetworkOnMainThreadException. See How to fix android.os.NetworkOnMainThreadException? . This exception is thrown when an application attempts to perform a networking operation on its main (UI) thread. Do the networking tasks using AsyncTask or inside a new thread. See the Android Documentation on NetworkOnMainThreadException for reasons of this Exception.
Here:
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
you are doing network related stuff on main UI thread. Try to do this in a new thread.
The JSONParser make a HTTP connect in UI thread(The oneClick is invoked in UI thread)and it was fobidden now.
So you need move the network codes to other thread.
In case you have not noticed; StrictMode for network access results in a fatal error as for Android 3.0 (Honeycomb) or later, unless your app is targeting an API version before Honeycomb.
The right way of solving this is to use Android AsyncTask for network access.
The lazy way of handling this is to turn the check of:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
As others mentioned, you shouldn't be doing networking on UI thread to make your app UI responsive.
Try this
public class JsonParser extends AsyncTask<String, Void, JSONObject> {
InputStream is = null;
JSONObject jObj = null;
String json = "";
#Override
protected JSONObject doInBackground(String... params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Put the above class in your activity class, then use new JsonParser().execute(url); to fetch data and update the database.