I'm new in android and I want to send editText value using JSON to server . I get this error "StringIndexOutOfBoundsException" and I don't know how can fix it. Here is My code :
JSONParser.java
package com.example.bookstore;
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.equals("POST")){
HttpClient httpclient = getNewHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpclient.execute(httpPost);
if(httpResponse != null){
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}else if(method.equals("GET")){
// request method is GET
HttpClient httpclient = getNewHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpclient.execute(httpGet);
if(httpResponse != null){
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;
if(reader != 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.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
Sale.java
package com.example.bookstore;
public class Sale extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText BookName;
EditText AuthorName;
EditText Publication;
EditText Price;
EditText BookGenre;
// url to create new product
private static String url_create_product = "https://5.144.130.36/android/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.sale);
BookName = (EditText) findViewById(R.id.BookName);
AuthorName = (EditText) findViewById(R.id.AuthorName);
Publication = (EditText) findViewById(R.id.Publication);
Price = (EditText) findViewById(R.id.Price);
BookGenre = (EditText) findViewById(R.id.BookGenre);
Button confirm = (Button) findViewById(R.id.Confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewBook().execute();
}
});
}
class CreateNewBook extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Sale.this);
pDialog.setMessage("Book Submition");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
String B_Name = BookName.getText().toString();
String Au_Name = AuthorName.getText().toString();
String Pub = Publication.getText().toString();
String Pr = Price.getText().toString();
String B_Genre = BookGenre.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("B_Name", B_Name));
params.add(new BasicNameValuePair("Au_Name", Au_Name));
params.add(new BasicNameValuePair("Pub", Pub));
params.add(new BasicNameValuePair("Pr", Pr));
params.add(new BasicNameValuePair("B_Genre", B_Genre));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Logcat
04-29 11:13:59.536: E/AndroidRuntime(784):
java.lang.StringIndexOutOfBoundsException: length=58; regionStart=-1;
regionLength=1
04-29 11:13:59.536: E/AndroidRuntime(784): at
java.lang.String.startEndAndLength(String.java:583)
04-29 11:13:59.536: E/AndroidRuntime(784): at
java.lang.String.substring(String.java:1464)
04-29 11:13:59.536: E/AndroidRuntime(784): at
com.example.bookstore.JSONParser.makeHttpRequest(JSONParser.java:109)
I have MySSLSocketFactory class to certification that I don't think any problem exists in there.
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
Why do you add 1 to the last index? if you receive a String where the last } is really on the last index, you have a OutOfBounds.
I will edit my answer after you will paste your logs, however I think that the issue is with the :
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
or with a similar fragment with string operations.
Change this line to:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{");
stringBuilder.append(StringUtils.substringBeforeLast(StringUtils.substringAfter(json, "{"), "}"));
stringBuilder.append("}");
jObj = new JSONObject(stringBuilder.toString());
This piece is entirely StringOutOfBoundsException and NullPointerException safe.
According to: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
Related
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to implement login and signup form in Android with the help of JSON using post method. When i signup and enter the details it successfully register and data has been shown in my local host sever and when i login its enter wrong username and password its show incorrect details in toast and enter right details shows login success in toast, but i want when i enter right details its goes to another activity. and enter wrong details shows only toast. Here is the code :-
MainActivity.java
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
private static final String TAG = "LoginActivity";
String URL = "http://10.0.2.2/test_android/index.php";
JSONParser jsonParser=new JSONParser();
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, password;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
password = (EditText)findViewById(R.id.passwordd);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin = new AttemptLogin();
attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String email = args[2];
String password = args[1];
String name = args[0];
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", name));
params.add(new BasicNameValuePair("password", password));
if (email.length() > 0)
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("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();
Log.d("API123",json);
} 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);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null)
{
if(result.getString("message").equals("Successfully logged in"))
{
Intent intent = new Intent(ThisActivity.this,NewActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am new to Android, I followed some tutorials online to create a login page with MySQL database hosted locally on my PC.
I am getting an error on JSONParser.java file says:
Error:(60, 61) error: incompatible types: List<Pair<String,String>> cannot be converted to List<? extends NameValuePair>
Here is the code in JSONParser.java
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<Pair<String, String>> 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 for Login.java
public class login extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputUsername, inputPassword;
Button btnlogin;
TextView txtregister;
// url to login
private static String url_login = "http://10.0.2.2/VICOBA/login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Edit Text
inputUsername = (EditText)findViewById(R.id.login_username);
inputPassword = (EditText)findViewById(R.id.login_password);
//Text View
txtregister = (TextView)findViewById(R.id.createAccount);
//Create button
btnlogin = (Button)findViewById(R.id.loginBtn);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Make login in background thread
String username = inputPassword.getText().toString();
String password = inputPassword.getText().toString();
new doLogin().execute(username,password);
}
});
}
/**
* Background Async Task to Create new product
* */
class doLogin extends AsyncTask<String, String, String>{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
//String description = inputDesc.getText().toString();
String username = args[0];
String password = args[1];
// Building parameters
List<Pair<String, String>> params = new ArrayList<>();
params.add(new Pair<>("username", username));
params.add(new Pair<>("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat fro response
Log.d("Login", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), HomeActivity.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();
}
}
}
I have stacked here for some days trying searching for online solution with no success.
When I go back to the previous activity by pressing the back button the progress dialog is appearing and not disappearing. When I minimize they the app the progress dialog disappears.
Here is the code for the async class
public class BackGroundTask extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
private ProgressDialog pd;
String url = null;
String method = null;
Context context;
public BackGroundTask(String url, String method,
List<NameValuePair> params, Context context) {
this.url = url;
postparams = params;
this.method = method;
this.context = context;
//pd = new ProgressDialog(context);
//pd.setTitle("Processing...");
//pd.setMessage("Please wait.");
//pd.setCancelable(false);
//pd.setIndeterminate(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd = ProgressDialog.show(context, "Processing...", "Please wait.", true, false);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
HttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams,
"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());
}
System.out.println(json);
// 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());
}
//pd.dismiss();
// return JSON String
return jObj;
}
}
You aren't dismissing it when you finish the Activity and the task must not be done. Override finish() and dismiss it if needed
#Override
public void finish()
{
if (pd.isShowing()
{
pd.dismiss();
}
super.finish();
}
You could also Override onBackPressed() and put this code there but since pressing the back button calls finish() its probably safer just to do it there.
Also, you are comparing Strings correctly in one place
if (method.equals("POST")) // correct
but not others
else if (method == "GET") // incorrect
i want to send android form data to specific URL (like login.php page "this is a page of my website that will verification of form data from DB saved record")
See this tutorial and you are done
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
You actually need two Classes to do this
1. Your Activity
2. JSON Parser
Here is the sample code for two of them, you can modify it as per your own needs
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static JSONArray jArr = null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 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());
}
Log.i("PHP Error", "["+json+"]");
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.getMessage() + json);
}
// return JSON String
return jObj;
}
public JSONArray getAllMessages(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, "utf-8"), 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());
}
Log.i("PHP Error", "["+json+"]");
// try parse the string to a JSON object
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.getMessage() + json);
}
// return JSON String
return jArr;
}
}
Activity
public class Home extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
String message;
private static String url_addmessage = "http://www.yourdomain.com/addmessage.php";
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final EditText et = (EditText)findViewById(R.id.editText1);
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
message = et.getText().toString();
Log.i("message to be posted", message);
new RegisterMe().execute();
}catch(Exception e){
Log.e("Exception while getting Message", e.getMessage().toString());
}
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Home.this, GetMessage.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
class RegisterMe extends AsyncTask<String, String, String>{
String Message=null;
public boolean workdone(String Message){
boolean x=false;
if(Message == "Done"){
x=true;
}
return x;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(Home.this);
pDialog.setMessage("Transaction In Progress... \n You Have The Right To Remain \n Silent & Patient :)");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("message", message));
JSONObject json = jsonParser.makeHttpRequest(url_addmessage, "GET", params);
Log.d("Create Response", json.toString());
try{
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
Message = "Done";
Log.d("Work Done", "Message Added");
}
else{
Log.d("Work Done", "Message Not Added");
}
} catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
pDialog.dismiss();
if(new RegisterMe().workdone(Message)){
Toast.makeText(Home.this, "Message Added Successfully.",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Home.this, "Sorry There was some error in processing your request, please try after some time.",Toast.LENGTH_LONG).show();
}
}
}
}
I am trying to send some sign up information to a php server from my Android app.
I have two classes: RegisterActivity and JSONParser.
While I'm trying to run this programs there is some errors like this:
Error parsing data org.json.JSONException: Value not of type java.lang.String cannot be converted to JSONObject" and "android.os.AsyncTask$3.done(AsyncTask.java:299)
Here is my code:
RegisterActivity.java
public class RegisterActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText username;
EditText email;
EditText password;
EditText RePass;
private static String url_create_product = "http://oranz.co/pmdtest/index.php";
private static final String TAG_SUCCESS = "sucess";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.register);
Button registerscreen=(Button)findViewById(R.id.btnCntnueRegister);
// Listening to Login Screen link
email = (EditText)findViewById(R.id.reg_email);
password =(EditText)findViewById(R.id.reg_password);
username =(EditText)findViewById(R.id.reg_username);
RePass = (EditText)findViewById(R.id.rereg_password);
EditText passwords=(EditText)findViewById(R.id.reg_password);
passwords.setTransformationMethod(new PasswordTransformationMethod());
EditText repasswords = (EditText) findViewById(R.id.rereg_password);
repasswords.setTransformationMethod(new PasswordTransformationMethod());
registerscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if(email.getText().toString().equals("")&&password.getText().toString().equals("")&&username.getText().toString().equals("")&&RePass.getText().toString().equals(""))
{
Toast toast = Toast.makeText(context, "Please Enter a valed data. !", duration);
toast.show();
}
else if(email.getText().toString().equals("")||password.getText().toString().equals("")||username.getText().toString().equals("")||RePass.getText().toString().equals(""))
{
Toast toast = Toast.makeText(context, "Please check any field is blank. !", duration);
toast.show();
}
else if(password.getText().toString().compareTo(RePass.getText().toString())==0)
{
Intent k = new Intent(getApplicationContext(), ContinueRegister.class);
startActivity(k);
new CreateNewUser().execute();
}
else
{
Toast toast = Toast.makeText(context, "Password matching is failed. !", duration);
toast.show();
}
}
});
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent m = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(m);
}
});
}
class CreateNewUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String Username = username.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password",Password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created user
Intent i = new Intent(getApplicationContext(),FinishSignupActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
}
} 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();
}
}
}
JSONParser.java:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
This is due to the android emulator crash there is no mistakes in the programs.