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".
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 am learning from Video Tutorials and I've done exactly the same stuff that is on Video, the only difference is on the video they are doing it on Eclipse and I'm doing it on Android Studio (and I guess it should not affect the outcome). Anyway, what I am trying to do is to get raw XML data from Apple RSS to my Android app and display it on a text field...
I have already added :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
to Manifest file
XML CODE:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1" />
</RelativeLayout>
Main Activity Code:
package com.example.haziqsheikhlocal.top10appsofios;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends ActionBarActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text =(TextView) findViewById(R.id.textView1);
new DownloadData().execute("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=10/xml");
}
#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);
}
private class DownloadData extends AsyncTask<String, Void, String>{
String myXmlData; // This String Will Contain Our XML Data
protected String doInBackground(String... urls) { // It Finds The First Url In BackGround;
try{
myXmlData = downloadXML(urls[0]); // It Downloads the first element in array Element;
}
catch (IOException e){
e.printStackTrace();
return "" ;
}
return null;
}
protected void onPostExecution(String result){
Log.d("OnPostExecute", myXmlData);
text.setText(myXmlData);
}
private String downloadXML (String theUrl) throws IOException {
int BUFFER_SIZE = 2000; // Buffer Size Constant
InputStream is = null; // Declaring Input Stream
String xmlContent = ""; // Creating empty xmlContent variable to store xml data from the web in furutre
try {
URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Open The Connection with url given
conn.setReadTimeout(10000);// Read time Out 10seconds
conn.setConnectTimeout(15000);// connection timeout 15 s
conn.setRequestMethod("GET"); // Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.
conn.setDoInput(true);
int response = conn.getResponseCode();
Log.d("DownloadXML", "The Ressponse Code Is: " + response);
is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int charRead;
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0){
String readString = String.copyValueOf(inputBuffer, 0 , charRead);
xmlContent += readString;
inputBuffer = new char[BUFFER_SIZE];
}
return xmlContent;
}
catch (IOException e){
e.printStackTrace();
return null;
}
}finally {
if(is != null) {
is.close();
}
}
}
}
}
Device LogCat shows no Error & showing the response code 200.
Device LogCat:
03-25 22:53:09.237 1144-1144/com.example.haziqsheikhlocal.top10appsofios I/art﹕ Not late-enabling -Xcheck:jni (already on)
03-25 22:53:12.688 1144-1162/com.example.haziqsheikhlocal.top10appsofios D/OpenGLRenderer﹕ Render dirty regions requested: true
03-25 22:53:12.718 1144-1144/com.example.haziqsheikhlocal.top10appsofios D/﹕ HostConnection::get() New Host Connection established 0xa7b419c0, tid 1144
03-25 22:53:12.771 1144-1144/com.example.haziqsheikhlocal.top10appsofios D/Atlas﹕ Validating map...
03-25 22:53:13.058 1144-1162/com.example.haziqsheikhlocal.top10appsofios D/﹕ HostConnection::get() New Host Connection established 0xa7b41bf0, tid 1162
03-25 22:53:13.122 1144-1162/com.example.haziqsheikhlocal.top10appsofios I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-25 22:53:13.194 1144-1162/com.example.haziqsheikhlocal.top10appsofios D/OpenGLRenderer﹕ Enabling debug mode 0
03-25 22:53:13.256 1144-1162/com.example.haziqsheikhlocal.top10appsofios W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-25 22:53:13.256 1144-1162/com.example.haziqsheikhlocal.top10appsofios W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa7b3ba40, error=EGL_SUCCESS
03-25 22:53:14.100 1144-1156/com.example.haziqsheikhlocal.top10appsofios I/art﹕ Background sticky concurrent mark sweep GC freed 3424(291KB) AllocSpace objects, 0(0B) LOS objects, 14% free, 968KB/1135KB, paused 1.420ms total 737.728ms
03-25 22:53:15.313 1144-1161/com.example.haziqsheikhlocal.top10appsofios D/DownloadXML﹕ The Ressponse Code Is: 200
ADB LogCat shows this Error:
DeviceMonitor: Adb connection Error:An existing connection was forcibly closed by the remote host
ddms: null
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:206)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:698)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
ddms: Client data packet exceeded maximum buffer size [Client pid: 1272]
DeviceMonitor: Adb rejected connection to client '1537': closed
DeviceMonitor: Adb connection Error:An existing connection was forcibly closed by the remote host
DeviceMonitor: Connection attempts: 1
DeviceMonitor: Connection attempts: 2
DeviceMonitor: Connection attempts: 3
DeviceMonitor: Connection attempts: 4
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
What I did to solve this is I went to terminal and used adb kill-server and then adb start-server. I ran the emulator again but still no luck !
Help me please .
Note: Same is happening when I am using gennymotion and I am able to use emulators browser and surf website on it..
I am using the code below to upload files on server. But whenever I run this code my application closes unexpectedly.
Code:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("Registered") public class UploadToServer extends Activity {
TextView messageText;
//Button uploadButton;
int serverResponseCode = 0;
//ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
String uploadFilePath = "/mnt/sdcard/";
String uploadFileName = "service_lifecycle.png";
void uploadToServer(File file, TextView msgText)
{
/************* Php script path ****************/
upLoadServerUri = "http://192.168.1.3/media/UploadToServer.php";
messageText = msgText;
uploadFilePath = file.getParent()+"/";
uploadFileName = file.getName();
try
{
// dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
}
catch(Exception e)
{
msgText.setText("1 : "+e.toString());
}
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
try{
uploadFile(uploadFilePath + "" + uploadFileName);
}catch(Exception e)
{messageText.setText(e.toString());}
}
}).start();
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
// dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
try {
messageText.setText("1");
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
//-=----------
messageText.setText("2");
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
messageText.setText("3");
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
messageText.setText("4");
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
// dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
// dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
// dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
And code for php is:
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
And I am calling this method through:
void openDialogBox()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
Uri uri = data.getData();
File file = new File(uri.toString());
if(uri.toString().startsWith("file:/"))
file = new File(uri.toString().substring(6));
msgTxt.setText(file.getName());
Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
try
{
UploadToServer upToServer = new UploadToServer();
upToServer.uploadToServer(file,msgTxt);
}catch(Exception e)
{
msgTxt.setText(e.toString());
e.printStackTrace();
}
}
}
}
I don't know how but it uploaded two image files before closing down.
Any help is appreciated.
03-07 02:24:35.092: W/Resources(2847): Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f050003}
03-07 02:24:35.252: D/dalvikvm(2847): GC_FOR_ALLOC freed 118K, 6% free 3265K/3448K, paused 40ms, total 45ms
03-07 02:24:35.382: D/(2847): HostConnection::get() New Host Connection established 0xb80e2ae0, tid 2847
03-07 02:24:35.482: W/EGL_emulation(2847): eglSurfaceAttrib not implemented
03-07 02:24:35.502: D/OpenGLRenderer(2847): Enabling debug mode 0
03-07 02:24:40.332: W/IInputConnectionWrapper(2847): showStatusIcon on inactive InputConnection
03-07 02:24:49.832: W/EGL_emulation(2847): eglSurfaceAttrib not implemented
03-07 02:24:50.872: I/Choreographer(2847): Skipped 60 frames! The application may be doing too much work on its main thread.
03-07 02:24:51.612: D/dalvikvm(2847): GC_FOR_ALLOC freed 262K, 9% free
3464K/3792K, paused 348ms, total 351ms
03-07 02:24:52.072: D/dalvikvm(2847): GC_FOR_ALLOC freed 6K, 9% free 3553K/3888K, paused 410ms, total 411ms
03-07 02:24:54.862: I/uploadFile(2847): HTTP Response is : OK: 200
03-07 02:24:55.112: D/AndroidRuntime(2847): Shutting down VM
03-07 02:24:55.122: W/dalvikvm(2847): threadid=1: thread exiting with uncaught exception (group=0xb1a97b90)
03-07 02:24:55.122: E/AndroidRuntime(2847): FATAL EXCEPTION: main
03-07 02:24:55.122: E/AndroidRuntime(2847): Process: com.example.fileuploaddemo, PID: 2847
03-07 02:24:55.122: E/AndroidRuntime(2847): java.lang.NullPointerException
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.widget.Toast.<init>(Toast.java:93)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.widget.Toast.makeText(Toast.java:241)
03-07 02:24:55.122: E/AndroidRuntime(2847): at com.example.fileuploaddemo.UploadToServer$9.run(UploadToServer.java:239)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.os.Handler.handleCallback(Handler.java:733)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.os.Handler.dispatchMessage(Handler.java:95)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.os.Looper.loop(Looper.java:137)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.app.ActivityThread.main(ActivityThread.java:4998)
03-07 02:24:55.122: E/AndroidRuntime(2847): at java.lang.reflect.Method.invokeNative(Native Method)
03-07 02:24:55.122: E/AndroidRuntime(2847): at java.lang.reflect.Method.invoke(Method.java:515)
03-07 02:24:55.122: E/AndroidRuntime(2847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-07 02:24:55.122: E/AndroidRuntime(2847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-07 02:24:55.122: E/AndroidRuntime(2847): at dalvik.system.NativeStart.main(Native Method)
03-07 02:24:58.642: I/Process(2847): Sending signal. PID: 2847 SIG: 9
And whenvever I comment the following part of code it works fine, no error, no unfortunately closing of app
Code:
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200)
{
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
I have a simple code that is supposed to do one task, when the button is clicked download a file, save it to the SD card, and open it. Everything works except during the download, for larger files, the connection drops and the progress bar hangs - almost always at 20%. I have searched and searched and cannot figure out what to do to keep the connection alive and allow the download to complete. Any ideas how to keep the connection alive so the download completes instead of stalling at 20%?
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DownloadTestActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgressDialog = new ProgressDialog(DownloadTestActivity.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/file.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.doc");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[8192];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
private void showPdf() {
// TODO Auto-generated method stub
if(mProgressDialog != null){
mProgressDialog.dismiss();
}
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.doc");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/msword");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/msword");
startActivity(intent);
}
}
}
Edit with logcat information:
--------- beginning of /dev/log/system
W/InputManagerService( 199): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4137b898
--------- beginning of /dev/log/main
D/AndroidRuntime(20673):
D/AndroidRuntime(20673): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20673): CheckJNI is OFF
D/AndroidRuntime(20673): Calling main entry com.android.commands.pm.Pm
D/AndroidRuntime(20673): Shutting down VM
D/dalvikvm(20673): GC_CONCURRENT freed 101K, 82% free 467K/2560K, paused 1ms+0ms
D/dalvikvm(20673): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20673): NOTE: attach of thread 'Binder Thread #3' failed
D/AndroidRuntime(20687):
D/AndroidRuntime(20687): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20687): CheckJNI is OFF
D/AndroidRuntime(20687): Calling main entry com.android.commands.am.Am
I/ActivityManager( 199): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.myapp/.Activity} from pid 20687
D/AndroidRuntime(20687): Shutting down VM
D/dalvikvm(20687): GC_CONCURRENT freed 102K, 81% free 489K/2560K, paused 0ms+0ms
D/jdwp (20687): Got wake-up signal, bailing out of select
D/dalvikvm(20687): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20687): NOTE: attach of thread 'Binder Thread #3' failed
D/dalvikvm(20698): Late-enabling CheckJNI
I/ActivityManager( 199): Start proc com.myapp for activity com.myapp/.Activity: pid=20698 uid=10102 gids={1015, 3003}
I/dalvikvm(20698): Turning on JNI app bug workarounds for target SDK version 10...
V/PhoneStatusBar( 271): setLightsOn(true)
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Displayed com.myapp/.Activity: +197ms
W/InputManagerService( 199): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#4199ed28 (uid=10098 pid=20011)
I/ActivityManager( 199): START {cmp=com.myapp/.Choice} from pid 20698
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
V/PhoneStatusBar( 271): setLightsOn(true)
I/ActivityManager( 199): Displayed com.myapp/.Choice: +93ms
D/ANDRO_ASYNC(20698): Lenght of file: 736768
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
W/NetworkStats( 199): found non-monotonic values; saving to dropbox
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Force stopping package com.myapp uid=10102
I/ActivityManager( 199): Killing proc 20698:com.myapp/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.myapp/.Choice}: app died, no saved state
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
I/ActivityManager( 199): Force finishing activity ActivityRecord{418450c8 com.myapp/.Activity}
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
W/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp/.Activity (server)' ~ Consumer closed input channel or an error occurred. events=0x8
E/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp.Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 199): Attempted to unregister already unregistered input channel '417b41f0 com.myapp/com.myapp.Activity (server)'
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41c7ffc8 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
I/WindowManager( 199): WIN DEATH: Window{4175b280 com.myapp/com.myapp.Choice paused=false}
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41758028 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
W/InputManagerService( 199): Got RemoteException sending setActive(false) notification to pid 20698 uid 10102
D/dalvikvm(20011): GC_CONCURRENT freed 460K, 32% free 9468K/13767K, paused 3ms+4ms
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
I've tried to download your file a few times, looks like download stalls for a few seconds here and there, and it might trigger a timeout in your application. Try to specify timeouts explicitly in range 10-20 seconds.
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet get = new HttpGet("your url comes here");
protected String[] doInBackground(Void... v) {
HttpParams httpParameters = new BasicHttpParams();
// set the timeout in milliseconds until a connection is established
// the default value is zero, that means the timeout is not used
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// set the default socket timeout (SO_TIMEOUT) in milliseconds
// which is the timeout for waiting for data
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient.setParams(httpParameters);
try {
HttpEntity entity = httpclient.execute( get ).getEntity();
FileOutputStream output = new FileOutputStream(outputFile);
entity.writeTo(output);
output.close();
// return something, maybe?
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return null;
}
What seems to be the problem is that process 199 in your logcat seem to be your activity, but then it shows:
I/ActivityManager( 199): Force stopping package com.viperean.atcassistant uid=10102
I/ActivityManager( 199): Killing proc 20698:com.viperean.atcassistant/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.viperean.atcassistant/.atcChoice}: app died, no saved state
(and the second line shows that it is killing your asynctask...).
I don't think there is anything wrong with the download code by itself. I think you should look more in the activity (what are you doing during that time beside that asynctask, what are you displaying on the screen...etc...).
Seems also that you are pretty low in heap space.
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
Those are from the garbage collection and happen just before your app crashed, maybe that could be a problem too?
every thread in Android is being killed by the system if it doesn't respond for more than five minutes. maybe you should consider downloading as a service or overriding the onProgress and get the thread to stay alive
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.