|
I have simple android project that inserts and retrieves some data from MySQL DB using PHP Scripts and JSONParser.
The Project is done using AsyncTask, when I press Insert button, the Progress Dialog Starts then after sometime it displays the message "Unfortunately 'App_Name' has stopped." in Eclipse Emulator.
I have done the following and many others....
*AndroidManifest.xml is set with all required(Permissions)
*I'm using URL_Insert="http://10.0.2.2/foldername/insert.php";
Do I need to configure WAMP Server.....?
Please tell me all possible causes of on button click crash from your experience.
HERE IS MY LOG CAT ERROR
02-26 10:23:58.570: E/Buffer Error(1065): Error converting result java.lang.NullPointerException: lock == null
02-26 10:23:58.670: E/JSON Parser(1065): Error parsing data org.json.JSONException: End of input at character 0 of
02-26 10:23:59.000: E/AndroidRuntime(1065): FATAL EXCEPTION: AsyncTask #5
02-26 10:23:59.000: E/AndroidRuntime(1065): java.lang.RuntimeException: An error occured while executing doInBackground()
Here is May JSONParser.java
package com.example.estate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET 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;
}
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;
}
}
Thank You!
-- modified 27-Feb-14 4:34am.
|
|
|
|
|
Hello all,
I am very new to android development.I have installed AVD and JAVA SDK and able to run my test application on Simulator also.
(As mentioned in the below link)
https://sites.google.com/site/barbarahohensee/android-development-on-ubuntu
But the issue is:It takes a long time to run on simulator. I am on my way to develop very few basic pages with buttons and textBox and in last payment option. I dont want to run simulator every time I want to check GUI.
Please suggest.
Ankita
|
|
|
|
|
Go for Genymotion Emulator For First Time It will take time to download After That It is Fast,
2)Go for original devices
|
|
|
|
|
It's true that the emulator load very slowly at the first time, but that's it. You can reuse it from then on...
I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V)
|
|
|
|
|
Using a physical device to test your android app is another alternative.
|
|
|
|
|
|
AsyncTask takes too long to do tasks while rotating Progress Dialog, finally the application crashes displaying the message "Unfortunately "App_Name" has stopped."
What should I do in onPreExecute, doInbackground, onPostExecute so as to solve this problem?
What are the most likely causes this?
PLEASE TELL ME IF THIS IS THE STANDARD CODE FOR AsynkTask!!!
THANK YOU IN ADVANCE FOR YOUR TIME!!!
The AsynkTask Code I used is below:
package com.Project.mbjs;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class RegisterJobSeeker extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputFirstName;
EditText inputLastName;
EditText inputEmail;
EditText inputPassword;
EditText inputExperience;
EditText inputEduLevel;
EditText inputPhoneNo;
// URL to register Job Seeker
private static String URL_RegisterJobSeeker = "http://10.0.2.2 /mbjs/RegisterJobSeeker.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
<a href="/Members/override">@Override</a>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registerjobseeker);
// Edit Text
inputFirstName = (EditText) findViewById(R.id.txtFName);
inputLastName = (EditText) findViewById(R.id.txtLName);
inputEmail = (EditText) findViewById(R.id.txtEmail);
inputPassword = (EditText) findViewById(R.id.txtPassword);
inputExperience = (EditText) findViewById(R.id.txtExperience);
inputEduLevel = (EditText) findViewById(R.id.txtEduLevel);
inputPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
// Create button
Button btnRegister = (Button) findViewById(R.id.btnRegister);
// button click event
btnRegister.setOnClickListener(new View.OnClickListener() {
<a href="/Members/override">@Override</a>
public void onClick(View view) {
// creating new product in background thread
new AddJobSeeker().execute();
}
});
}
/** * Background Async Task to Create new product * */
class AddJobSeeker extends AsyncTask<String, String, String> {
/** * Before starting background thread Show Progress Dialog * */
<a href="/Members/override">@Override</a>
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterJobSeeker.this);
pDialog.setMessage("Registering Job Seeker...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
<a href="/Members/override">@Override</a>
protected String doInBackground(String... args) {
String firstName = inputFirstName.getText().toString();
String lastName = inputLastName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String experience = inputExperience.getText().toString();
String eduLevel = inputEduLevel.getText().toString();
String phoneNo = inputPhoneNo.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstName", firstName));
params.add(new BasicNameValuePair("lastName", lastName));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("experience", experience));
params.add(new BasicNameValuePair("eduLevel", eduLevel));
params.add(new BasicNameValuePair("phoneNo", phoneNo));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(URL_RegisterJobSeeker,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Toast.makeText(RegisterJobSeeker.this,
"Job Seeker Successfully Registered.",
Toast.LENGTH_LONG).show();;
// Intent i = new
// Intent(getApplicationContext(),RegisterJobSeeker.class);
// startActivity(i);
// closing this screen
// finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/** * After completing background task Dismiss the progress dialog * **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
-- modified 25-Feb-14 2:57am.
|
|
|
|
|
I added super.onPostExecute(file_url) in the onPostExecute and has inserted the data in to DB but still AsynkTask taking too long and finally the app in emulator crashes!
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url)
// dismiss the dialog once done
pDialog.dismiss();
}
How can I avoid waiting too long doing BG Tasks and crashing???
What to include in my AndroidManifest.xml???
THANK YOU IN ADVANCE!
|
|
|
|
|
First you are not supposed to access UI components directly from a background thread.
String doInBackground(String... args) {
String firstName = args[0];
String lastName = args[1];
String email = args[2];
String password = args[3];
String experience = args[4];
String eduLevel = args[5];
String phoneNo = args[6];
JSONParser jsonParser = new JSONParser();
.....
JSONObject json = jsonParser.makeHttpRequest(URL_RegisterJobSeeker,
"POST", params);
return String.valueOf(json.getInt(TAG_SUCCESS));
}
protected void onPostExecute(String success) {
pDialog.dismiss();
if (success == "1") {
Toast.makeText(RegisterJobSeeker.this,
"Job Seeker Successfully Registered.",
Toast.LENGTH_LONG).show();;
} else {
}
}
You might want to host your AsyncTask in a headless fragment so that device configuration changes don't crash your app.
Hope this helps.
“Everything is simple when you take your time to analyze it.”
|
|
|
|
|
HI,
I am developing android app in visual studio using xamarin plugin.
I have a requirement that my offline data in device need to sync with server on scheduled intervals let say 6AM every day.
I have some documentation for Native android on android developers centre but I am looking help with xamarin development environment.
Appreciate help on this.
Thanks & regards
suresh
|
|
|
|
|
|
You should have called your telco, make a police report, asap, instead of posting at this wrong place.
|
|
|
|
|
Switch the phone off.
Veni, vidi, abiit domum
|
|
|
|
|
|
Nice suggestion.
But (s)he is a possible spammer, isn't (s)he? Did you notice the link in OP's message? Did you check my spam message in protocolshape?
thatrajaCode converters | Education Needed
No thanks, I am all stocked up. - Luc Pattyn
When you're wrestling a gorilla, you don't stop when you're tired, you stop when the gorilla is - Henry Minute
|
|
|
|
|
thatraja wrote: But (s)he is a possible spammer, isn't (s)he? Possible, but not definite.
Veni, vidi, abiit domum
|
|
|
|
|
Richard MacCutchan wrote: Possible, but not definite.
- Joined within the last two days;
- Single message which has nothing to do with programming, and contains a spammy link;
- Username of "Architecht123", related to the spammy link;
Smells like spam to me.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
And given the 'quality' of their written communication, I tend to agree.
|
|
|
|
|
I'm thinking about Android applications...
I'm interested in your opinion about development environment (on Windows). I found Eclipse, IntelliJ and Android Studio. Which is better? There are others?
I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V)
|
|
|
|
|
|
There is also NetBeans.
In my opinion and experience, Eclipse remains the best
Light or darkness, we must choose ...
|
|
|
|
|
For now, Eclipse
Soon or later, Android Studio
thatrajaCode converters | Education Needed
No thanks, I am all stocked up. - Luc Pattyn
When you're wrestling a gorilla, you don't stop when you're tired, you stop when the gorilla is - Henry Minute
|
|
|
|
|
Eclipse is best so far as various plug-ins are supported to make our development effort convenient.
|
|
|
|
|
Eclipse, IntelliJ is good
|
|
|
|
|
So, I'm developing my first ever Android app and my first experience of Eclipse and Java (after many years of Visual Studio and C#)!
I have all my data storage and retrieval coded and working, as well as all my classes that represent that data.
Now it's time to design the UI - I have an idea of how I want it to look and interact so all good to go but...
What is the best or recommended way of hooking up the UI in Java to the objects behind. From the research I've done it doesn't appear that DataBinding (ala WPF) is supported which would be the obvious way. It's just straight forward class instances and collections of those classes.
Thanks in advance
|
|
|
|