How to connect Clusterpoint database to an android appliaction - java

I am new to NoSQL database and cloud. I am trying to develop a simple application in android using Clusterpoint (DBAAS). I tried and searched so many possibilities, but it is not quite working.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://username:password#api-eu" +
".clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(requestString);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (IOException e) {
result = "Error";
e.printStackTrace();
} finally {
Log.v("ClusterResponse", result);
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.v("ClusterResponse", s);
}
}).execute();
In my code i replaced username and password with original values.

I got the connection. I am posting my code so the next person can get it right in a much faster way
My mistakes
- Needed GET instead of POST
- Authorization should be of base64 with NOWRAP , so it won't add "CR" line at the end.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://api-eu.clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestString);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpget.addHeader("Authorization", "Basic "+Base64.encodeToString
("username:password".getBytes(),Base64.NO_WRAP));
result = httpClient.execute(httpget, responseHandler);
} catch (IOException e) {
result = e.toString();
e.printStackTrace();
} finally {
Log.v("ClusterResponse", "Done");
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getBaseContext(), s, Toast.LENGTH_LONG).show();
Log.v("ClusterResponse", s);
}
}).execute();

Related

Android Http Request POST JSON

I am trying to create a function to make a request, but it is giving some error, I already put permission to the internet, but still
This is my code:
public String request(String Url,JSONObject Data){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url);
InputStream inputstream;
String content = "";
try {
httppost.setEntity(new StringEntity(Data.toString()));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
while(true){
if(entity != null){
inputstream = entity.getContent();
content = inputstream.toString();
break;
}
}
} catch (Exception ex) {
return ex.toString();
}
return content;
}
Input:
JSONObject data = new JSONObject();
data.put("teste","teste");
String response = request('urlExample',data);
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();
Output:
android.os.NetworkOnMainThreadExecption
I suggest you to use AsyncTask as I mentioned in the comment :
private class LongOperation extends AsyncTask<Void, Void, String> {
private String mUrl;
private JSONObject mData;
public LongOperation(String url, JSONObject data) {
mUrl = url;
mData = data;
}
#Override
protected String doInBackground(Void... params) {
return request(mUrl, mData);
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(getApplicationContext(),response,
Toast.LENGTH_SHORT).show();
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
You can start your AsyncTask as follow:
JSONObject data = new JSONObject();
data.put("teste","teste");
new LongOperation('urlExample', data).execute();
Network operation does not be launched on Main Thread. You can create another Thread for running it.
Thread thread = new Thread(new Runnable(){
#Override public void run(){
// Run request here !!!!
}
});
thread.start();
I recomend you to use **Volley**, it's a side client library which helps you with the Http-Request.
Search for StringRequest.

no any response when use httpclient in AsyncTask

i want to get data from my server with AsyncTask and then extract some and send to another location and get more info from that
for first section I'm using from this code for run my AsyncTask method and Cancel AsyncTask after some time (for no response...)
new MySecendServer(link, param,mInstagramSession).execute();
final ProgressDialog pd2 = new ProgressDialog(testActivity.this);
pd2.show();
final Timer tm = new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
count++;
if (count == 30) {
pd2.cancel();
tm.cancel();
new MySecendServer(.....) .cancel(true); }
}
});
}
}, 1, 1000);
then after get data from my server i try to get more info with this code but i don't get any response or exception i test this code in doInBackground And onPostExecute and no any diffrent and no any response
try {
String requestUrl = "https://api.instagram.com/v1/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(requestUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (Exception ex) {}
now anyone can give me reason or any suggest for do this work ?
thanks
Update :
I found exception here :
HttpResponse httpResponse = httpClient.execute(httpGet);
and message is :
cause NetworkOnMainThreadException (id=831620140512)
Update 2 :
My first AsyncTask
public class MySecendServerClass extends AsyncTask {
private String link="";
private String [][]pparams;
private InstagramUser IG_User;
private InstagramSession IG_Session;
public MySecendServerClass(String link,String [][]params,InstagramSession user){
this.link=link;
this.pparams=params;
this.IG_Session = user;
}
#Override
protected String doInBackground(Object... arg0) {
String data="";
try{
if(pparams!=null){
for(int i=0;i<pparams.length;i++){
if(i!=0){
data+="&";
}
data+=URLEncoder.encode(pparams[i][0],"UTF8")+"="+URLEncoder.encode(pparams[i][1],"UTF8");
}
}
URL mylink=new URL(link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line);
}
Log.d("sssss",sb.toString());
return sb.toString();
}
catch(Exception ex){
}
return null;
}
#Override
protected void onPostExecute(Object tr) {
super.onPostExecute(tr);
String result = (String)tr;
try{
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("followlist");
JSONObject jObject = jArray.getJSONObject(0);
String client_id=jObject.getString("client_id");
GrtUserProfile(client_id);
}
catch(Exception ex){
}
}
}
Solve Problem With this Code :
public void GrtUserProfile(String Cid) {
String requestUrl= "https://api.instagram.com/v1/users/"+Cid+"/"+"&access_token="+mInstagramSession.getAccessToken();
new HTTPRequestClass().execute(requestUrl);
}
class HTTPRequestClass extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
String url = urls[0];
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
return response;
} catch (Exception e) {
return "";
}
}
protected void onPostExecute(String Response) {
Log.i("Response", Response);
}
}
Instead of using Timer to cancel async task you can set timeout for HttpURLConnection
private class DownloadFilesTask extends AsyncTask<URL, Integer, Boolean> {
protected Boolean doInBackground(URL... urls) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Boolean result) {
showDialog("Downloaded " + result );
}
}

Android httpclient login to Rails server

I started to learn about how to make an Android application. I tried to connect my app to rails server by using httpclient, however I cannot understand how to connect between app and the remote server.
Here is part of my code, and I matched id form inside "BasicNameValuePair" with html id values. Please let me know how to check whether login is successful or not.
class SendPost extends AsyncTask<Void, Void, String>
{
protected String doInBackground(Void... unused) {
String content = executeClient();
return content;
}
protected void onPostExecute(String result) {
}
public String executeClient() {
ArrayList<NameValuePair> post = new ArrayList<NameValuePair>();
post.add(new BasicNameValuePair("user_name", "SallyCook"));
post.add(new BasicNameValuePair("user_email", "domain#ppls.kr"));
post.add(new BasicNameValuePair("user_password", "add123456"));
post.add(new BasicNameValuePair("user_password_confirmation", "add123456"));
post.add(new BasicNameValuePair("user_phone", "01013089579"));
HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
System.out.println(params);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpPost httpPost = new HttpPost("http://www.ppls.kr/users/sign_up");
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(post, "UTF-8");
httpPost.setEntity(entity);
HttpResponse responsePost = client.execute(httpPost);
System.out.println(responsePost.getStatusLine());
HttpEntity resEntity=responsePost.getEntity();
if (resEntity != null) {
Log.w("RESPONSE", EntityUtils.toString(resEntity));
}
return EntityUtils.getContentCharSet(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

post data in json format to php script with java

I'm trying to POST data in JSON format to a script I have running PHP on my webserver. I have found this post: How to send data to a website using httpPost, app crashes.
Using the code he wrote (putting it on a separate thread first) I am able to post data to the PHP script, which accesses it by the $_POST variable. However, I wish to post my data in JSON format. I am guessing it would require me to post a raw stream of data to the server. What functions are available to achieve this? I would also need to post images as a stream of data to the PHP script so I think this solution will also help me in that area.
Additionally, what are the advantages of posting JSON to the server rather than using the method he used?
I am programming the client side in Java in conjunction with the Android SDK.
Any help would be appreciated.
I have a sample example for posting json data .
Have a look at this:
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private Context mContext;
private Intent mIntent;
private ProgressDialog pdLoading;
private class LoginTask extends AsyncTask<Void, Void, String>
{
private ArrayList<NameValuePair> mParams = new ArrayList<NameValuePair>();
private JSONArray mJArray = new JSONArray();
private JSONObject mJobject = new JSONObject();
private String jsonString = new String();
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.show();
}
#Override
protected String doInBackground(Void... params) {
try {
mJobject.put("userName", "test");
mJobject.put("password", "test");
mJArray.put(mJobject);
mParams.add(new BasicNameValuePair("message", mJArray.toString()));
jsonString = WebAPIRequest.postJsonData("http://putyoururlhere.com/login.php?", mParams);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return jsonString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdLoading.dismiss();
if(result!=null)
{
/* try {
mJobject = new JSONObject(jsonString);
if(mJobject.getString("Success").equals("True"))
{
mJArray = mJobject.getJSONArray("user");
JSONObject mUser = mJArray.getJSONObject(0);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Log.e(TAG, jsonString);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialization();
new LoginTask().execute();
}
private void initialization() {
mContext = this;
mIntent = new Intent();
pdLoading = new ProgressDialog(mContext);
pdLoading.setMessage("loading...");
}
}
and
public class WebAPIRequest {
public static String convertStreamToString(InputStream is)
throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
public static String postJsonData(String url, List<NameValuePair> params) {
String response_string = new String();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
try {
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String sampleurl = url + "" + paramString;
Log.e("Request_Url", "" + sampleurl);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
InputStream in = response.getEntity().getContent();
response_string = WebAPIRequest.convertStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return response_string;
}
}
EDIT :
try,
print_r(json_decode($_POST['message'], true);
or
$data = file_get_contents('php://input');
$json = json_decode($data,true);
I hope it will be helpful !!

What is the most efficient way on Android to call HTTP Web API calls that return a JSON response?

I'm the perfectionist type, I already got web API calls working fine with Google Places API (just as an example), but I feel it's sometimes slow or maybe I'm not doing it right. Some blogs are saying I should use AndroidHttpClient, but I'm not, should I ?
The web API calls i'm using return json and I don't run them on the UI thread, hence using AsyncTask (is AsyncTask the most efficient way to run on background thread or should I use something else ?)
Please see my code and tell me how could it be more efficient in anyway
public static class NearbySearchRequest extends AsyncTask<String, Void, JSONObject>
{
Exception mException = null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
this.mException = null;
}
#Override
protected JSONObject doInBackground(String... params)
{
StringBuilder urlString = new StringBuilder();
urlString.append("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
urlString.append("key=").append(Constants.GOOGLE_SIMPLE_API_KEY);
urlString.append("&location=").append(params[0]);
urlString.append("&sensor=").append("true");
urlString.append("&language=").append("en-GB");
urlString.append("&name=").append(params[1]);
urlString.append("&rankby=").append("distance");
LogHelper.Log(urlString.toString());
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
try
{
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = null;
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null)
response += temp;
bReader.close();
inStream.close();
urlConnection.disconnect();
object = (JSONObject) new JSONTokener(response).nextValue();
}
catch (Exception e)
{
this.mException = e;
}
return (object);
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
if (this.mException != null)
ErrorHelper.report(this.mException, "Error # NearbySearchRequest");
}
}
The Http engine you're using seems the best choice. Actually any other 3-rd party engines are based either on Apache, either on HttpUrlConnection. I prefer to use Spring for Android as that API provide an abstraction over Http Engine and you don't really need to care how about what API to use based on API level. Or you can use Volley - a very fashionable library.
I would touch however some of your code:
What if there is an exception while reading the stream? Then the stream remains open and also the connection. So I would suggest to have a finally block where the streams and connection is closed no matter if you get an exception or not:
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
InputStream inStream = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null) {
response += temp;
}
object = (JSONObject) new JSONTokener(response).nextValue();
} catch (Exception e) {
this.mException = e;
} finally {
if (inStream != null) {
try {
// this will close the bReader as well
inStream.close();
} catch (IOException ignored) {
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
JSON parsing: you're using the Android standard way of parsing JSON, but that's not the fastest and easiest to work with. GSON and Jackson are better to use. To make a comparison when it comes for JSON parsers, I would go for Jackson. Here's another SO topic on this comparison.
Don't concatenate strings like that as concatenating strings will create each time another string. Use a StringBuilder instead.
Exception handling (this is anyway a long-debate subject in all programming forums). First of all you have to log it (Use Log class not System.out.printXXX). Then you need to either inform the user: either you toast a message, either you show a label or notification. The decision depends on the user case and how relevant is the call you're making.
These are the topics I see in you code.
EDIT I realize I didn't answer this: is AsyncTask the most efficient way to run on background thread or should I use something else?
The short answer I would give is: if you're supposed to perform a short time lived request, then AsyncTask is perfect. However, if you need to get some data and display it - but you don't want to worry about whether to download again if the screen is rotated and so on, I would strongly recommend using an AsyncTaskLoader and Loaders in general.
If you need to download some big data, then either you use an IntentService or, for heavy-weight operations, DownloadManager.
Enjoy coding!
------Create a Service Handler Class to your Project--------
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
Log.e("in POST","in POST");
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
Log.e("in POST params","in POST params");
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
Log.e("url in post service",url);
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
Log.e("in GET","in GET");
if (params != null) {
Log.e("in GET params","in GET params");
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
Log.e("url in get service",url);
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public String makeServiceCallIMAGE(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
--------------AsyncTask For Login------------------
public class Login_Activity extends ActionBarActivity {
//Internet Service
NetworkConnection nw;
ProgressDialog prgDialog;
Boolean netConnection = false;
//
//Login API
String loginURL ="url";
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
nw = new NetworkConnection(getApplicationContext());
prgDialog = new ProgressDialog(this);
// Set Cancelable as False
prgDialog.setCancelable(false);
new LoginOperation().execute();
}
private class LoginOperation extends AsyncTask<String, Void, Void> {
String status, message;
#Override
protected void onPreExecute() {
// Set Progress Dialog Text
prgDialog.setMessage("Logging...");
prgDialog.show();
}
#Override
protected Void doInBackground(String... urls) {
if(nw.isConnectingToInternet() == true)
{
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "ClientesLogin"));
nameValuePairs.add(new BasicNameValuePair("Email", str_Email));
nameValuePairs.add(new BasicNameValuePair("Senha", str_Password));
ServiceHandler sh = new ServiceHandler();
String response = sh.makeServiceCall(loginURL, ServiceHandler.GET,
nameValuePairs);
Log.e("response", response);
JSONObject js = new JSONObject(response);
status = js.getString("status");
Log.e("status",status);
if(status.contains("Fail"))
{
message = js.getString("message");
}
/*else
{
JSONObject jslogin=js.getJSONObject("user_list");
for (int i = 0; i < jslogin.length(); i++) {
}
}*/
}catch(Exception ex){
}
netConnection = true;
}else
{
netConnection = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
prgDialog.dismiss();
if(netConnection == false)
{
Toast toast = Toast.makeText(getApplicationContext(),"Internet is not available. Please turn on and try again.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else
{
if(status.contains("Success"))
{
Toast toast = Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Intent i=new Intent(Login_Activity.this,home_page_activity.class);
startActivity(i);
}
else{
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
super.onPostExecute(result);
}
}
}
---------------Network Connection class---------------------
public class NetworkConnection {
Context context;
public NetworkConnection(Context context){
this.context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
JSONArray main1 = js.getJSONArray("Test 1");
for (int i = 0; i < main1.length(); i++) {
JSONObject jsonObject = main1.getJSONObject(i);

Categories