Im trying to store an intent from an android app to a database and I'm having some issues converting it into a string and storing it in the database.Its connecting to the database and the id is incrementing.
Ive stored the intents inside the string.xml file like this:
<string name="key_username">username</string>
<string name="key_pet_name">pet_name</string>
I took the intent from another actvity like this:
Intent i = newIntent(Hamster.this,Death.class); i.putExtra(getString(R.string.key_username),Username); i.putExtra(getString(R.string.key_pet_name), Petname);
i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
overridePendingTransition(0, 0);
startActivity(i);
And this is the code I'm using to connect to the database:
public class Death extends Activity {
public static String Petsname,Username ;
private ImageView dead;
private Button submit;
private TextView hamsters_death;
public static final String TAG = "Death";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.death);
final Intent intent = getIntent();
submit = (Button) findViewById(R.id.button);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Username = intent.getStringExtra(getString(R.string.key_username));
String Petname = intent.getStringExtra(getString(R.string.key_pet_name));
Log.d(TAG, Username);
Log.d(TAG,Petname);
new SummaryAsyncTask().execute(new FormData());
}
});
}
}
class SummaryAsyncTask extends AsyncTask<FormData, Void, JSONArray> {
Intent intent;
public String Username;
public String Petname;
public void postData(String Username, String Petname)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8888/Hamster_website/hamster.php");
try{
ArrayList<NameValuePair> form_items = new ArrayList<NameValuePair>(2);
form_items.add(new BasicNameValuePair("Username", Username));
form_items.add(new BasicNameValuePair("Petname", Petname));
httppost.setEntity(new UrlEncodedFormEntity(form_items));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: " + e.toString());
}
}
protected JSONArray doInBackground(FormData... params) {
postData(Username, Petname);
return null;
}
}
class FormData {
public JSONArray PostForm() {
{
String url = "http://10.0.2.2:8888/Hamster_website/hamster.php";
HttpEntity httpEntity = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//JSONArray =
for (int i = 0; i < jsonArray.length(); i++) {
Log.d("JSON DEBUG", jsonArray.get(i).toString());
}
} catch (JSONException jse) {
jse.printStackTrace();
}
return jsonArray;
}
}
}
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'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
I wrote a program
I want download a json file from a URL and show it in a text view ..
When you click the button the program will stop after a few seconds .
I do not know what the problem is .
Please help me..
java code:
public class MainActivity extends Activity {
TextView tx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button2);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetJsonTask().execute("http://shahid.ifilmtv.ir/query/englishcurrentshows");
}
});
}
public class GetJsonTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
return getJson(urls[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONArray jsonArray;
try {
jsonArray = new JSONArray(result);
JSONObject object = jsonArray.getJSONObject(1);
tx.setText(object.getString("id"));
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getJson(String url) {
try {
InputStream inputStream = null;
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String result = sb.toString();
return result;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}
}
I think the issue is in getJSON method. I have rewritten a following code. Please try this.
public String getJson(String url) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
Object resp = defaultHttpClient.execute(httpPost, responseHandler);
String json = resp.toString();
// create a object here if you want
JSONObject obj = new JSONObject(json);
return json;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}
im making an app for a website. It has an JSON API. The URL im trying to fetch the result from is: http://api.bayfiles.net/v1/account/login/<user>/<password>
I get the error: java.lang.string cannot be converted to jsonarray when logging the error using logcat.
My main activity is:
public class MainActivity extends SherlockActivity {
EditText un,pw;
TextView error;
Button ok;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText)findViewById(R.id.user);
pw = (EditText)findViewById(R.id.psw);
ok = (Button)findViewById(R.id.button1);
error = (TextView)findViewById(R.id.textView1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//error.setText("Clicked");
//Intent startNewActivityOpen = new Intent(LoginActivity.this, FilesActivity.class);
//startActivityForResult(startNewActivityOpen, 0);
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
//mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
// getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/login/spxc/mess2005");
}
});
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("error");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
//map.put("video_id", String.valueOf(i));
map.put("session", "" + e.getString("session"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data: " + e.toString());
}
error.setText("session");
/*
//Intent myIntent = new Intent(ListMoviesController.this,
// TestVideoController.class);
myIntent.putExtra("video_title", o.get("video_title"));
myIntent.putExtra("video_channel", o.get("video_channel"));
myIntent.putExtra("video_location", o.get("video_location"));
startActivity(myIntent); */
}{
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
And this is my adapter: JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "stianxxs"));
nameValuePairs.add(new BasicNameValuePair("secret", "mhfgpammv9f94ddayh8GSweji"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}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{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Why im i getting this error? When using the right username and password in the url you would get: {"error":"","session":"RANDOM NUMBER"}
And as you can see i try to fetch this number. Any help is much appreciated!
You are getting this error because in line
JSONArray shows = object.getJSONArray("error");
you are trying to get value for key error and treat is as an array, whereas it's not - it's an empty string. Therefore you need to get it as a string:
String error = object.getString("error");
Similarly, if you need to get your "session", you can get it with
String session = object.getString("session");
P.S. Note that this is assuming that your JSONObject object actually contains the object represented by the string in your question.
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.