I am trying to store the data entered by user to MySQL database using PHP in my android app. But whenever the button is clicked, i receive this message "Unfortunately, [app] has stopped working."
public class Register extends Activity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first_screen);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
And here is my JSONParser code.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
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 here is the logcat
02-25 11:25:36.224 2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ Render dirty regions requested: true
02-25 11:25:36.228 2445-2445/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c43550, tid 2445
02-25 11:25:36.271 2445-2445/com.example.user.callarocket D/Atlas﹕ Validating map...
02-25 11:25:36.373 2445-2460/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c438d0, tid 2460
02-25 11:25:36.423 2445-2460/com.example.user.callarocket I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-25 11:25:36.457 2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 11:25:36.500 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:36.500 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1eb880, error=EGL_SUCCESS
02-25 11:25:48.014 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:48.014 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5b6d2a0, error=EGL_SUCCESS
02-25 11:25:48.303 2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa6cb7580 (RippleDrawable) with handle 0xa6c43c60
02-25 11:25:59.147 2445-2465/com.example.user.callarocket D/request!﹕ starting
02-25 11:25:59.207 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:59.207 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1f3be0, error=EGL_SUCCESS
02-25 11:25:59.281 2445-2465/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 11:25:59.299 2445-2465/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.user.callarocket, PID: 2445
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:128)
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:85)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
02-25 11:25:59.599 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:59.599 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1f3e60, error=EGL_SUCCESS
02-25 11:26:00.172 2445-2445/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2dbde5f6 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.callarocket.Register$CreateUser.onPreExecute(Register.java:99)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.user.callarocket.Register.onClick(Register.java:81)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
After Log.i("DATA",json) is added
02-25 12:24:16.222 2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ Render dirty regions requested: true
02-25 12:24:16.225 2750-2750/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c3e550, tid 2750
02-25 12:24:16.259 2750-2750/com.example.user.callarocket D/Atlas﹕ Validating map...
02-25 12:24:16.366 2750-2765/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c3e6f0, tid 2765
02-25 12:24:16.405 2750-2765/com.example.user.callarocket I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-25 12:24:16.433 2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 12:24:16.462 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:16.462 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c118a0, error=EGL_SUCCESS
02-25 12:24:24.841 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:24.842 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5e39720, error=EGL_SUCCESS
02-25 12:24:25.095 2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa6cb2580 (RippleDrawable) with handle 0xa6c3eab0
02-25 12:24:33.820 2750-2768/com.example.user.callarocket D/request!﹕ starting
02-25 12:24:33.862 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:33.863 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5605140, error=EGL_SUCCESS
02-25 12:24:34.027 2750-2768/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 12:24:34.028 2750-2768/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.user.callarocket, PID: 2750
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:128)
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:85)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
02-25 12:24:34.335 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:34.335 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5af7e00, error=EGL_SUCCESS
02-25 12:24:36.361 2750-2750/com.example.user.callarocket I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-25 12:24:36.754 2750-2750/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2dbde5f6 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.callarocket.Register$CreateUser.onPreExecute(Register.java:99)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.user.callarocket.Register.onClick(Register.java:81)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
You have problem in.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
here you have to use which button is clicked. normally we use
switch(v.getId())
{
case your button id :
//Button function
}
You need to be using a parser to parse the string and then cast it to a JSONObject like so -
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONObject jsonObj = (JSONObject) obj;
return jsonObj;
Related
I make an android application on movies. I have a database movies. In the application I display the movies in ListView and I add a new movie.
I have a problem when I try to insert in my dataBase a new movie. Indeed, I have n error in my AsyncTask in the doInBackground but I don't know why. When I use the debugger, I have reject on the begin of the doInBackground at the line :
String title = eTitle.getText().toString();
So I give you my java code :
public class AddMovie extends Activity implements OnClickListener{
// Edit and Button that the user fill
private EditText eTitle, eActors, eDirector, eKind, eDate, eImage, eSummary ;
private Button bAdd;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
//JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
eTitle = (EditText)findViewById(R.id.title);
eActors = (EditText)findViewById(R.id.actors);
eDirector = (EditText)findViewById(R.id.director);
eKind = (EditText)findViewById(R.id.kind);
eDate = (EditText)findViewById(R.id.date);
eImage = (EditText)findViewById(R.id.image);
eSummary = (EditText)findViewById(R.id.summary);
bAdd = (Button)findViewById(R.id.addMovies);
bAdd.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.addMovies:
new AttempMovie().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
default:
break;
}
}
class AttempMovie extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddMovie.this);
pDialog.setMessage("Attempting for add new movie...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
try {
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("title", title));
params.add(new BasicNameValuePair("actors", actors));
params.add(new BasicNameValuePair("director", director));
params.add(new BasicNameValuePair("kind", kind));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("image", image));
params.add(new BasicNameValuePair("summary", summary));
Log.d("request!", "starting");
JSONObject json = JSONfunctions.getJSONfromURL("http://10.0.0.35/BD_Enterprise_Mobility_Movies/add_movie.php");
// checking log for json response
Log.d("Register attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
Log.d("Successfully Register!", json.toString());
return json.getString(TAG_MESSAGE);
}
else
{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Intent i = new Intent(AddMovie.this,MainActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(i);
Toast.makeText(AddMovie.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
I give you also my JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject json = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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);
StringBuilder sb = new StringBuilder();
String line = null;
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());
}
try {
json = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return json;
}
}
And my error in the logcat:
03-20 18:28:19.753: E/AndroidRuntime(14656): FATAL EXCEPTION: AsyncTask #3
03-20 18:28:19.753: E/AndroidRuntime(14656): Process: com.mickKoza.jsonkoza, PID: 14656
03-20 18:28:19.753: E/AndroidRuntime(14656): java.lang.RuntimeException: An error occured while executing doInBackground()
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.lang.Thread.run(Thread.java:818)
03-20 18:28:19.753: E/AndroidRuntime(14656): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:81)
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:1)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-20 18:28:19.753: E/AndroidRuntime(14656): ... 4 more
03-20 18:28:20.184: E/WindowManager(14656): android.view.WindowLeaked: Activity com.mickKoza.jsonkoza.AddMovie has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3e1b7378 V.E..... R......D 0,0-1026,288} that was originally added here
03-20 18:28:20.184: E/WindowManager(14656): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.Dialog.show(Dialog.java:298)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.onPreExecute(AddMovie.java:74)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.execute(AsyncTask.java:535)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie.onClick(AddMovie.java:54)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View.performClick(View.java:4756)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View$PerformClick.run(View.java:19749)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.handleCallback(Handler.java:739)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.dispatchMessage(Handler.java:95)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Looper.loop(Looper.java:135)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Native Method)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Method.java:372)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thank you for your help
Michaël
One (or possibly all) of these views is null:
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
Possibly the view IDs that you're referencing during onCreate to find these views are not correct?
Good day. Please can someone help me with this?
Is it possible to upload images from android to remote database?
I'm able to communicate with my remote database and perform simple operations like read, write, and delete from database but I have a problem when it comes to uploading images. I'v spent my whole day searching trying and reading methods to accomplish this from stackoverflow and other websites.
This is what I have tried
public class MainActivity extends Activity {
Bitmap bitmap1;
byte[]image1byte;
...
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_1) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap1 = BitmapFactory.decodeFile(picturePath);
image1 = (ImageView) findViewById(R.id.imageView1);
image1.setImageBitmap(bitmap1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG,100,stream);
image1byte=stream.toByteArray();
}
and my AsyncTask task is;
class CreateNewMessage extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute(){
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setMessage("Uploading Message...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String topic=inputTopic.getText().toString();
String message=inputMessage.getText().toString();
String other=inputOther.getText().toString();
List<NameValuePair>params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("topic",topic));
params.add(new BasicNameValuePair("message",message));
params.add(new BasicNameValuePair("details",details));
params.add(new BasicNameValuePair("image",sendImage1));
JSONObject json=jsonParser.makeHttpRequest(url_create_message,"GET",params);
try {
response=json.getString(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response",json.toString());
return response;
}
protected void onPostExecute(String response) {
Toast.makeText(getBaseContext(),"Finished..Response= "+response,Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
but I get the following error;
12-12 16:22:47.017 15942-15985/com.example.mcleroy.studentboxadminpanel E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
Process: com.example.mcleroy.studentboxadminpanel, PID: 15942
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.doInBackground(MainActivity.java:119)
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.doInBackground(MainActivity.java:96)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
12-12 16:22:48.286 15942-15942/com.example.mcleroy.studentboxadminpanel E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.mcleroy.studentboxadminpanel.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4261d878 V.E..... R......D 0,0-684,192} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:376)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.onPreExecute(MainActivity.java:104)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.mcleroy.studentboxadminpanel.MainActivity.createMessage(MainActivity.java:94)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3846)
at android.view.View.performClick(View.java:4466)
at android.view.View$PerformClick.run(View.java:18537)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Please please can anyone look into my code and tell me what I am not doing write, as I really need to be able to upload and download images from my app to remote database nd from remote database to app respectively. or is it impossible to accomplish this?
Here is my PHP script
<?php
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$response = array();
$topic = $_GET['name'];
$message = $_GET['price'];
$details = $_GET['description'];
$image=$_GET['image'];
$con = mysql_connect($servername,$username,$password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("INSERT INTO messages(topic, messages, others,image) VALUES('$name', '$price',`` '$description','$image')");
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Message successfully created.";
// echoing JSON response
echo json_encode($response);
}
?>
Thanks alot in advance as you try to help;
I want to make a login registration system with my app but is not working properly. Here the code where I think I've got an error.
PHP LOGIN SCRIPT :
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
$response["message"] = "Enter username and password!";
die(json_encode($response));
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
<?php
?>
LoginActivity :
public class LoginActivity extends ActionBarActivity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static final String TAG_MESSAGE = "message";
// Testing on emulator
private static String LOGIN_URL = "http://10.0.2.2/webservice/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new LoginProcess().execute();
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
private class LoginProcess extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// Check for success tag
int success;
String username = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(KEY_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginActivity.this,
MainActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSONParser Class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
Log.d("JSON Parser", json);
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
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;
}
}
When I want to login with the right username and password it's working but if I put right username and wrong password I've got an error. But if I delete query_params at :
$result = $stmt->execute($query_params);
I don't have any errors but I can't login anymore
The logcat :
08-31 10:40:39.885: E/Trace(1239): error opening trace file: No such file or directory (2)
08-31 10:40:40.785: D/dalvikvm(1239): GC_FOR_ALLOC freed 118K, 2% free 10936K/11143K, paused 55ms, total 57ms
08-31 10:40:40.845: I/dalvikvm-heap(1239): Grow heap (frag case) to 13.346MB for 2764816-byte allocation
08-31 10:40:40.954: D/dalvikvm(1239): GC_CONCURRENT freed 1K, 2% free 13635K/13895K, paused 24ms+6ms, total 108ms
08-31 10:40:41.334: D/libEGL(1239): loaded /system/lib/egl/libEGL_emulation.so
08-31 10:40:41.345: D/(1239): HostConnection::get() New Host Connection established 0x2a126450, tid 1239
08-31 10:40:41.357: D/libEGL(1239): loaded /system/lib/egl/libGLESv1_CM_emulation.so
08-31 10:40:41.376: D/libEGL(1239): loaded /system/lib/egl/libGLESv2_emulation.so
08-31 10:40:41.455: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:41.465: D/OpenGLRenderer(1239): Enabling debug mode 0
08-31 10:40:45.545: D/request!(1239): starting
08-31 10:40:45.645: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:48.205: E/JSON Parser(1239): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
08-31 10:40:48.355: W/dalvikvm(1239): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
08-31 10:40:48.754: E/AndroidRuntime(1239): FATAL EXCEPTION: AsyncTask #1
08-31 10:40:48.754: E/AndroidRuntime(1239): java.lang.RuntimeException: An error occured while executing doInBackground()
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.lang.Thread.run(Thread.java:856)
08-31 10:40:48.754: E/AndroidRuntime(1239): Caused by: java.lang.NullPointerException
08-31 10:40:48.754: E/AndroidRuntime(1239): at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:118)
08-31 10:40:48.754: E/AndroidRuntime(1239): at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:1)
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-31 10:40:48.754: E/AndroidRuntime(1239): ... 5 more
08-31 10:40:51.844: E/WindowManager(1239): Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239): android.view.WindowLeaked: Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.Window$LocalWindowManager.addView(Window.java:547)
08-31 10:40:51.844: E/WindowManager(1239): at android.app.Dialog.show(Dialog.java:277)
08-31 10:40:51.844: E/WindowManager(1239): at com.example.diycenter.LoginActivity$LoginProcess.onPreExecute(LoginActivity.java:96)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.AsyncTask.execute(AsyncTask.java:534)
08-31 10:40:51.844: E/WindowManager(1239): at com.example.diycenter.LoginActivity$1.onClick(LoginActivity.java:69)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.View.performClick(View.java:4084)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.View$PerformClick.run(View.java:16966)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Handler.handleCallback(Handler.java:615)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Looper.loop(Looper.java:137)
08-31 10:40:51.844: E/WindowManager(1239): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-31 10:40:51.844: E/WindowManager(1239): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 10:40:51.844: E/WindowManager(1239): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 10:40:51.844: E/WindowManager(1239): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-31 10:40:51.844: E/WindowManager(1239): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 10:40:51.844: E/WindowManager(1239): at dalvik.system.NativeStart.main(Native Method)
The OP wrote in an edit:
UPDATE : I found the solution I add :
Log.e("jsonlol", json);
in the JSONParser class before i create the JSONObject and then i check in the logcat what was the the message and it was like that :
08-31 12:31:16.854: E/jsonlol(786): <br />
08-31 12:31:16.854: E/jsonlol(786): <b>Notice</b>: Undefined variable: login_ok in <b>C:\xampp\htdocs\webservice\login.php</b> on line <b>54</b><br />
08-31 12:31:16.854: E/jsonlol(786): {"success":0,"message":"Invalid Credentials!"}
08-31 12:31:17.012: E/JSON Parser(786): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
So I went to the php file login.php on line 54 and there was a variable name problem I just change
$validated_info = false;
by
$login_ok = false;
If you follow the mybringback tutorial it's an error on the script.
I am very new in using JSON in Android. I have got the webAPI that the base URL is
Test server. While developing, I am trying to login using email and password from web server database.
A user token is calculated by following formula:
Token = MD5(email + userId); I do not know what is this. What I tried to do is ;
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
System.out.println("url:: "+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 {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
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;
}
// 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 the request method
if(method == "POST"){
//request method to post
//default HTTPClient
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 to 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;
}
}
Login.java
public class Login extends Activity {
EditText inputEmail;
EditText inputPassword;
Button loginBtn;
// Progress Dialog
ProgressDialog pDialog;
// JSONParser class
JSONParser jsonParser = new JSONParser();
// PHP Login Script location
private static final String LOGIN_URL = "http://www.sthng.com/ws/?c=profile&func=login";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "Success";
private static final String TAG_MESSAGE = "Message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
loginBtn = (Button) findViewById(R.id.btnLogin);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
});
}
// AsyncTask is a seperate thread than the thread that runs the GUI
// Any type of networking should be done with asynctask.
class AttemptLogin extends AsyncTask<String, Void, String> {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//params.add(new BasicNameValuePair("RegistrationID", ));
// Log.d("HERE", email);
// Log.d("HERE2", password);
Log.d("request!", "starting");
// getting users details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
Log.d("DEBUG!", "CHECKPOINT");
// json = json.toString();
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
/* Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);*/
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But I am getting error like;
04-29 19:03:22.691: D/request!(15060): starting
04-29 19:03:22.736: D/dalvikvm(15060): GC_CONCURRENT freed 222K, 14% free 9575K/11015K, paused 13ms+22ms, total 82ms
04-29 19:03:22.781: W/dalvikvm(15060): threadid=11: thread exiting with uncaught exception (group=0x41d082a0)
04-29 19:03:22.791: E/AndroidRuntime(15060): FATAL EXCEPTION: AsyncTask #1
04-29 19:03:22.791: E/AndroidRuntime(15060): java.lang.RuntimeException: An error occured while executing doInBackground()
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.lang.Thread.run(Thread.java:856)
04-29 19:03:22.791: E/AndroidRuntime(15060): Caused by: java.lang.IllegalArgumentException: Host name may not be null
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:519)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.JSONParser.makeHttpRequest(JSONParser.java:125)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:106)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:1)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-29 19:03:22.791: E/AndroidRuntime(15060): ... 5 more
04-29 19:03:32.686: I/Choreographer(15060): Skipped 589 frames! The application may be doing too much work on its main thread.
04-29 19:03:33.256: E/WindowManager(15060): Activity com.example.sthng.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): android.view.WindowLeaked: Activity com.example.clipme.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:403)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.Window$LocalWindowManager.addView(Window.java:554)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.Dialog.show(Dialog.java:277)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$AttemptLogin.onPreExecute(Login.java:87)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.execute(AsyncTask.java:534)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$1.onClick(Login.java:61)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View.performClick(View.java:4232)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View$PerformClick.run(View.java:17298)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.handleCallback(Handler.java:615)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.dispatchMessage(Handler.java:92)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Looper.loop(Looper.java:137)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.ActivityThread.main(ActivityThread.java:4921)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invokeNative(Native Method)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invoke(Method.java:511)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
04-29 19:03:33.256: E/WindowManager(15060): at dalvik.system.NativeStart.main(Native Method)
I am sure I have done some stupid mistake but please do not take it bad way. I hope I get some hints and solutions for this.
You are accessing UI element doInBackground()
Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);
above method on doInBackground(). You have to call this method onPostExecute.
you are sending email and password two time.
You make url with https:sthng.com/ws?function=login&email=" + email+ "&password=" + password
JSONObject json = jsonParser.makeHttpRequest(
"https:sthng.com/ws?function=login&email=" + email
+ "&password=" + password, "POST", params);
or
Now you make below param.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("androidToken", androidToken));// your token
and passing again
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));// passing again
I am parsing this JSON data from Rotten Tomatoes website. I am just trying to get the genres array and put it in a toast. But no toast is coming. Here is my code:
public class MovieInfo extends Activity
{
private static final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxx";
String[] Genres;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.movieinfo);
String MovieID = getIntent().getExtras().getString("MovieID");
new RequestTask().execute("http://api.rottentomatoes.com/api/public/v1.0/movies/"+MovieID+".json?apikey=" + API_KEY);
}
private class RequestTask extends AsyncTask<String, String, String>
{
// make a request to the specified url
#Override
protected String doInBackground(String... uri)
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try
{
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK)
{
// request successful - read the response and close the connection
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
}
else
{
// request failed - close the connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
catch (Exception e)
{
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response)
{
super.onPostExecute(response);
if (response != null)
{
try
{
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray genres = jsonResponse.getJSONArray("genres");
Genres = new String[genres.length()];
for (int i = 0; i < genres.length(); i++)
{
JSONObject movie = genres.getJSONObject(i);
Genres[i] = movie.getString("genres");
}
// add each movie's title to an array
for(int i = 0; i < genres.length(); i++)
{
Toast.makeText(getBaseContext(), ""+Genres[i], Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
Log.d("Test", "Failed to parse the JSON response!");
}
}
}
}
}
LogCat Output:
04-12 20:57:46.088: E/AndroidRuntime(593): FATAL EXCEPTION: main
04-12 20:57:46.088: E/AndroidRuntime(593): java.lang.RuntimeException: org.json.JSONException: Value Drama at 0 of type java.lang.String cannot be converted to JSONObject
04-12 20:57:46.088: E/AndroidRuntime(593): at akshat.jaiswal.rottenreviews.MovieInfo$RequestTask.onPostExecute(MovieInfo.java:106)
04-12 20:57:46.088: E/AndroidRuntime(593): at akshat.jaiswal.rottenreviews.MovieInfo$RequestTask.onPostExecute(MovieInfo.java:1)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.AsyncTask.finish(AsyncTask.java:602)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.AsyncTask.access$600(AsyncTask.java:156)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.Looper.loop(Looper.java:154)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.app.ActivityThread.main(ActivityThread.java:4624)
04-12 20:57:46.088: E/AndroidRuntime(593): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:57:46.088: E/AndroidRuntime(593): at java.lang.reflect.Method.invoke(Method.java:511)
04-12 20:57:46.088: E/AndroidRuntime(593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
04-12 20:57:46.088: E/AndroidRuntime(593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
04-12 20:57:46.088: E/AndroidRuntime(593): at dalvik.system.NativeStart.main(Native Method)
04-12 20:57:46.088: E/AndroidRuntime(593): Caused by: org.json.JSONException: Value Drama at 0 of type java.lang.String cannot be converted to JSONObject
04-12 20:57:46.088: E/AndroidRuntime(593): at org.json.JSON.typeMismatch(JSON.java:100)
04-12 20:57:46.088: E/AndroidRuntime(593): at org.json.JSONArray.getJSONObject(JSONArray.java:484)
04-12 20:57:46.088: E/AndroidRuntime(593): at akshat.jaiswal.rottenreviews.MovieInfo$RequestTask.onPostExecute(MovieInfo.java:91)
04-12 20:57:46.088: E/AndroidRuntime(593): ... 12 more
I am not able to parse objects like Title or release, is there something I am missing here?
Try something like:
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
//Array
JSONArray genres = jsonResponse.getJSONArray("genres");
// which gives you this:
// "genres": [
// "Animation",
// "Kids & Family",
// "Science Fiction & Fantasy",
// "Comedy"
// ]
//Now you can ask length
int howManyGenres = genres.length();
String[] genresStr = new String[howManyGenres];
//You can iterate here
for(int i=0; i<howManyGenres; i++) {
genresStr[i] = genres.get(i);
}