How to read html content from server - java

I want to show content in webview from the server.The data is coming from server in html form.How I can so it on webview.The data variable contained all the results but i am not able to read the html contents.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard__description__page);
WebView webView = (WebView) findViewById(R.id.webview);
// String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webView.loadData(summary, "text/html", null);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
alternate_id= null;
bookmarkid= null;
bookmarkfile = null;
} else {
alternate_id= extras.getString("alternateid");
bookmarkid= extras.getString("bookmarkid");
bookmarkfile = extras.getString("bookmarkfile");
}
} else {
alternate_id= (String) savedInstanceState.getSerializable("alternateid");
bookmarkid= (String) savedInstanceState.getSerializable("bookmarkid");
bookmarkfile= (String) savedInstanceState.getSerializable("bookmarkfile");
}
// System.out.println(stringCameFromFirstAcvitity);
// actorsList = new ArrayList<Actors>();
new JSONReaderAsyncTask().execute("https://www.webmod.com/mydata/get_article_detail?", " access_token", "bookmark_file", "alternate_id", "bookmarkId");
reader_back=(ImageButton)findViewById(R.id.reader_back_btn);
reader_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent dash_back = new Intent(getApplicationContext(),Dashboard.class);
startActivity(dash_back);
}
});
}
class JSONReaderAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Dashboard_Description__page.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("access_token", "94529e5dbc6234fc3bbfce7406b8dde9"));
nameValuePairs.add(new BasicNameValuePair("bookmark_file", bookmarkfile));
nameValuePairs.add(new BasicNameValuePair("alternate_id", alternate_id));
nameValuePairs.add(new BasicNameValuePair("bookmarkId", bookmarkid));
// System.out.println(alternate_id);
//System.out.println(bookmarkfile);
// System.out.println(bookmarkid);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
// System.out.println("hello Hitu");
// jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
// System.out.println(jsonResult);
// StatusLine stat = response.getStatusLine();
int status = 200;
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
// ArrayList<String> mylist = new ArrayList<String>();
// mylist.add(data);
// System.out.println(first);
System.out.println(data);
System.out.println("fffff");
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("content");
}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
// adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}

Okey. as you stated you want those data to be desplayed in WebView this is what you can do.
wv = (WebView) findViewById(R.id.webView)
wv.loadDataWithBaseURL("", YOUR_TEXT, "text/html", "utf-8", "");
I hope this will help.

Related

How to handle Login Successful in json? [duplicate]

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();
}
}

how to make response method and call it in main class

I want to access html from the server using API for that i want to make a method in the response, that method i want to use it in main class.I am using webview to show the output result in webview.Following code I am using.
public class Dashboard_Description__page extends AppCompatActivity {
ImageButton reader_back;
ArrayList<Reader_Model> actorsList;
String addCat;
ActorAdapter adapter;
WebView webView;
String alternate_id;
String bookmarkid;
String bookmarkfile;
private String webData;
String mimeType = "text/html";
String encoding = "utf-8";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard__description__page);
WebView webView = (WebView) findViewById(R.id.webview);
// String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webView.loadData(getWebData(), "text/html", null);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
alternate_id= null;
bookmarkid= null;
bookmarkfile = null;
} else {
alternate_id= extras.getString("alternateid");
bookmarkid= extras.getString("bookmarkid");
bookmarkfile = extras.getString("bookmarkfile");
}
} else {
alternate_id= (String) savedInstanceState.getSerializable("alternateid");
bookmarkid= (String) savedInstanceState.getSerializable("bookmarkid");
bookmarkfile= (String) savedInstanceState.getSerializable("bookmarkfile");
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// System.out.println(stringCameFromFirstAcvitity);
// actorsList = new ArrayList<Actors>();
new JSONReaderAsyncTask().execute("https://www.webo.com/secure-mobile/get_article_detail?", " access_token","bookmark_file","alternate_id","bookmarkId");
reader_back=(ImageButton)
findViewById(R.id.reader_back_btn);
reader_back.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v) {
Intent dash_back = new Intent(getApplicationContext(),Dashboard.class);
startActivity(dash_back);
}
});
}
public String getWebData() {
return webData;
}
public void setWebData(String data) {
this.webData = data;
}
class JSONReaderAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Dashboard_Description__page.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("access_token", "94529e5dbc6234fc3bbfce7406b8dde9"));
nameValuePairs.add(new BasicNameValuePair("bookmark_file", bookmarkfile));
nameValuePairs.add(new BasicNameValuePair("alternate_id", alternate_id));
nameValuePairs.add(new BasicNameValuePair("bookmarkId", bookmarkid));
// System.out.println(alternate_id);
//System.out.println(bookmarkfile);
// System.out.println(bookmarkid);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
// System.out.println("hello Hitu");
// jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
// System.out.println(jsonResult);
// StatusLine stat = response.getStatusLine();
int status = 200;
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
// ArrayList<String> mylist = new ArrayList<String>();
// mylist.add(data);
// System.out.println(first);
System.out.println(data);
System.out.println("fffff");
//here result is coming from the server. I want here a method which can be used in main class.I want to view this result in html form using webview.
// JSONObject jsono = new JSONObject(data);
// JSONArray jarray = jsono.getJSONArray("content");
}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
// adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class HttpClientWrapper {
public static String post(String requestUrl,String postValues) {
URL url;
String response = "";
try {
url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);// Specifies whether this URLConnection allows receiving data.
conn.setDoOutput(true);// Specifies whether this URLConnection allows sending data.
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/json; charset=utf-8");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postValues);
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line="";
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
while ((line=br.readLine()) != null) {
sb.append(line+"\n");
response = sb.toString().substring(0, sb.toString().length() - 1);
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
public static String getResponseGET(String url) {
String response = "";
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setConnectTimeout(15000);
c.setReadTimeout(15000);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
response = sb.toString().substring(0, sb.toString().length() - 1);
}
br.close();
return response;
}
} catch (IOException ex) {
if (c != null) {
c.disconnect();
}
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
}
}
}
return null;
}
}
private class RegistrationAsyncTask extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
Context mContext;
String error;
String response;
String mData;
public RegistrationAsyncTask(Context context,String data) {
this.mContext = context;
this.error = "";
this.mData = data;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setTitle("Registration");
dialog.setMessage("Registration in process...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
response = HttpClientWrapper.post(URL.URL_REGISTRATION, mData);
Log.e(TAG, "Response: " + response);
} catch (Exception e) {
e.printStackTrace();
this.error = e.getMessage();
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "result: " + response);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (response.isEmpty()){
Utils.message(getActivity(), getResources().getString(R.string.error_server));
return;
}
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.has("error")) {
String error = jsonObject.getString("error");
JSONObject jsonObject1 = new JSONObject(error);
String message = jsonObject1.getString("message");
Utils.showDialog(mContext, alert, alertDialog, getResources().getString(R.string.text_title_reg),message);
return;
} else {
String error = jsonObject.getString("success");
JSONObject jsonObject1 = new JSONObject(error);
String message = jsonObject1.getString("message");
alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.text_title_reg);
alert.setMessage(message);
alert.setCancelable(false);
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
clearForm();
dialog.dismiss();
}
});
alertDialog = alert.create();
alertDialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

java.lang.StringIndexOutOfBoundsException:

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

Unable to fetch JSON data from Server

Unable to fetch data from server even i have value in textview as per my condition in onCreate() and when i remove this condition this works just fine for me (my mean, in that case i am able to fetch JSON data from Server).
and i tried many things but still no success for me, always getting "Unable to fetch data from server" because i used this as Toast in onPostExecute() method of AsyncTask
I am getting value for TextView and that's for sure its calling execute method of AsyncTask as well, but always getting Unable to fetch data from server
Do you have Questions in your mind :
1) Why I am using such condition in onCreate(), then check my this question
2) Why I am setting adapter in onPostExecute(), then check my this question
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_category);
etTextToSave = (TextView) findViewById(R.id.textView2);
sharedprefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
etTextToSave.setText(sharedprefs.getString("SharedPrefsData",""));
actorsList = new ArrayList<VideoCategory>();
if(etTextToSave.getText().toString().length()>0)
{
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}
centerLockHorizontalScrollview = (HSVActivity) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new VideoCategoryAdapter(getApplicationContext(), R.layout.adapter_video_category, actorsList);
centerLockHorizontalScrollview.setAdapter(HomeActivity.this, adapter);
}
}
}
I am not getting any exception or toast message.
Check the Json response.
As per your posted question , you get data form the server still you get Toast that "Unable to fetch data from server" . I done the small change in your code please try it and let me known .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_category);
etTextToSave = (TextView) findViewById(R.id.textView2);
sharedprefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
etTextToSave.setText(sharedprefs.getString("SharedPrefsData",""));
actorsList = new ArrayList<VideoCategory>();
if(etTextToSave.getText().toString().length()>0)
{
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}
centerLockHorizontalScrollview = (HSVActivity) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
JSONObject jObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
jObj = new JSONObject(data);
if(!(jObj.equals(null)))
{
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(jObj== null)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new VideoCategoryAdapter(getApplicationContext(), R.layout.adapter_video_category, actorsList);
centerLockHorizontalScrollview.setAdapter(HomeActivity.this, adapter);
}
}
}

json-parsing errors at run time

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.

Categories

Resources